diff --git a/.config/CredScanSuppressions.json b/.config/CredScanSuppressions.json
index ccd35fe83c7..52381cb8b33 100644
--- a/.config/CredScanSuppressions.json
+++ b/.config/CredScanSuppressions.json
@@ -1,294 +1,294 @@
-{
- "tool": "Credential Scanner",
- "suppressions": [
- {
- "_justification": "This is a fake password used in test code.",
- "placeholder": [
- "aspnetcore"
- ]
- },
- {
- "_justification": "This is a fake password used in test code.",
- "placeholder": [
- "password"
- ]
- },
- {
- "_justification": "This is a fake password used in test code.",
- "placeholder": [
- "my password"
- ]
- },
- {
- "_justification": "This is a fake password used in test code.",
- "placeholder": [
- "newpassword"
- ]
- },
- {
- "_justification": "This is a fake password used in test code.",
- "placeholder": [
- "testpassword"
- ]
- },
- {
- "_justification": "This is a fake password hash used in test code.",
- "placeholder": [
- "AAABAgMEBQYHCAkKCwwNDg\u002BukCEMDf0yyQ29NYubggE="
- ]
- },
- {
- "_justification": "This is a fake password used in test code.",
- "placeholder": [
- "1qaz!QAZ"
- ]
- },
- {
- "_justification": "This is a fake password used in test code.",
- "placeholder": [
- "1qaz@WSX"
- ]
- },
- {
- "_justification": "Legitimate UT certificate file with private key",
- "file": [
- "/src/aspnetcore/src/Shared/TestCertificates/testCert.pfx"
- ]
- },
- {
- "_justification": "Legitimate UT certificate file with private key",
- "file": [
- "/src/aspnetcore/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/TestFiles/TestCert1.pfx"
- ]
- },
- {
- "_justification": "Legitimate UT certificate file with private key",
- "file": [
- "/src/aspnetcore/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/TestFiles/TestCert2.pfx"
- ]
- },
- {
- "_justification": "Legitimate UT certificate file with private key",
- "file": [
- "/src/aspnetcore/src/DataProtection/Extensions/test/TestFiles/TestCert.pfx"
- ]
- },
- {
- "_justification": "Legitimate UT certificate file with private key",
- "file": [
- "/src/aspnetcore/src/DataProtection/Extensions/test/TestFiles/TestCert2.pfx"
- ]
- },
- {
- "_justification": "Legitimate UT certificate file with private key",
- "file": [
- "/src/aspnetcore/src/DataProtection/Extensions/test/TestFiles/TestCert3.pfx"
- ]
- },
- {
- "_justification": "Legitimate UT certificate file without private key",
- "file": [
- "/src/aspnetcore/src/DataProtection/Extensions/test/TestFiles/TestCert3WithoutPrivateKey.pfx"
- ]
- },
- {
- "_justification": "Legitimate UT certificate file without private key",
- "file": [
- "/src/aspnetcore/src/DataProtection/Extensions/test/TestFiles/TestCertWithoutPrivateKey.pfx"
- ]
- },
- {
- "_justification": "Legitimate UT certificate file with private key",
- "file": [
- "/src/aspnetcore/src/DefaultBuilder/test/Microsoft.AspNetCore.FunctionalTests/testCert.pfx"
- ]
- },
- {
- "_justification": "Legitimate UT certificate file with private key",
- "file": [
- "/src/aspnetcore/src/Middleware/WebSockets/test/ConformanceTests/AutobahnTestApp/TestResources/testCert.pfx"
- ]
- },
- {
- "_justification": "Legitimate UT certificate file with private key",
- "file": [
- "/src/aspnetcore/src/Security/Authentication/Negotiate/test/Negotiate.FunctionalTest/negotiateAuthCert.pfx"
- ]
- },
- {
- "_justification": "Legitimate UT certificate file with private key",
- "file": [
- "/src/aspnetcore/src/Servers/IIS/tools/TestCert.pfx"
- ]
- },
- {
- "_justification": "Legitimate UT certificate file with private key",
- "file": [
- "/src/aspnetcore/src/Shared/TestCertificates/aspnetdevcert.pfx"
- ]
- },
- {
- "_justification": "Legitimate UT certificate file with private key",
- "file": [
- "/src/aspnetcore/src/Shared/TestCertificates/eku.client.pfx"
- ]
- },
- {
- "_justification": "Legitimate UT certificate file with private key",
- "file": [
- "/src/aspnetcore/src/Shared/TestCertificates/eku.code_signing.pfx"
- ]
- },
- {
- "_justification": "Legitimate UT certificate file with private key",
- "file": [
- "/src/aspnetcore/src/Shared/TestCertificates/eku.multiple_usages.pfx"
- ]
- },
- {
- "_justification": "Legitimate UT certificate file with private key",
- "file": [
- "/src/aspnetcore/src/Shared/TestCertificates/eku.server.pfx"
- ]
- },
- {
- "_justification": "Legitimate UT certificate file with private key",
- "file": [
- "/src/aspnetcore/src/Shared/TestCertificates/no_extensions.pfx"
- ]
- },
- {
- "_justification": "Legitimate UT certificate file with private key",
- "file": [
- "/src/aspnetcore/src/SignalR/common/Shared/testCert.pfx"
- ]
- },
- {
- "_justification": "Legitimate UT certificate file with private key",
- "file": [
- "/src/aspnetcore/src/SignalR/common/Shared/testCertECC.pfx"
- ]
- },
- {
- "_justification": "Legitimate key file used for testing",
- "file": [
- "/src/aspnetcore/src/Shared/TestCertificates/https-aspnet.key"
- ]
- },
- {
- "_justification": "Legitimate key file used for testing",
- "file": [
- "/src/aspnetcore/src/Shared/TestCertificates/https-dsa-protected.key"
- ]
- },
- {
- "_justification": "Legitimate key file used for testing",
- "file": [
- "/src/aspnetcore/src/Shared/TestCertificates/https-dsa.key"
- ]
- },
- {
- "_justification": "Legitimate key file used for testing",
- "file": [
- "/src/aspnetcore/src/Shared/TestCertificates/https-ecdsa-protected.key"
- ]
- },
- {
- "_justification": "Legitimate key file used for testing",
- "file": [
- "/src/aspnetcore/src/Shared/TestCertificates/https-ecdsa.key"
- ]
- },
- {
- "_justification": "Legitimate key file used for testing",
- "file": [
- "/src/aspnetcore/src/Shared/TestCertificates/https-rsa-protected.key"
- ]
- },
- {
- "_justification": "Legitimate key file used for testing",
- "file": [
- "/src/aspnetcore/src/Shared/TestCertificates/https-rsa.key"
- ]
- },
- {
- "_justification": "Legitimate key file used for testing",
- "file": [
- "/src/aspnetcore/src/Shared/TestCertificates/intermediate2_ca.key"
- ]
- },
- {
- "_justification": "Legitimate key file used for testing",
- "file": [
- "/src/aspnetcore/src/Shared/TestCertificates/intermediate_ca.key"
- ]
- },
- {
- "_justification": "Legitimate key file used for testing",
- "file": [
- "/src/aspnetcore/src/Shared/TestCertificates/leaf.com.key"
- ]
- },
- {
- "_justification": "Legitimate key file used for testing",
- "file": [
- "/src/aspnetcore/src/Shared/TestCertificates/root_ca.key"
- ]
- },
- {
- "_justification": "Legitimate key file used for testing",
- "file": [
- "/src/aspnetcore/src/SignalR/clients/ts/FunctionalTests/node_modules/https-proxy-agent/node_modules/agent-base/test/ssl-cert-snakeoil.key"
- ]
- },
- {
- "_justification": "New certificate file with private key used only for testing",
- "file": [
- "/src/msbuild/src/Tasks.UnitTests/TestResources/mycert.pfx"
- ]
- },
- {
- "_justification": "Unit tests use dummy input data.",
- "file": [
- "/src/nuget-client/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetCredentialsResponseTests.cs",
- "/src/nuget-client/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/SetCredentialsRequestTests.cs",
- "/src/nuget-client/docs/cross-platform-debugging.md"
- ]
- },
- {
- "_justification": "Suppression approved. Private key for testing purpose.",
- "placeholder": [
- "-----BEGIN PRIVATE KEY-----",
- "-----BEGIN * PRIVATE KEY-----"
- ],
- "file": [
- "/src/runtime/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSAKeyPemTests.cs",
- "/src/runtime/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyPemTests.cs",
- "/src/runtime/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAKeyPemTests.cs",
- "/src/runtime/src/libraries/Common/tests/System/Security/Cryptography/X509Certificates/TestData.cs",
- "/src/runtime/src/tests/FunctionalTests/Android/Device_Emulator/gRPC/grpc-dotnet/testassets/Certs/InteropTests/server1.key"
- ]
- },
- {
- "_justification": "Suppression approved. Private key for testing purpose.",
- "file": [
- "/src/runtime/src/tests/FunctionalTests/Android/Device_Emulator/gRPC/grpc-dotnet/testassets/Certs/InteropTests/server1.pfx"
- ]
- },
- {
- "_justification": "Third party repositories, no control over the content and these are not actual secrets.",
- "file": [
- "/src/source-build-reference-packages/src/externalPackages/src/azure-activedirectory-identitymodel-extensions-for-dotnet/test/Certs/SelfSigned1024_SHA1.pfx",
- "/src/source-build-reference-packages/src/externalPackages/src/azure-activedirectory-identitymodel-extensions-for-dotnet/test/Certs/SelfSigned1024_SHA256.pfx",
- "/src/source-build-reference-packages/src/externalPackages/src/azure-activedirectory-identitymodel-extensions-for-dotnet/test/Certs/SelfSigned2048_SHA256.pfx",
- "/src/source-build-reference-packages/src/externalPackages/src/azure-activedirectory-identitymodel-extensions-for-dotnet/test/Certs/SelfSigned2048_SHA256_2.pfx",
- "/src/source-build-reference-packages/src/externalPackages/src/azure-activedirectory-identitymodel-extensions-for-dotnet/test/Certs/SelfSigned2048_SHA384.pfx",
- "/src/source-build-reference-packages/src/externalPackages/src/azure-activedirectory-identitymodel-extensions-for-dotnet/test/Certs/SelfSigned2048_SHA512.pfx",
- "/src/source-build-reference-packages/src/externalPackages/src/azure-activedirectory-identitymodel-extensions-for-dotnet/test/Microsoft.IdentityModel.TestUtils/KeyingMaterial.cs",
- "/src/source-build-reference-packages/src/externalPackages/src/humanizer/src/Humanizer.Tests.Uwp/Humanizer.Tests.Uwp_TemporaryKey.pfx",
- "/src/source-build-reference-packages/src/externalPackages/src/humanizer/src/Humanizer.Tests.Uwp.Runner/Humanizer.Tests.Uwp.Runner_TemporaryKey.pfx",
- "/src/source-build-reference-packages/src/externalPackages/src/xunit/appveyor.yml"
- ]
- }
- ]
+{
+ "tool": "Credential Scanner",
+ "suppressions": [
+ {
+ "_justification": "This is a fake password used in test code.",
+ "placeholder": [
+ "aspnetcore"
+ ]
+ },
+ {
+ "_justification": "This is a fake password used in test code.",
+ "placeholder": [
+ "password"
+ ]
+ },
+ {
+ "_justification": "This is a fake password used in test code.",
+ "placeholder": [
+ "my password"
+ ]
+ },
+ {
+ "_justification": "This is a fake password used in test code.",
+ "placeholder": [
+ "newpassword"
+ ]
+ },
+ {
+ "_justification": "This is a fake password used in test code.",
+ "placeholder": [
+ "testpassword"
+ ]
+ },
+ {
+ "_justification": "This is a fake password hash used in test code.",
+ "placeholder": [
+ "AAABAgMEBQYHCAkKCwwNDg\u002BukCEMDf0yyQ29NYubggE="
+ ]
+ },
+ {
+ "_justification": "This is a fake password used in test code.",
+ "placeholder": [
+ "1qaz!QAZ"
+ ]
+ },
+ {
+ "_justification": "This is a fake password used in test code.",
+ "placeholder": [
+ "1qaz@WSX"
+ ]
+ },
+ {
+ "_justification": "Legitimate UT certificate file with private key",
+ "file": [
+ "/src/aspnetcore/src/Shared/TestCertificates/testCert.pfx"
+ ]
+ },
+ {
+ "_justification": "Legitimate UT certificate file with private key",
+ "file": [
+ "/src/aspnetcore/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/TestFiles/TestCert1.pfx"
+ ]
+ },
+ {
+ "_justification": "Legitimate UT certificate file with private key",
+ "file": [
+ "/src/aspnetcore/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/TestFiles/TestCert2.pfx"
+ ]
+ },
+ {
+ "_justification": "Legitimate UT certificate file with private key",
+ "file": [
+ "/src/aspnetcore/src/DataProtection/Extensions/test/TestFiles/TestCert.pfx"
+ ]
+ },
+ {
+ "_justification": "Legitimate UT certificate file with private key",
+ "file": [
+ "/src/aspnetcore/src/DataProtection/Extensions/test/TestFiles/TestCert2.pfx"
+ ]
+ },
+ {
+ "_justification": "Legitimate UT certificate file with private key",
+ "file": [
+ "/src/aspnetcore/src/DataProtection/Extensions/test/TestFiles/TestCert3.pfx"
+ ]
+ },
+ {
+ "_justification": "Legitimate UT certificate file without private key",
+ "file": [
+ "/src/aspnetcore/src/DataProtection/Extensions/test/TestFiles/TestCert3WithoutPrivateKey.pfx"
+ ]
+ },
+ {
+ "_justification": "Legitimate UT certificate file without private key",
+ "file": [
+ "/src/aspnetcore/src/DataProtection/Extensions/test/TestFiles/TestCertWithoutPrivateKey.pfx"
+ ]
+ },
+ {
+ "_justification": "Legitimate UT certificate file with private key",
+ "file": [
+ "/src/aspnetcore/src/DefaultBuilder/test/Microsoft.AspNetCore.FunctionalTests/testCert.pfx"
+ ]
+ },
+ {
+ "_justification": "Legitimate UT certificate file with private key",
+ "file": [
+ "/src/aspnetcore/src/Middleware/WebSockets/test/ConformanceTests/AutobahnTestApp/TestResources/testCert.pfx"
+ ]
+ },
+ {
+ "_justification": "Legitimate UT certificate file with private key",
+ "file": [
+ "/src/aspnetcore/src/Security/Authentication/Negotiate/test/Negotiate.FunctionalTest/negotiateAuthCert.pfx"
+ ]
+ },
+ {
+ "_justification": "Legitimate UT certificate file with private key",
+ "file": [
+ "/src/aspnetcore/src/Servers/IIS/tools/TestCert.pfx"
+ ]
+ },
+ {
+ "_justification": "Legitimate UT certificate file with private key",
+ "file": [
+ "/src/aspnetcore/src/Shared/TestCertificates/aspnetdevcert.pfx"
+ ]
+ },
+ {
+ "_justification": "Legitimate UT certificate file with private key",
+ "file": [
+ "/src/aspnetcore/src/Shared/TestCertificates/eku.client.pfx"
+ ]
+ },
+ {
+ "_justification": "Legitimate UT certificate file with private key",
+ "file": [
+ "/src/aspnetcore/src/Shared/TestCertificates/eku.code_signing.pfx"
+ ]
+ },
+ {
+ "_justification": "Legitimate UT certificate file with private key",
+ "file": [
+ "/src/aspnetcore/src/Shared/TestCertificates/eku.multiple_usages.pfx"
+ ]
+ },
+ {
+ "_justification": "Legitimate UT certificate file with private key",
+ "file": [
+ "/src/aspnetcore/src/Shared/TestCertificates/eku.server.pfx"
+ ]
+ },
+ {
+ "_justification": "Legitimate UT certificate file with private key",
+ "file": [
+ "/src/aspnetcore/src/Shared/TestCertificates/no_extensions.pfx"
+ ]
+ },
+ {
+ "_justification": "Legitimate UT certificate file with private key",
+ "file": [
+ "/src/aspnetcore/src/SignalR/common/Shared/testCert.pfx"
+ ]
+ },
+ {
+ "_justification": "Legitimate UT certificate file with private key",
+ "file": [
+ "/src/aspnetcore/src/SignalR/common/Shared/testCertECC.pfx"
+ ]
+ },
+ {
+ "_justification": "Legitimate key file used for testing",
+ "file": [
+ "/src/aspnetcore/src/Shared/TestCertificates/https-aspnet.key"
+ ]
+ },
+ {
+ "_justification": "Legitimate key file used for testing",
+ "file": [
+ "/src/aspnetcore/src/Shared/TestCertificates/https-dsa-protected.key"
+ ]
+ },
+ {
+ "_justification": "Legitimate key file used for testing",
+ "file": [
+ "/src/aspnetcore/src/Shared/TestCertificates/https-dsa.key"
+ ]
+ },
+ {
+ "_justification": "Legitimate key file used for testing",
+ "file": [
+ "/src/aspnetcore/src/Shared/TestCertificates/https-ecdsa-protected.key"
+ ]
+ },
+ {
+ "_justification": "Legitimate key file used for testing",
+ "file": [
+ "/src/aspnetcore/src/Shared/TestCertificates/https-ecdsa.key"
+ ]
+ },
+ {
+ "_justification": "Legitimate key file used for testing",
+ "file": [
+ "/src/aspnetcore/src/Shared/TestCertificates/https-rsa-protected.key"
+ ]
+ },
+ {
+ "_justification": "Legitimate key file used for testing",
+ "file": [
+ "/src/aspnetcore/src/Shared/TestCertificates/https-rsa.key"
+ ]
+ },
+ {
+ "_justification": "Legitimate key file used for testing",
+ "file": [
+ "/src/aspnetcore/src/Shared/TestCertificates/intermediate2_ca.key"
+ ]
+ },
+ {
+ "_justification": "Legitimate key file used for testing",
+ "file": [
+ "/src/aspnetcore/src/Shared/TestCertificates/intermediate_ca.key"
+ ]
+ },
+ {
+ "_justification": "Legitimate key file used for testing",
+ "file": [
+ "/src/aspnetcore/src/Shared/TestCertificates/leaf.com.key"
+ ]
+ },
+ {
+ "_justification": "Legitimate key file used for testing",
+ "file": [
+ "/src/aspnetcore/src/Shared/TestCertificates/root_ca.key"
+ ]
+ },
+ {
+ "_justification": "Legitimate key file used for testing",
+ "file": [
+ "/src/aspnetcore/src/SignalR/clients/ts/FunctionalTests/node_modules/https-proxy-agent/node_modules/agent-base/test/ssl-cert-snakeoil.key"
+ ]
+ },
+ {
+ "_justification": "New certificate file with private key used only for testing",
+ "file": [
+ "/src/msbuild/src/Tasks.UnitTests/TestResources/mycert.pfx"
+ ]
+ },
+ {
+ "_justification": "Unit tests use dummy input data.",
+ "file": [
+ "/src/nuget-client/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetCredentialsResponseTests.cs",
+ "/src/nuget-client/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/SetCredentialsRequestTests.cs",
+ "/src/nuget-client/docs/cross-platform-debugging.md"
+ ]
+ },
+ {
+ "_justification": "Suppression approved. Private key for testing purpose.",
+ "placeholder": [
+ "-----BEGIN PRIVATE KEY-----",
+ "-----BEGIN * PRIVATE KEY-----"
+ ],
+ "file": [
+ "/src/runtime/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSAKeyPemTests.cs",
+ "/src/runtime/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyPemTests.cs",
+ "/src/runtime/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAKeyPemTests.cs",
+ "/src/runtime/src/libraries/Common/tests/System/Security/Cryptography/X509Certificates/TestData.cs",
+ "/src/runtime/src/tests/FunctionalTests/Android/Device_Emulator/gRPC/grpc-dotnet/testassets/Certs/InteropTests/server1.key"
+ ]
+ },
+ {
+ "_justification": "Suppression approved. Private key for testing purpose.",
+ "file": [
+ "/src/runtime/src/tests/FunctionalTests/Android/Device_Emulator/gRPC/grpc-dotnet/testassets/Certs/InteropTests/server1.pfx"
+ ]
+ },
+ {
+ "_justification": "Third party repositories, no control over the content and these are not actual secrets.",
+ "file": [
+ "/src/source-build-reference-packages/src/externalPackages/src/azure-activedirectory-identitymodel-extensions-for-dotnet/test/Certs/SelfSigned1024_SHA1.pfx",
+ "/src/source-build-reference-packages/src/externalPackages/src/azure-activedirectory-identitymodel-extensions-for-dotnet/test/Certs/SelfSigned1024_SHA256.pfx",
+ "/src/source-build-reference-packages/src/externalPackages/src/azure-activedirectory-identitymodel-extensions-for-dotnet/test/Certs/SelfSigned2048_SHA256.pfx",
+ "/src/source-build-reference-packages/src/externalPackages/src/azure-activedirectory-identitymodel-extensions-for-dotnet/test/Certs/SelfSigned2048_SHA256_2.pfx",
+ "/src/source-build-reference-packages/src/externalPackages/src/azure-activedirectory-identitymodel-extensions-for-dotnet/test/Certs/SelfSigned2048_SHA384.pfx",
+ "/src/source-build-reference-packages/src/externalPackages/src/azure-activedirectory-identitymodel-extensions-for-dotnet/test/Certs/SelfSigned2048_SHA512.pfx",
+ "/src/source-build-reference-packages/src/externalPackages/src/azure-activedirectory-identitymodel-extensions-for-dotnet/test/Microsoft.IdentityModel.TestUtils/KeyingMaterial.cs",
+ "/src/source-build-reference-packages/src/externalPackages/src/humanizer/src/Humanizer.Tests.Uwp/Humanizer.Tests.Uwp_TemporaryKey.pfx",
+ "/src/source-build-reference-packages/src/externalPackages/src/humanizer/src/Humanizer.Tests.Uwp.Runner/Humanizer.Tests.Uwp.Runner_TemporaryKey.pfx",
+ "/src/source-build-reference-packages/src/externalPackages/src/xunit/appveyor.yml"
+ ]
+ }
+ ]
}
\ No newline at end of file
diff --git a/src/roslyn/.vscode/tasks.json b/src/roslyn/.vscode/tasks.json
index eecd040d5dd..1c6757b1fe5 100644
--- a/src/roslyn/.vscode/tasks.json
+++ b/src/roslyn/.vscode/tasks.json
@@ -132,8 +132,9 @@
"command": "dotnet",
"type": "shell",
"args": [
- "pwsh",
- "${workspaceFolder}/eng/generate-compiler-code.ps1"
+ "run",
+ "--file",
+ "${workspaceFolder}/eng/generate-compiler-code.cs"
],
"problemMatcher": "$msCompile",
"group": "build"
diff --git a/src/roslyn/Directory.Packages.props b/src/roslyn/Directory.Packages.props
index e3e2abfdd7e..9f2e5ffec10 100644
--- a/src/roslyn/Directory.Packages.props
+++ b/src/roslyn/Directory.Packages.props
@@ -3,5 +3,5 @@
true
true
-
-
\ No newline at end of file
+
+
diff --git a/src/roslyn/azure-pipelines-official.yml b/src/roslyn/azure-pipelines-official.yml
index b3869f8e8ae..453850201fb 100644
--- a/src/roslyn/azure-pipelines-official.yml
+++ b/src/roslyn/azure-pipelines-official.yml
@@ -112,6 +112,8 @@ extends:
parameters:
featureFlags:
autoBaseline: true
+ autoEnablePREfastWithNewRuleset: false
+ autoEnableRoslynWithNewRuleset: false
sdl:
sourceAnalysisPool:
name: NetCore1ESPool-Svc-Internal
@@ -288,13 +290,13 @@ extends:
- task: MicroBuildSigningPlugin@4
inputs:
- signType: $(SignType)
+ signType: ${{ parameters.SignType }}
zipSources: false
feedSource: https://dnceng.pkgs.visualstudio.com/_packaging/MicroBuildToolset/nuget/v3/index.json
# Set ConnectedPMEServiceName if the build is a CI build, otherwise it is not needed
${{ if eq(variables['Build.Reason'], 'IndividualCI') }}:
ConnectedPMEServiceName: 248d384a-b39b-46e3-8ad5-c2c210d5e7ca
- condition: and(succeeded(), in(variables['SignType'], 'test', 'real'))
+ condition: and(succeeded(), in('${{ parameters.SignType }}', 'test', 'real'))
- download: profilingInputs
artifact: merged mibc
@@ -322,7 +324,7 @@ extends:
/p:RepositoryName=$(Build.Repository.Name)
/p:VisualStudioDropName=$(VisualStudio.DropName)
/p:VSCodeOptimizationDataRoot="$(VSCodeOptimizationDataRoot)"
- /p:DotNetSignType=$(SignType)
+ /p:DotNetSignType=${{ parameters.SignType }}
/p:DotnetPublishUsingPipelines=true
/p:IgnoreIbcMergeErrors=true
/p:GenerateSbom=true
@@ -401,7 +403,7 @@ extends:
componentPassword: $(dn-bot-dnceng-build-e-code-full-release-e-packaging-r)
componentBuildProjectName: internal
sourceBranch: "$(ComponentBranchName)"
- publishDataURI: "https://dev.azure.com/dnceng/internal/_apis/git/repositories/dotnet-roslyn/items?path=eng/config/PublishData.json&api-version=6.0"
+ publishDataURI: "https://dev.azure.com/dnceng/internal/_apis/git/repositories/dotnet-roslyn/items?path=eng/config/PublishData.json&version=$(ComponentBranchName)&api-version=6.0"
publishDataAccessToken: "$(System.AccessToken)"
dropPath: '$(Pipeline.Workspace)\VSSetup'
cherryPick: ${{ parameters.VisualStudioCherryPickSHA }}
@@ -410,9 +412,6 @@ extends:
- template: /eng/common/templates-official/post-build/post-build.yml@self
parameters:
publishingInfraVersion: 3
- # Symbol validation is not entirely reliable as of yet, so should be turned off until
- # https://github.com/dotnet/arcade/issues/2871 is resolved.
- enableSymbolValidation: false
enableSourceLinkValidation: false
# Enable SDL validation, passing through values from the 'DotNet-Roslyn-SDLValidation-Params' group.
SDLValidationParameters:
diff --git a/src/roslyn/azure-pipelines-pr-validation.yml b/src/roslyn/azure-pipelines-pr-validation.yml
index 427f87827e3..19e627450bd 100644
--- a/src/roslyn/azure-pipelines-pr-validation.yml
+++ b/src/roslyn/azure-pipelines-pr-validation.yml
@@ -357,7 +357,7 @@ extends:
vsBranchName: ${{ parameters.VisualStudioBranchName }}
titlePrefix: ${{ parameters.OptionalTitlePrefix }}
sourceBranch: $(ComponentBranchName)
- publishDataURI: "https://raw.githubusercontent.com/dotnet/roslyn/main/eng/config/PublishData.json"
+ publishDataURI: "https://raw.githubusercontent.com/dotnet/roslyn/$(ComponentBranchName)/eng/config/PublishData.json"
queueSpeedometerValidation: true
dropPath: '$(Pipeline.Workspace)\VSSetup'
retainInsertedBuild: false
diff --git a/src/roslyn/azure-pipelines.yml b/src/roslyn/azure-pipelines.yml
index d2d30e15a4a..df8d9cb182a 100644
--- a/src/roslyn/azure-pipelines.yml
+++ b/src/roslyn/azure-pipelines.yml
@@ -125,6 +125,10 @@ parameters:
default:
name: $(PoolName)
demands: ImageOverride -equals $(WindowsQueueName)
+ - name: macOSPool
+ type: object
+ default:
+ vmImage: macOS-15
- name: vs2022PreviewPool
type: object
default:
@@ -170,6 +174,16 @@ stages:
testArtifactName: Transport_Artifacts_Unix_Debug
poolParameters: ${{ parameters.ubuntuPool }}
+- ${{ if ne(variables['Build.Reason'], 'PullRequest') }}:
+ - stage: MacOS_Build
+ dependsOn: []
+ jobs:
+ - template: eng/pipelines/build-unix-job.yml
+ parameters:
+ jobName: Build_macOS_Debug
+ testArtifactName: Transport_Artifacts_macOS_Debug
+ poolParameters: ${{ parameters.macOSPool }}
+
- stage: Source_Build
dependsOn: []
jobs:
@@ -370,14 +384,19 @@ stages:
testArguments: --testCoreClr
poolParameters: ${{ parameters.ubuntuPool }}
- # https://github.com/dotnet/runtime/issues/97186
- # Disabled until runtime can track down the crash
- - ${{ if ne(variables['Build.Reason'], 'PullRequest') }}:
+- ${{ if ne(variables['Build.Reason'], 'PullRequest') }}:
+ - stage: MacOS_Debug_CoreClr
+ dependsOn: MacOS_Build
+ variables:
+ - ${{ if ne(variables['System.TeamProject'], 'public') }}:
+ - group: DotNet-HelixApi-Access
+ jobs:
+ # https://github.com/dotnet/runtime/issues/97186
- template: eng/pipelines/test-unix-job.yml
parameters:
testRunName: 'Test macOS Debug'
jobName: Test_macOS_Debug
- testArtifactName: Transport_Artifacts_Unix_Debug
+ testArtifactName: Transport_Artifacts_macOS_Debug
configuration: Debug
testArguments: --testCoreClr
helixQueueName: $(HelixMacOsQueueName)
@@ -446,8 +465,12 @@ stages:
- powershell: eng/validate-rules-missing-documentation.ps1 -ci
displayName: Validate rules missing documentation
- - powershell: eng/generate-compiler-code.ps1 -test -configuration Release
+ - task: DotNetCoreCLI@2
displayName: Generate Syntax Files
+ inputs:
+ command: 'custom'
+ custom: 'run'
+ arguments: '--file $(Build.SourcesDirectory)/eng/generate-compiler-code.cs -- -test -configuration Release'
- powershell: eng/validate-code-formatting.ps1 -ci -rootDirectory $(Build.SourcesDirectory)\src -includeDirectories Compilers\CSharp\Portable\Generated\, Compilers\VisualBasic\Portable\Generated\, ExpressionEvaluator\VisualBasic\Source\ResultProvider\Generated\
displayName: Validate Generated Syntax Files
diff --git a/src/roslyn/docs/compilers/CSharp/Compiler Breaking Changes - DotNet 10.md b/src/roslyn/docs/compilers/CSharp/Compiler Breaking Changes - DotNet 10.md
index 816c2435e2a..53e5dc91ef7 100644
--- a/src/roslyn/docs/compilers/CSharp/Compiler Breaking Changes - DotNet 10.md
+++ b/src/roslyn/docs/compilers/CSharp/Compiler Breaking Changes - DotNet 10.md
@@ -7,7 +7,7 @@ This document lists known breaking changes in Roslyn after .NET 9 general releas
***Introduced in Visual Studio 2022 version 17.13***
C# 14 introduces the ability to write a lambda with parameter modifiers, without having to specify a parameter type:
-https://github.com/dotnet/csharplang/blob/main/proposals/simple-lambda-parameters-with-modifiers.md
+[Simple lambda parameters with modifiers](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-14.0/simple-lambda-parameters-with-modifiers.md)
As part of this work, a breaking change was accepted where `scoped` will always be treated as a modifier
in a lambda parameter, even where it might have been accepted as a type name in the past. For example:
@@ -371,7 +371,7 @@ class C { } // type parameter may not be named "extension"
## Partial properties and events are now implicitly virtual and public
-***Introduced in Visual Studio 2022 version 17.15***
+***Introduced in Visual Studio 2026 version 18.0 preview 1***
We have fixed [an inconsistency](https://github.com/dotnet/roslyn/issues/77346)
where partial interface properties and events would not be implicitly `virtual` and `public` unlike their non-partial equivalents.
@@ -407,3 +407,30 @@ partial interface I
class C : I;
```
+
+## Missing `ParamCollectionAttribute` is reported in more cases
+
+***Introduced in Visual Studio 2026 version 18.0***
+
+If you are compiling a `.netmodule` (note that this doesn't apply to normal DLL/EXE compilations),
+and have a lambda or a local function with a `params` collection parameter,
+and the `ParamCollectionAttribute` is not found, a compilation error is now reported
+(because the attribute now must be [emitted](https://github.com/dotnet/roslyn/issues/79752) on the synthesized method
+but the attribute type itself is not synthesized by the compiler into a `.netmodule`).
+You can work around that by defining the attribute yourself.
+
+```cs
+using System;
+using System.Collections.Generic;
+class C
+{
+ void M()
+ {
+ Func, int> lam = (params IList xs) => xs.Count; // error if ParamCollectionAttribute does not exist
+ lam([1, 2, 3]);
+
+ int func(params IList xs) => xs.Count; // error if ParamCollectionAttribute does not exist
+ func(4, 5, 6);
+ }
+}
+```
diff --git a/src/roslyn/docs/contributing/Compiler Test Plan.md b/src/roslyn/docs/contributing/Compiler Test Plan.md
index bc9d292891d..00098c2fa22 100644
--- a/src/roslyn/docs/contributing/Compiler Test Plan.md
+++ b/src/roslyn/docs/contributing/Compiler Test Plan.md
@@ -9,7 +9,7 @@ This document provides guidance for thinking about language interactions and tes
- BCL (including mono) and other customer impact
- Determinism
- Loading from metadata (source vs. loaded from metadata)
-- Public interface of compiler APIs (including semantic model APIs listed below):
+- Public compiler APIs (including semantic model and other APIs listed below):
- GetDeclaredSymbol
- GetEnclosingSymbol
- GetSymbolInfo
@@ -29,12 +29,21 @@ This document provides guidance for thinking about language interactions and tes
- ClassifyConversion
- GetOperation (`IOperation`)
- GetCFG (`ControlFlowGraph`)
+ - DocumentationCommentId APIs
- VB/F# interop
- C++/CLI interop (particularly for metadata format changes, e.g. DIMs, static abstracts in interfaces, or generic attributes)
- Performance and stress testing
- Can build VS
- Check that `Obsolete` is honored for members used in binding/lowering
- LangVersion
+
+- Does the feature use cryptographic hashes in any way? (examples: metadata names of file-local types, extension types, assembly strong naming, PDB document table, etc.)
+ - Consider using non-cryptographic hash such as `XxHash128` instead.
+ - If you must use a cryptographic hash in the feature implementation, then use `SourceHashAlgorithms.Default`, and not any specific hash.
+ - A cryptographic hash must never be included in a public API name. Taking a change to the default crypto algorithm would then change public API surface, which would be enormously breaking.
+ - **DO NOT** allow using the value of a crypto hash in a field, method or type name
+ - **DO** allow using the value of a crypto hash in attribute or field values
+ - Any time the compiler reads in metadata containing crypto hashes, even if it's an attribute value, ensure the crypto hash algorithm name is included in the metadata (e.g. prefixing it to the hash value), so that it can be changed over time and the compiler can continue to read both metadata using both the old and new algorithms.
# Type and members
- Access modifiers (public, protected, internal, protected internal, private protected, private), static, ref
diff --git a/src/roslyn/eng/Directory.Packages.props b/src/roslyn/eng/Directory.Packages.props
index 1e8a1d46394..3ed04d2188b 100644
--- a/src/roslyn/eng/Directory.Packages.props
+++ b/src/roslyn/eng/Directory.Packages.props
@@ -1,339 +1,6 @@
-
-
-
- 3.11.0-beta1.24081.1
- 1.1.3-beta1.24319.1
- 0.1.800-beta
- <_BasicReferenceAssembliesVersion>1.8.3
-
- 4.8.0-3.final
- 18.0.332-preview
- 9.0.0-rc.2.24462.10
- 6.0.0-rtm.21518.12
- 7.0.0-alpha.1.22060.1
-
- 8.0.10
- 8.0.10
- <_xunitVersion>2.9.2
- 2.1.0
-
- 2.14.1
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+Please remove this file during conflict resolution in your PR.
+This file has been reverted (removed) in the source repository but the PR branch
+does not have the file yet as it's based on an older commit. This means the file is
+not getting removed in the PR due to the other conflicts.
\ No newline at end of file
diff --git a/src/roslyn/eng/Packages.props b/src/roslyn/eng/Packages.props
new file mode 100644
index 00000000000..37ee560eb8a
--- /dev/null
+++ b/src/roslyn/eng/Packages.props
@@ -0,0 +1,341 @@
+
+
+
+ 3.11.0-beta1.24081.1
+ 1.1.3-beta1.24319.1
+ 0.1.800-beta
+ <_BasicReferenceAssembliesVersion>1.8.3
+
+ 4.8.0-3.final
+ 18.0.332-preview
+ 9.0.0-rc.2.24462.10
+ 6.0.0-rtm.21518.12
+ 7.0.0-alpha.1.22060.1
+
+ 8.0.10
+ 8.0.10
+ <_xunitVersion>2.9.2
+ 2.1.0
+
+ 2.14.1
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/roslyn/eng/Version.Details.props b/src/roslyn/eng/Version.Details.props
index 964378c8f4f..5414f6197a8 100644
--- a/src/roslyn/eng/Version.Details.props
+++ b/src/roslyn/eng/Version.Details.props
@@ -9,7 +9,7 @@ This file should be imported by eng/Versions.props
3.11.0
4.10.0-1.24061.4
- 2.0.0-rc.2.25427.104
+ 2.0.0-rc.2.25468.104
9.0.0
9.0.0
@@ -38,9 +38,9 @@ This file should be imported by eng/Versions.props
9.0.0
9.0.0
- 10.0.0-beta.25427.2
- 10.0.0-beta.25427.2
- 10.0.0-beta.25427.2
+ 11.0.0-beta.25469.3
+ 11.0.0-beta.25469.3
+ 11.0.0-beta.25469.3
2.0.0
diff --git a/src/roslyn/eng/Version.Details.xml b/src/roslyn/eng/Version.Details.xml
index 6792bd1be72..25c49fa8f16 100644
--- a/src/roslyn/eng/Version.Details.xml
+++ b/src/roslyn/eng/Version.Details.xml
@@ -1,15 +1,15 @@
-
+
https://github.com/dotnet/roslyn
ae1fff344d46976624e68ae17164e0607ab68b10
-
+
https://github.com/dotnet/dotnet
- 7ac1ca67bb1fb8a381c1c94a9f82a97725f0ccf3
+ 2dea164f01d307c409cfe0d0ee5cb8a0691e3c94
@@ -115,13 +115,13 @@
-
+
https://github.com/dotnet/arcade
- ee3cae9ed3ef1990505e891831163ef34220d4e0
+ dbc4dce57f6a2087f13d86e89dfb0334be3c42e2
-
+
https://github.com/dotnet/arcade
- ee3cae9ed3ef1990505e891831163ef34220d4e0
+ dbc4dce57f6a2087f13d86e89dfb0334be3c42e2
https://github.com/dotnet/symreader
@@ -131,9 +131,9 @@
https://github.com/dotnet/roslyn
5d10d428050c0d6afef30a072c4ae68776621877
-
+
https://github.com/dotnet/arcade
- ee3cae9ed3ef1990505e891831163ef34220d4e0
+ dbc4dce57f6a2087f13d86e89dfb0334be3c42e2
https://github.com/dotnet/roslyn-analyzers
diff --git a/src/roslyn/eng/Versions.props b/src/roslyn/eng/Versions.props
index aec4f310cca..25a52871980 100644
--- a/src/roslyn/eng/Versions.props
+++ b/src/roslyn/eng/Versions.props
@@ -100,6 +100,17 @@
+
+
+ 17.10.29
+ 8.0.5
+
true
false
diff --git a/src/roslyn/eng/build-utils.ps1 b/src/roslyn/eng/build-utils.ps1
index 64dd3a3d343..ba679ba8beb 100644
--- a/src/roslyn/eng/build-utils.ps1
+++ b/src/roslyn/eng/build-utils.ps1
@@ -8,7 +8,6 @@ $ErrorActionPreference="Stop"
$VSSetupDir = Join-Path $ArtifactsDir "VSSetup\$configuration"
$PackagesDir = Join-Path $ArtifactsDir "packages\$configuration"
-$PublishDataUrl = "https://raw.githubusercontent.com/dotnet/roslyn/main/eng/config/PublishData.json"
$binaryLog = if (Test-Path variable:binaryLog) { $binaryLog } else { $false }
$nodeReuse = if (Test-Path variable:nodeReuse) { $nodeReuse } else { $false }
@@ -27,8 +26,10 @@ function GetPublishData() {
return $global:_PublishData
}
- Write-Host "Downloading $PublishDataUrl"
- $content = (Invoke-WebRequest -Uri $PublishDataUrl -UseBasicParsing).Content
+ $publishDataFile = Join-Path $PSScriptRoot "config\PublishData.json"
+
+ Write-Host "Reading $publishDataFile"
+ $content = Get-Content -Path $publishDataFile -Raw
return $global:_PublishData = ConvertFrom-Json $content
}
diff --git a/src/roslyn/eng/build.sh b/src/roslyn/eng/build.sh
index caf46e4825c..a87e4b2a131 100755
--- a/src/roslyn/eng/build.sh
+++ b/src/roslyn/eng/build.sh
@@ -341,6 +341,7 @@ function GetCompilerTestAssembliesIncludePaths {
assemblies+=" --include '^Microsoft\.CodeAnalysis\.VisualBasic\.Emit\.UnitTests$'"
assemblies+=" --include '^Roslyn\.Compilers\.VisualBasic\.IOperation\.UnitTests$'"
assemblies+=" --include '^Microsoft\.CodeAnalysis\.VisualBasic\.CommandLine\.UnitTests$'"
+ assemblies+=" --include '^Microsoft\.Build\.Tasks\.CodeAnalysis\.UnitTests$'"
echo "$assemblies"
}
diff --git a/src/roslyn/eng/common/SetupNugetSources.ps1 b/src/roslyn/eng/common/SetupNugetSources.ps1
index 792b60b49d4..9445c314325 100644
--- a/src/roslyn/eng/common/SetupNugetSources.ps1
+++ b/src/roslyn/eng/common/SetupNugetSources.ps1
@@ -157,7 +157,7 @@ if ($dotnet31Source -ne $null) {
AddPackageSource -Sources $sources -SourceName "dotnet3.1-internal-transport" -SourceEndPoint "https://pkgs.dev.azure.com/dnceng/_packaging/dotnet3.1-internal-transport/nuget/v2" -Creds $creds -Username $userName -pwd $Password
}
-$dotnetVersions = @('5','6','7','8','9')
+$dotnetVersions = @('5','6','7','8','9','10')
foreach ($dotnetVersion in $dotnetVersions) {
$feedPrefix = "dotnet" + $dotnetVersion;
diff --git a/src/roslyn/eng/common/SetupNugetSources.sh b/src/roslyn/eng/common/SetupNugetSources.sh
index facb415ca6f..ddf4efc81a4 100644
--- a/src/roslyn/eng/common/SetupNugetSources.sh
+++ b/src/roslyn/eng/common/SetupNugetSources.sh
@@ -99,7 +99,7 @@ if [ "$?" == "0" ]; then
PackageSources+=('dotnet3.1-internal-transport')
fi
-DotNetVersions=('5' '6' '7' '8' '9')
+DotNetVersions=('5' '6' '7' '8' '9' '10')
for DotNetVersion in ${DotNetVersions[@]} ; do
FeedPrefix="dotnet${DotNetVersion}";
diff --git a/src/roslyn/eng/common/core-templates/job/publish-build-assets.yml b/src/roslyn/eng/common/core-templates/job/publish-build-assets.yml
index 348cd16376f..37dff559fc1 100644
--- a/src/roslyn/eng/common/core-templates/job/publish-build-assets.yml
+++ b/src/roslyn/eng/common/core-templates/job/publish-build-assets.yml
@@ -40,6 +40,8 @@ parameters:
repositoryAlias: self
+ officialBuildId: ''
+
jobs:
- job: Asset_Registry_Publish
@@ -62,6 +64,11 @@ jobs:
value: false
# unconditional - needed for logs publishing (redactor tool version)
- template: /eng/common/core-templates/post-build/common-variables.yml
+ - name: OfficialBuildId
+ ${{ if ne(parameters.officialBuildId, '') }}:
+ value: ${{ parameters.officialBuildId }}
+ ${{ else }}:
+ value: $(Build.BuildNumber)
pool:
# We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com)
@@ -124,7 +131,7 @@ jobs:
/p:ManifestsPath='$(Build.StagingDirectory)/AssetManifests'
/p:IsAssetlessBuild=${{ parameters.isAssetlessBuild }}
/p:MaestroApiEndpoint=https://maestro.dot.net
- /p:OfficialBuildId=$(Build.BuildNumber)
+ /p:OfficialBuildId=$(OfficialBuildId)
condition: ${{ parameters.condition }}
continueOnError: ${{ parameters.continueOnError }}
diff --git a/src/roslyn/eng/common/core-templates/jobs/jobs.yml b/src/roslyn/eng/common/core-templates/jobs/jobs.yml
index b637cb6e948..01ada747665 100644
--- a/src/roslyn/eng/common/core-templates/jobs/jobs.yml
+++ b/src/roslyn/eng/common/core-templates/jobs/jobs.yml
@@ -44,6 +44,7 @@ parameters:
artifacts: {}
is1ESPipeline: ''
repositoryAlias: self
+ officialBuildId: ''
# Internal resources (telemetry, microbuild) can only be accessed from non-public projects,
# and some (Microbuild) should only be applied to non-PR cases for internal builds.
@@ -116,3 +117,4 @@ jobs:
artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }}
signingValidationAdditionalParameters: ${{ parameters.signingValidationAdditionalParameters }}
repositoryAlias: ${{ parameters.repositoryAlias }}
+ officialBuildId: ${{ parameters.officialBuildId }}
diff --git a/src/roslyn/eng/common/core-templates/steps/generate-sbom.yml b/src/roslyn/eng/common/core-templates/steps/generate-sbom.yml
index c05f6502797..003f7eae0fa 100644
--- a/src/roslyn/eng/common/core-templates/steps/generate-sbom.yml
+++ b/src/roslyn/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: 10.0.0
+ PackageVersion: 11.0.0
BuildDropPath: '$(System.DefaultWorkingDirectory)/artifacts'
PackageName: '.NET'
ManifestDirPath: $(Build.ArtifactStagingDirectory)/sbom
diff --git a/src/roslyn/eng/common/core-templates/steps/source-index-stage1-publish.yml b/src/roslyn/eng/common/core-templates/steps/source-index-stage1-publish.yml
index e9a694afa58..eff4573c6e5 100644
--- a/src/roslyn/eng/common/core-templates/steps/source-index-stage1-publish.yml
+++ b/src/roslyn/eng/common/core-templates/steps/source-index-stage1-publish.yml
@@ -1,6 +1,6 @@
parameters:
- sourceIndexUploadPackageVersion: 2.0.0-20250818.1
- sourceIndexProcessBinlogPackageVersion: 1.0.1-20250818.1
+ sourceIndexUploadPackageVersion: 2.0.0-20250906.1
+ sourceIndexProcessBinlogPackageVersion: 1.0.1-20250906.1
sourceIndexPackageSource: https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json
binlogPath: artifacts/log/Debug/Build.binlog
diff --git a/src/roslyn/eng/config/PublishData.json b/src/roslyn/eng/config/PublishData.json
index 3e379f2ceef..120ca91da2c 100644
--- a/src/roslyn/eng/config/PublishData.json
+++ b/src/roslyn/eng/config/PublishData.json
@@ -14,6 +14,7 @@
"Microsoft.CodeAnalysis.Workspaces.Common": "vssdk",
"Microsoft.CodeAnalysis.Workspaces.MSBuild": "arcade",
"Microsoft.CodeAnalysis.Workspaces.Desktop": "arcade",
+ "Microsoft.CodeAnalysis.Workspaces.Test.Utilities": "vs-impl",
"Microsoft.CodeAnalysis.Compiler.Test.Resources": "vs-impl",
"Microsoft.CodeAnalysis.CSharp": "vssdk",
"Microsoft.CodeAnalysis.CSharp.CodeStyle": "arcade",
diff --git a/src/roslyn/eng/generate-compiler-code.cmd b/src/roslyn/eng/generate-compiler-code.cmd
index 60a78f05898..c16c34740ce 100644
--- a/src/roslyn/eng/generate-compiler-code.cmd
+++ b/src/roslyn/eng/generate-compiler-code.cmd
@@ -1,4 +1,3 @@
@echo off
-set PSMODULEPATH=
-powershell -noprofile -executionPolicy Unrestricted -file "%~dp0\generate-compiler-code.ps1" %*
+call "%~dp0\common\dotnet.cmd" run --file "%~dp0\generate-compiler-code.cs" %*
diff --git a/src/roslyn/eng/generate-compiler-code.cs b/src/roslyn/eng/generate-compiler-code.cs
new file mode 100755
index 00000000000..855fcc78a88
--- /dev/null
+++ b/src/roslyn/eng/generate-compiler-code.cs
@@ -0,0 +1,242 @@
+#!/usr/bin/env dotnet
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+// Need this fix to delete the static graph disable: https://github.com/dotnet/sdk/pull/50532, 10.0.100-rc.2
+#:property RestoreUseStaticGraphEvaluation=false
+#:project ../src/Tools/Source/CompilerGeneratorTools/Source/BoundTreeGenerator/
+#:project ../src/Tools/Source/CompilerGeneratorTools/Source/IOperationGenerator/
+#:project ../src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/
+#:project ../src/Tools/Source/CompilerGeneratorTools/Source/CSharpErrorFactsGenerator/
+#:project ../src/Tools/Source/CompilerGeneratorTools/Source/VisualBasicSyntaxGenerator/
+#:project ../src/Tools/Source/CompilerGeneratorTools/Source/VisualBasicErrorFactsGenerator/
+
+using System.Runtime.CompilerServices;
+
+var (test, configuration, repoRoot) = ParseArgs(args);
+
+// Folders for test artifacts when running in -test mode
+var generationTempDirRoot = Path.Join(repoRoot, "artifacts", "log", configuration, "Generated");
+var retVal = 0;
+
+// Generate C# source
+Console.WriteLine("Generating C# files...");
+
+var csharpLocation = GetLanguageDirStructure(repoRoot, "CSharp", generationTempDirRoot, test);
+retVal = GenerateLanguage(
+ BoundTreeGenerator.TargetLanguage.CSharp,
+ csharpLocation.LanguageDir,
+ test ? csharpLocation.GeneratedSourceTempDir : csharpLocation.GeneratedSourceDir,
+ (test ? csharpLocation.GeneratedTestTempDir : csharpLocation.GeneratedTestDir)!,
+ (inputFile, outputFile, writeSource, writeTests, writeGrammar)
+ => CSharpSyntaxGenerator.Program.Generate(inputFile, outputFile, writeSource, writeTests, writeGrammar, writeSignatures: false),
+ Microsoft.CodeAnalysis.CSharp.Internal.CSharpErrorFactsGenerator.Program.Generate);
+
+// Generate VB source
+Console.WriteLine("Generating VB files...");
+
+var vbLocation = GetLanguageDirStructure(repoRoot, "VisualBasic", generationTempDirRoot, test);
+retVal |= GenerateLanguage(
+ BoundTreeGenerator.TargetLanguage.VB,
+ vbLocation.LanguageDir,
+ test ? vbLocation.GeneratedSourceTempDir : vbLocation.GeneratedSourceDir,
+ (test ? vbLocation.GeneratedTestTempDir : vbLocation.GeneratedTestDir)!,
+ Microsoft.CodeAnalysis.VisualBasic.Internal.VBSyntaxGenerator.Program.Generate,
+ Microsoft.CodeAnalysis.VisualBasic.Internal.VBErrorFactsGenerator.Program.Generate);
+
+// Generate VB GetText source
+Console.WriteLine("Generating VB GetText files...");
+
+var getTextLocation = GetGetTextLocation(vbLocation, repoRoot, generationTempDirRoot, test);
+Microsoft.CodeAnalysis.VisualBasic.Internal.VBSyntaxGenerator.Program.Generate(
+ Path.Join(vbLocation.LanguageDir, "Syntax", "Syntax.xml"),
+ Path.Join(test ? getTextLocation.GeneratedSourceTempDir : getTextLocation.GeneratedSourceDir, "Syntax.xml.GetText.Generated.vb"),
+ writeSource: false, writeTests: false, writeGrammar: false);
+
+// Generate IOperation source
+Console.WriteLine("Generating IOperation files...");
+
+var ioperationLocation = GetIOperationLocation(repoRoot, generationTempDirRoot, test);
+retVal |= IOperationGenerator.Program.Generate(Path.Join(ioperationLocation.LanguageDir, "Operations", "OperationInterfaces.xml"), test ? ioperationLocation.GeneratedSourceTempDir : ioperationLocation.GeneratedSourceDir);
+
+if (test)
+{
+ Console.WriteLine("Verifying generated files...");
+ retVal |= TestGenerationResults(repoRoot, csharpLocation, vbLocation, getTextLocation, ioperationLocation);
+}
+
+Console.WriteLine(retVal == 0 ? "Generation succeeded." : "Generation failed.");
+return retVal;
+
+static (bool test, string configuration, string roslynDirectory) ParseArgs(string[] args, [CallerFilePath] string sourceFilePath = "")
+{
+ var test = false;
+ var configuration = "Debug";
+
+ for (var i = 0; i < args.Length; i++)
+ {
+ var a = args[i];
+ switch (a)
+ {
+ case "-test":
+ test = true;
+ break;
+ case "-configuration" when i + 1 < args.Length:
+ configuration = args[i++];
+ break;
+ default:
+ Console.WriteLine("Unknown argument: " + a);
+ Environment.Exit(1);
+ break;
+ }
+ }
+
+ if (Path.GetDirectoryName(sourceFilePath) is not string engDir || Path.GetDirectoryName(engDir) is not string roslynRoot || !File.Exists(Path.Join(roslynRoot, "eng", Path.GetFileName(sourceFilePath))))
+ {
+ Console.WriteLine("Could not determine source file path. This script must be located in the 'eng' directory of the Roslyn repo.");
+ Environment.Exit(1);
+ throw null!;
+ }
+
+ return (test, configuration, roslynRoot);
+}
+
+static GenerationLocation GetLanguageDirStructure(string repoRoot, string languageName, string generationTempDirRoot, bool isTest)
+{
+ var languageDir = Path.Join(repoRoot, "src", "Compilers", languageName, "Portable");
+ var loc = new GenerationLocation(
+ languageDir,
+ Path.Join(languageDir, "Generated"),
+ Path.Join(repoRoot, "src", "Compilers", languageName, "Test", "Syntax", "Generated"),
+ Path.Join(generationTempDirRoot, languageName, "Src"),
+ Path.Join(generationTempDirRoot, languageName, "Test")
+ );
+
+ if (isTest)
+ {
+ Directory.CreateDirectory(loc.GeneratedSourceTempDir);
+ Directory.CreateDirectory(loc.GeneratedTestTempDir!);
+ }
+
+ return loc;
+}
+
+static GenerationLocation GetGetTextLocation(GenerationLocation vbLocation, string repoRoot, string generationTempDirRoot, bool test)
+{
+ var getTextDir = new GenerationLocation(
+ vbLocation.LanguageDir,
+ Path.Join(repoRoot, "src", "ExpressionEvaluator", "VisualBasic", "Source", "ResultProvider", "Generated"),
+ GeneratedTestDir: null,
+ Path.Join(generationTempDirRoot, "VisualBasic", "GetText"),
+ GeneratedTestTempDir: null
+ );
+
+ if (test)
+ {
+ Directory.CreateDirectory(getTextDir.GeneratedSourceTempDir);
+ }
+
+ return getTextDir;
+}
+
+static GenerationLocation GetIOperationLocation(string repoRoot, string generationTempDirRoot, bool test)
+{
+ var languageDir = Path.Join(repoRoot, "src", "Compilers", "Core", "Portable");
+ var loc = new GenerationLocation(
+ languageDir,
+ Path.Join(languageDir, "Generated"),
+ GeneratedTestDir: null,
+ Path.Join(generationTempDirRoot, "Core", "Src"),
+ GeneratedTestTempDir: null
+ );
+
+ if (test)
+ {
+ Directory.CreateDirectory(loc.GeneratedSourceTempDir);
+ }
+
+ return loc;
+}
+
+static int GenerateLanguage(BoundTreeGenerator.TargetLanguage language, string languageDir, string generatedDir, string generatedTestDir, SyntaxGeneratorAction syntaxGenerator, ErrorFactsGeneratorAction errorFactsGenerator)
+{
+ var extension = language == BoundTreeGenerator.TargetLanguage.CSharp ? "cs" : "vb";
+ var generatedTestFile = Path.Join(generatedTestDir, $"Syntax.Test.xml.Generated.{extension}");
+ var errorsPath = Path.Join(languageDir, "Errors", language == BoundTreeGenerator.TargetLanguage.CSharp ? "ErrorCode.cs" : "Errors.vb");
+ var errorFactsFilePath = Path.Join(generatedDir, $"ErrorFacts.Generated.{extension}");
+
+ var syntaxFile = Path.Join(languageDir, "Syntax", $"Syntax.xml");
+
+ int retVal = 0;
+
+ if (language != BoundTreeGenerator.TargetLanguage.CSharp)
+ {
+ retVal |= syntaxGenerator(syntaxFile, generatedDir, writeSource: true, writeTests: false, writeGrammar: false);
+ }
+
+ retVal |= syntaxGenerator(syntaxFile, generatedDir, writeSource: false, writeTests: false, writeGrammar: true);
+ retVal |= syntaxGenerator(syntaxFile, generatedTestFile, writeSource: false, writeTests: true, writeGrammar: false);
+
+ retVal |= BoundTreeGenerator.Program.Generate(
+ language,
+ Path.Join(languageDir, "BoundTree", "BoundNodes.xml"),
+ Path.Join(generatedDir, $"BoundNodes.xml.Generated.{extension}"));
+
+ retVal |= errorFactsGenerator(errorsPath, errorFactsFilePath);
+
+ return retVal;
+}
+
+static int TestGenerationResults(string repoRoot, GenerationLocation csharpLocation, GenerationLocation vbLocation, GenerationLocation getTextLocation, GenerationLocation ioperationLocation)
+{
+ string[] actualDirs = [.. csharpLocation.GetActualDirs(), .. vbLocation.GetActualDirs(), getTextLocation.GeneratedSourceDir, ioperationLocation.GeneratedSourceDir];
+ string[] tempDirs = [.. csharpLocation.GetTempDirs(), .. vbLocation.GetTempDirs(), getTextLocation.GeneratedSourceTempDir, ioperationLocation.GeneratedSourceTempDir];
+
+ var retVal = 0;
+ foreach (var (actualDir, tempDir) in actualDirs.Zip(tempDirs))
+ {
+ var tempFiles = Directory.GetFiles(tempDir).Select(Path.GetFileName);
+ foreach (var fileName in tempFiles)
+ {
+ Console.WriteLine($"Verifying {fileName}");
+ var actualFile = Path.Join(actualDir, fileName);
+ var tempFile = Path.Join(tempDir, fileName);
+
+ if (!File.Exists(actualFile))
+ {
+ Console.WriteLine($"Generated file '{actualFile}' does not exist.");
+ Console.WriteLine($"Run {Path.Join(repoRoot, "eng", "generate-compiler-code.cmd")} to update it.");
+ retVal = 1;
+ }
+ else if (!File.ReadAllText(actualFile).Equals(File.ReadAllText(tempFile), StringComparison.Ordinal))
+ {
+ Console.WriteLine($"Generated file '{actualFile}' is out of date.");
+ Console.WriteLine($"Run {Path.Join(repoRoot, "eng", "generate-compiler-code.cmd")} to update it.");
+ retVal = 1;
+ }
+ }
+ }
+
+ return retVal;
+}
+
+delegate int SyntaxGeneratorAction(string inputFile, string outputFile, bool writeSource, bool writeTests, bool writeGrammar);
+delegate int ErrorFactsGeneratorAction(string inputPath, string outputPath);
+
+readonly record struct GenerationLocation(string LanguageDir, string GeneratedSourceDir, string? GeneratedTestDir, string GeneratedSourceTempDir, string? GeneratedTestTempDir)
+{
+ public readonly IEnumerable GetActualDirs()
+ {
+ yield return GeneratedSourceDir;
+ if (GeneratedTestDir is not null)
+ yield return GeneratedTestDir;
+ }
+
+ public readonly IEnumerable GetTempDirs()
+ {
+ yield return GeneratedSourceTempDir;
+ if (GeneratedTestTempDir is not null)
+ yield return GeneratedTestTempDir;
+ }
+}
diff --git a/src/roslyn/eng/generate-compiler-code.ps1 b/src/roslyn/eng/generate-compiler-code.ps1
deleted file mode 100644
index dee6b02db82..00000000000
--- a/src/roslyn/eng/generate-compiler-code.ps1
+++ /dev/null
@@ -1,149 +0,0 @@
-# The compiler source base has a large body of generated code. This script is responsible
-# for both generating this code and verifying the generated code is always up to date with
-# the generator source files.
-[CmdletBinding(PositionalBinding=$false)]
-param ([string]$configuration = "Debug",
- [switch]$test = $false,
- [switch]$ci = $false)
-
-Set-StrictMode -version 2.0
-$ErrorActionPreference="Stop"
-
-function Run-Tool($projectFilePath, $toolArgs, $targetFramework) {
- $toolName = Split-Path -leaf $projectFilePath
- Write-Host "Running $toolName $toolArgs"
- Exec-DotNet "run --project $projectFilePath --framework $targetFramework $toolArgs"
-}
-
-function Run-LanguageCore($language, $languageSuffix, $languageDir, $syntaxProject, $errorFactsProject, $generatedDir, $generatedTestDir) {
- $syntaxFilePath = Join-Path $languageDir "Syntax\Syntax.xml"
- $syntaxTestFilePath = Join-Path $generatedTestDir "Syntax.Test.xml.Generated.$($languageSuffix)"
- $boundFilePath = Join-Path $languageDir "BoundTree\BoundNodes.xml"
- $boundGeneratedFilePath = Join-Path $generatedDir "BoundNodes.xml.Generated.$($languageSuffix)"
- $errorFileName = if ($language -eq "CSharp") { "ErrorCode.cs" } else { "Errors.vb" }
- $errorFilePath = Join-Path $languageDir "Errors\$errorFileName"
- $errorGeneratedFilePath = Join-Path $generatedDir "ErrorFacts.Generated.$($languageSuffix)"
- $targetFramework = "net9.0"
-
- Create-Directory $generatedDir
- Create-Directory $generatedTestDir
-
- # The C# syntax is now generated by a source generator
- if ($language -ne "CSharp") {
- Run-Tool $syntaxProject "`"$syntaxFilePath`" `"$generatedDir`"" $targetFramework
- }
- Run-Tool $syntaxProject "`"$syntaxFilePath`" `"$generatedDir`" /grammar" $targetFramework
- Run-Tool $syntaxProject "`"$syntaxFilePath`" `"$syntaxTestFilePath`" /test" $targetFramework
- Run-Tool $boundTreeGenProject "$language `"$boundFilePath`" `"$boundGeneratedFilePath`"" $targetFramework
- Run-Tool $errorFactsProject "`"$errorFilePath`" `"$errorGeneratedFilePath`"" $targetFramework
-}
-
-# Test the contents of our generated files to ensure they are equal. Compares our checked
-# in code with the freshly generated code.
-function Test-GeneratedContent($generatedDir, $scratchDir) {
- $algo = "MD5"
- foreach ($fileName in (Get-ChildItem $scratchDir | Select-Object -ExpandProperty Name)) {
- Write-Host "Checking $fileName"
- $realFilePath = Join-Path $generatedDir $fileName
- $scratchFilePath = Join-Path $scratchDir $fileName
- $scratchHash = (Get-FileHash $scratchFilePath -algorithm $algo).Hash
- $realHash = (Get-FileHash $realFilePath -algorithm $algo).Hash
- if ($scratchHash -ne $realHash) {
- Write-Host "Files are out of date"
- Write-Host "Run $(Join-Path $PSScriptRoot generate-compiler-code.ps1) to refresh"
- throw "Files are out of date"
- }
- }
-}
-
-function Run-Language($language, $languageSuffix, $languageDir, $languageTestDir, $syntaxTool, $errorFactsTool) {
- $generatedDir = Join-Path $languageDir "Generated"
- $generatedTestDir = Join-Path $languageTestDir "Generated"
- if (-not $test) {
- Run-LanguageCore $language $languageSuffix $languageDir $syntaxTool $errorFactsTool $generatedDir $generatedTestDir
- }
- else {
- $scratchDir = Join-Path $generationTempDir "$language\Src"
- $scratchTestDir = Join-Path $generationTempDir "$language\Test"
- Run-LanguageCore $language $languageSuffix $languageDir $syntaxTool $errorFactsTool $scratchDir $scratchTestDir
- Test-GeneratedContent $generatedDir $scratchDir
- Test-GeneratedContent $generatedTestDir $scratchTestDir
- }
-}
-
-function Run-IOperation($coreDir, $ioperationProject) {
- $operationsDir = Join-Path $coreDir "Operations"
- $operationsXml = Join-Path $operationsDir "OperationInterfaces.xml"
- $generationDir = Join-Path $coreDir "Generated"
- $targetFramework = "net9.0"
-
- if (-not $test) {
- Run-Tool $ioperationProject "`"$operationsXml`" `"$generationDir`"" $targetFramework
- } else {
- $scratchDir = Join-Path $generationTempDir "Core\Operations"
- Create-Directory $scratchDir
- Run-Tool $ioperationProject "`"$operationsXml`" `"$scratchDir`"" $targetFramework
- Test-GeneratedContent $generationDir $scratchDir
- }
-}
-
-function Run-GetTextCore($generatedDir) {
- $syntaxFilePath = Join-Path $basicDir "Syntax\Syntax.xml"
- $syntaxTextFilePath = Join-Path $generatedDir "Syntax.xml.GetText.Generated.vb"
-
- Create-Directory $generatedDir
- Run-Tool $basicSyntaxProject "`"$syntaxFilePath`" `"$syntaxTextFilePath`" /gettext" "net9.0"
-}
-
-function Run-GetText() {
- $generatedDir = Join-Path $RepoRoot "src\ExpressionEvaluator\VisualBasic\Source\ResultProvider\Generated"
- if (-not $test) {
- Run-GetTextCore $generatedDir
- }
- else {
- $scratchDir = Join-Path $generationTempDir "VB\GetText"
- Run-GetTextCore $scratchDir
- Test-GeneratedContent $generatedDir $scratchDir
- }
-}
-
-function Get-ToolPath($projectRelativePath) {
- $p = Join-Path 'src\Tools\Source\CompilerGeneratorTools\Source' $projectRelativePath
- $p = Join-Path $RepoRoot $p
- return $p
-}
-
-try {
- . (Join-Path $PSScriptRoot "build-utils.ps1")
- Push-Location $RepoRoot
- $prepareMachine = $ci
-
- $dotnet = Ensure-DotnetSdk
- $boundTreeGenProject = Get-ToolPath 'BoundTreeGenerator\CompilersBoundTreeGenerator.csproj'
-
- $coreDir = Join-Path $RepoRoot "src\Compilers\Core\Portable"
- $operationsProject = Get-ToolPath "IOperationGenerator\CompilersIOperationGenerator.csproj"
- $csharpDir = Join-Path $RepoRoot "src\Compilers\CSharp\Portable"
- $csharpTestDir = Join-Path $RepoRoot "src\Compilers\CSharp\Test\Syntax"
- $csharpSyntaxProject = Get-ToolPath 'CSharpSyntaxGenerator\CSharpSyntaxGenerator.csproj'
- $csharpErrorFactsProject = Get-ToolPath 'CSharpErrorFactsGenerator\CSharpErrorFactsGenerator.csproj'
- $basicDir = Join-Path $RepoRoot "src\Compilers\VisualBasic\Portable"
- $basicTestDir = Join-Path $RepoRoot "src\Compilers\VisualBasic\Test\Syntax"
- $basicSyntaxProject = Get-ToolPath 'VisualBasicSyntaxGenerator\VisualBasicSyntaxGenerator.vbproj'
- $basicErrorFactsProject = Get-ToolPath 'VisualBasicErrorFactsGenerator\VisualBasicErrorFactsGenerator.vbproj'
- $generationTempDir = Join-Path $RepoRoot "artifacts\log\$configuration\Generated"
-
- Run-Language "CSharp" "cs" $csharpDir $csharpTestDir $csharpSyntaxProject $csharpErrorFactsProject
- Run-Language "VB" "vb" $basicDir $basicTestDir $basicSyntaxProject $basicErrorFactsProject
- Run-IOperation $coreDir $operationsProject
- Run-GetText
-
- ExitWithExitCode 0
-}
-catch {
- Write-Host $_
- ExitWithExitCode 1
-}
-finally {
- Pop-Location
-}
diff --git a/src/roslyn/eng/targets/GeneratePkgDef.targets b/src/roslyn/eng/targets/GeneratePkgDef.targets
index dff341435fa..d14f08cf197 100644
--- a/src/roslyn/eng/targets/GeneratePkgDef.targets
+++ b/src/roslyn/eng/targets/GeneratePkgDef.targets
@@ -86,9 +86,18 @@
+
+
+
+
+
+ $(CollectUpToDateCheckInputDesignTimeDependsOn);_SetGeneratePkgDefInputsOutputs
+ $(CollectUpToDateCheckOutputDesignTimeDependsOn);_SetGeneratePkgDefInputsOutputs
+
+
@@ -293,12 +302,10 @@
-
+ Encoding="UTF-8" />
diff --git a/src/roslyn/eng/targets/VisualStudio.FastUpToDateCheckWorkarounds.targets b/src/roslyn/eng/targets/VisualStudio.FastUpToDateCheckWorkarounds.targets
index 15dfae3b1d9..716f3adda86 100644
--- a/src/roslyn/eng/targets/VisualStudio.FastUpToDateCheckWorkarounds.targets
+++ b/src/roslyn/eng/targets/VisualStudio.FastUpToDateCheckWorkarounds.targets
@@ -1,22 +1,11 @@
-
-
-
-
-
-
-
-
-
+
$(CollectUpToDateCheckInputDesignTimeDependsOn);RemoveBuildOutputSourceItems
-
<_ItemsInObjDirectory Include="$(IntermediateOutputPath)\**\*" Set="VsixItems" />
diff --git a/src/roslyn/eng/targets/VisualStudio.targets b/src/roslyn/eng/targets/VisualStudio.targets
index 7d7c4a32833..904f9d3410f 100644
--- a/src/roslyn/eng/targets/VisualStudio.targets
+++ b/src/roslyn/eng/targets/VisualStudio.targets
@@ -142,7 +142,7 @@
Condition="$([MSBuild]::ValueOrDefault('$(ExtensionsPath)', '').Contains('16.0'))"/>
-
+
diff --git a/src/roslyn/eng/test-build-correctness.ps1 b/src/roslyn/eng/test-build-correctness.ps1
index 073b80f8d34..fffe4dedcff 100644
--- a/src/roslyn/eng/test-build-correctness.ps1
+++ b/src/roslyn/eng/test-build-correctness.ps1
@@ -71,8 +71,7 @@ try {
# Verify the state of our generated syntax files
Write-Host "Checking generated compiler files"
- & eng/generate-compiler-code.ps1 -test -configuration:$configuration
- Test-LastExitCode
+ Exec-DotNet "run --file eng/generate-compiler-code.cs -- -test -configuration $configuration"
Exec-DotNet "tool run dotnet-format whitespace . --folder --include-generated --include src/Compilers/CSharp/Portable/Generated/ src/Compilers/VisualBasic/Portable/Generated/ src/ExpressionEvaluator/VisualBasic/Source/ResultProvider/Generated/ --verify-no-changes"
Write-Host ""
diff --git a/src/roslyn/global.json b/src/roslyn/global.json
index ed08b2111bd..e8cf0f3b286 100644
--- a/src/roslyn/global.json
+++ b/src/roslyn/global.json
@@ -12,8 +12,8 @@
"vswhere": "3.1.7"
},
"msbuild-sdks": {
- "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25427.2",
- "Microsoft.DotNet.Helix.Sdk": "10.0.0-beta.25427.2",
+ "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25469.3",
+ "Microsoft.DotNet.Helix.Sdk": "11.0.0-beta.25469.3",
"Microsoft.Build.Traversal": "3.4.0"
}
}
diff --git a/src/roslyn/src/Analyzers/CSharp/Analyzers/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionDiagnosticAnalyzer.Analyzer.cs b/src/roslyn/src/Analyzers/CSharp/Analyzers/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionDiagnosticAnalyzer.Analyzer.cs
index 81a4794e13a..29b8435efca 100644
--- a/src/roslyn/src/Analyzers/CSharp/Analyzers/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionDiagnosticAnalyzer.Analyzer.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Analyzers/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionDiagnosticAnalyzer.Analyzer.cs
@@ -162,8 +162,7 @@ private bool CanConvertLabelsToArms(SyntaxList labels)
// Then we can't convert into a single arm.
foreach (var label in labels)
{
- if (label is CasePatternSwitchLabelSyntax casePattern &&
- casePattern.WhenClause != null)
+ if (label is CasePatternSwitchLabelSyntax { WhenClause: not null })
{
return false;
}
diff --git a/src/roslyn/src/Analyzers/CSharp/Analyzers/ConvertTypeofToNameof/CSharpConvertTypeOfToNameOfDiagnosticAnalyzer.cs b/src/roslyn/src/Analyzers/CSharp/Analyzers/ConvertTypeofToNameof/CSharpConvertTypeOfToNameOfDiagnosticAnalyzer.cs
index f8a82406481..6600f869dac 100644
--- a/src/roslyn/src/Analyzers/CSharp/Analyzers/ConvertTypeofToNameof/CSharpConvertTypeOfToNameOfDiagnosticAnalyzer.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Analyzers/ConvertTypeofToNameof/CSharpConvertTypeOfToNameOfDiagnosticAnalyzer.cs
@@ -31,8 +31,8 @@ protected override bool IsValidTypeofAction(OperationAnalysisContext context)
// Make sure that the syntax that we're looking at is actually a typeof expression and that
// the parent syntax is a member access expression otherwise the syntax is not the kind of
// expression that we want to analyze
- return node is TypeOfExpressionSyntax { Parent: MemberAccessExpressionSyntax } typeofExpression &&
- // nameof(System.Void) isn't allowed in C#.
- typeofExpression is not { Type: PredefinedTypeSyntax { Keyword.RawKind: (int)SyntaxKind.VoidKeyword } };
+ return node is TypeOfExpressionSyntax { Parent: MemberAccessExpressionSyntax }
+ // nameof(System.Void) isn't allowed in C#.
+ and not { Type: PredefinedTypeSyntax { Keyword.RawKind: (int)SyntaxKind.VoidKeyword } };
}
}
diff --git a/src/roslyn/src/Analyzers/CSharp/Analyzers/MakeStructMemberReadOnly/CSharpMakeStructMemberReadOnlyAnalyzer.cs b/src/roslyn/src/Analyzers/CSharp/Analyzers/MakeStructMemberReadOnly/CSharpMakeStructMemberReadOnlyAnalyzer.cs
index f0c45c29ded..eb538fea66e 100644
--- a/src/roslyn/src/Analyzers/CSharp/Analyzers/MakeStructMemberReadOnly/CSharpMakeStructMemberReadOnlyAnalyzer.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Analyzers/MakeStructMemberReadOnly/CSharpMakeStructMemberReadOnlyAnalyzer.cs
@@ -104,7 +104,7 @@ void ProcessResults(
// No need to lock the dictionary here. Processing only is called once, after all mutation work is done.
foreach (var (method, diagnostic) in methodToDiagnostic)
{
- if (method.IsInitOnly && method.AssociatedSymbol is IPropertySymbol owningProperty)
+ if (method is { IsInitOnly: true, AssociatedSymbol: IPropertySymbol owningProperty })
{
// Iff we have an init method that we want to mark as readonly, we can only do so if there is no
// `get` accessor, or if the `get` method is already `readonly` or would determined we want to
@@ -181,8 +181,7 @@ private static (Location? location, Location? additionalLocation) GetDiagnosticL
// An init accessor in a readonly property is already readonly. No need to analyze it. Note: there is no way
// to tell this symbolically. We have to check to the syntax here.
- if (owningMethod.IsInitOnly &&
- owningMethod.AssociatedSymbol is IPropertySymbol { DeclaringSyntaxReferences: [var reference, ..] } &&
+ if (owningMethod is { IsInitOnly: true, AssociatedSymbol: IPropertySymbol { DeclaringSyntaxReferences: [var reference, ..] } } &&
reference.GetSyntax(cancellationToken) is PropertyDeclarationSyntax property &&
property.Modifiers.Any(SyntaxKind.ReadOnlyKeyword))
{
diff --git a/src/roslyn/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryDiscardDesignation/CSharpRemoveUnnecessaryDiscardDesignationDiagnosticAnalyzer.cs b/src/roslyn/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryDiscardDesignation/CSharpRemoveUnnecessaryDiscardDesignationDiagnosticAnalyzer.cs
index ff48a216f5b..5f16decccd4 100644
--- a/src/roslyn/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryDiscardDesignation/CSharpRemoveUnnecessaryDiscardDesignationDiagnosticAnalyzer.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryDiscardDesignation/CSharpRemoveUnnecessaryDiscardDesignationDiagnosticAnalyzer.cs
@@ -81,8 +81,7 @@ private void AnalyzeDiscardDesignation(SyntaxNodeAnalysisContext context)
else if (discard.Parent is RecursivePatternSyntax recursivePattern)
{
// can't remove from `(int i) _` as `(int i)` is not a legal pattern itself.
- if (recursivePattern.PositionalPatternClause != null &&
- recursivePattern.PositionalPatternClause.Subpatterns.Count == 1)
+ if (recursivePattern.PositionalPatternClause is { Subpatterns.Count: 1 })
{
return;
}
diff --git a/src/roslyn/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryLambdaExpression/CSharpRemoveUnnecessaryLambdaExpressionDiagnosticAnalyzer.cs b/src/roslyn/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryLambdaExpression/CSharpRemoveUnnecessaryLambdaExpressionDiagnosticAnalyzer.cs
index 73765482364..d31694d8f4d 100644
--- a/src/roslyn/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryLambdaExpression/CSharpRemoveUnnecessaryLambdaExpressionDiagnosticAnalyzer.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryLambdaExpression/CSharpRemoveUnnecessaryLambdaExpressionDiagnosticAnalyzer.cs
@@ -132,13 +132,13 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context, INamedTypeSymbol?
return;
// cannot convert a partial-definition to a delegate (unless there's an existing implementation part that can be used).
- if (invokedMethod.IsPartialDefinition && invokedMethod.PartialImplementationPart is null)
+ if (invokedMethod is { IsPartialDefinition: true, PartialImplementationPart: null })
return;
// Check if the invoked method is a member of a struct. If it is, and it is not readonly and the invoked method
// is not readonly, then we don't want to convert it to a method group. If we did, we may accidently change the
// behaviour of the code, since structs are value types and the method group will be copied rather than referenced.
- if (invokedMethod.ContainingType.TypeKind == TypeKind.Struct && !invokedMethod.IsReadOnly && !invokedMethod.ContainingType.IsReadOnly)
+ if (invokedMethod is { ContainingType.TypeKind: TypeKind.Struct, IsReadOnly: false, ContainingType.IsReadOnly: false })
return;
// If we're calling a generic method, we have to have supplied type arguments. They cannot be inferred once
@@ -307,7 +307,7 @@ public static bool TryGetAnonymousFunctionInvocation(
if (anonymousFunction.ExpressionBody != null)
return TryGetInvocation(anonymousFunction.ExpressionBody, out invocation, out wasAwaited);
- if (anonymousFunction.Block != null && anonymousFunction.Block.Statements.Count == 1)
+ if (anonymousFunction.Block is { Statements.Count: 1 })
{
var statement = anonymousFunction.Block.Statements[0];
if (statement is ReturnStatementSyntax { Expression: { } expression })
diff --git a/src/roslyn/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryParentheses/CSharpRemoveUnnecessaryExpressionParenthesesDiagnosticAnalyzer.cs b/src/roslyn/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryParentheses/CSharpRemoveUnnecessaryExpressionParenthesesDiagnosticAnalyzer.cs
index ffb403611d9..8fee35020db 100644
--- a/src/roslyn/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryParentheses/CSharpRemoveUnnecessaryExpressionParenthesesDiagnosticAnalyzer.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryParentheses/CSharpRemoveUnnecessaryExpressionParenthesesDiagnosticAnalyzer.cs
@@ -77,7 +77,7 @@ public static bool CanRemoveParenthesesHelper(
parentExpression = isPatternExpression;
break;
- case ConstantPatternSyntax constantPattern when constantPattern.Parent is IsPatternExpressionSyntax isPatternExpression:
+ case ConstantPatternSyntax { Parent: IsPatternExpressionSyntax isPatternExpression }:
// on the right side of an 'x is const_pattern' expression
parentExpression = isPatternExpression;
break;
diff --git a/src/roslyn/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/UseCollectionExpressionHelpers.cs b/src/roslyn/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/UseCollectionExpressionHelpers.cs
index 4a6ff87c465..1faf6c3d638 100644
--- a/src/roslyn/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/UseCollectionExpressionHelpers.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/UseCollectionExpressionHelpers.cs
@@ -101,7 +101,7 @@ public static bool CanReplaceWithCollectionExpression(
return false;
// (X[])[1, 2, 3] is target typed. `(X)[1, 2, 3]` is currently not (because it looks like indexing into an expr).
- if (topMostExpression.Parent is CastExpressionSyntax castExpression && castExpression.Type is IdentifierNameSyntax)
+ if (topMostExpression.Parent is CastExpressionSyntax { Type: IdentifierNameSyntax })
return false;
// X[] = new Y[] { 1, 2, 3 }
@@ -977,13 +977,13 @@ bool IsCompatibleSignatureAndArguments(
if (arguments.Count == 1 &&
compilation.SupportsRuntimeCapability(RuntimeCapability.InlineArrayTypes) &&
originalCreateMethod.Parameters is [
- {
- Type: INamedTypeSymbol
{
- Name: nameof(Span<>) or nameof(ReadOnlySpan<>),
- TypeArguments: [ITypeParameterSymbol { TypeParameterKind: TypeParameterKind.Method }]
- } spanType
- }])
+ Type: INamedTypeSymbol
+ {
+ Name: nameof(Span<>) or nameof(ReadOnlySpan<>),
+ TypeArguments: [ITypeParameterSymbol { TypeParameterKind: TypeParameterKind.Method }]
+ } spanType
+ }])
{
if (spanType.OriginalDefinition.Equals(compilation.SpanOfTType()) ||
spanType.OriginalDefinition.Equals(compilation.ReadOnlySpanOfTType()))
@@ -1021,7 +1021,7 @@ public static bool IsArgumentCompatibleWithIEnumerableOfT(
if (argExpression is ObjectCreationExpressionSyntax objectCreation)
{
// Can't have any arguments, as we cannot preserve them once we grab out all the elements.
- if (objectCreation.ArgumentList != null && objectCreation.ArgumentList.Arguments.Count > 0)
+ if (objectCreation.ArgumentList is { Arguments.Count: > 0 })
return false;
// If it's got an initializer, it has to be a collection initializer (or an empty object initializer);
diff --git a/src/roslyn/src/Analyzers/CSharp/Analyzers/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentDiagnosticAnalyzer.cs b/src/roslyn/src/Analyzers/CSharp/Analyzers/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentDiagnosticAnalyzer.cs
index 3d39d9fb163..97f3771cc11 100644
--- a/src/roslyn/src/Analyzers/CSharp/Analyzers/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentDiagnosticAnalyzer.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Analyzers/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentDiagnosticAnalyzer.cs
@@ -199,8 +199,7 @@ private bool IsReferenceEqualsNullCheck(
arg1.Kind() == SyntaxKind.NullLiteralExpression)
{
var symbol = semanticModel.GetSymbolInfo(invocation, cancellationToken).Symbol;
- if (symbol?.Name == nameof(ReferenceEquals) &&
- symbol.ContainingType?.SpecialType == SpecialType.System_Object)
+ if (symbol is { Name: nameof(ReferenceEquals), ContainingType.SpecialType: SpecialType.System_Object })
{
testedExpression = arg0.Kind() == SyntaxKind.NullLiteralExpression ? arg1 : arg0;
}
diff --git a/src/roslyn/src/Analyzers/CSharp/Analyzers/UseDeconstruction/CSharpUseDeconstructionDiagnosticAnalyzer.cs b/src/roslyn/src/Analyzers/CSharp/Analyzers/UseDeconstruction/CSharpUseDeconstructionDiagnosticAnalyzer.cs
index 9f7cd1a256e..9817d759094 100644
--- a/src/roslyn/src/Analyzers/CSharp/Analyzers/UseDeconstruction/CSharpUseDeconstructionDiagnosticAnalyzer.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Analyzers/UseDeconstruction/CSharpUseDeconstructionDiagnosticAnalyzer.cs
@@ -151,10 +151,7 @@ private static bool TryAnalyze(
if (!IsViableTupleTypeSyntax(typeNode))
return false;
- if (conversion.Exists &&
- !conversion.IsIdentity &&
- !conversion.IsTupleConversion &&
- !conversion.IsTupleLiteralConversion)
+ if (conversion is { Exists: true, IsIdentity: false, IsTupleConversion: false, IsTupleLiteralConversion: false })
{
// If there is any other conversion, we bail out because the source type might not be a tuple
// or it is a tuple but only thanks to target type inference, which won't occur in a deconstruction.
diff --git a/src/roslyn/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForLocalFunctionHelper.cs b/src/roslyn/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForLocalFunctionHelper.cs
index 970c92cee9b..a51fa0b1752 100644
--- a/src/roslyn/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForLocalFunctionHelper.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForLocalFunctionHelper.cs
@@ -57,9 +57,7 @@ protected override bool CreateReturnStatementForExpression(
// if it's 'async TaskLike' (where TaskLike is non-generic) we do *not* want to
// create a return statement. This is just the 'async' version of a 'void' local function.
var symbol = semanticModel.GetDeclaredSymbol(statement);
- return symbol is IMethodSymbol methodSymbol &&
- methodSymbol.ReturnType is INamedTypeSymbol namedType &&
- namedType.Arity != 0;
+ return symbol is IMethodSymbol { ReturnType: INamedTypeSymbol { Arity: not 0 } };
}
return !statement.ReturnType.IsVoid();
diff --git a/src/roslyn/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForMethodsHelper.cs b/src/roslyn/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForMethodsHelper.cs
index d61f5abe544..94ca346c50d 100644
--- a/src/roslyn/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForMethodsHelper.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForMethodsHelper.cs
@@ -57,7 +57,7 @@ protected override bool CreateReturnStatementForExpression(
// if it's 'async TaskLike' (where TaskLike is non-generic) we do *not* want to
// create a return statement. This is just the 'async' version of a 'void' method.
var method = semanticModel.GetDeclaredSymbol(declaration);
- return method.ReturnType is INamedTypeSymbol namedType && namedType.Arity != 0;
+ return method.ReturnType is INamedTypeSymbol { Arity: not 0 };
}
return !declaration.ReturnType.IsVoid();
diff --git a/src/roslyn/src/Analyzers/CSharp/Analyzers/UseExpressionBody/UseExpressionBodyDiagnosticAnalyzer.cs b/src/roslyn/src/Analyzers/CSharp/Analyzers/UseExpressionBody/UseExpressionBodyDiagnosticAnalyzer.cs
index a0ea8cc4a4c..fa00a7e87a5 100644
--- a/src/roslyn/src/Analyzers/CSharp/Analyzers/UseExpressionBody/UseExpressionBodyDiagnosticAnalyzer.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Analyzers/UseExpressionBody/UseExpressionBodyDiagnosticAnalyzer.cs
@@ -40,7 +40,7 @@ public UseExpressionBodyDiagnosticAnalyzer()
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
- => DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis;
+ => DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxNodeAction(AnalyzeSyntax, _syntaxKinds);
diff --git a/src/roslyn/src/Analyzers/CSharp/Analyzers/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationDiagnosticAnalyzer.cs b/src/roslyn/src/Analyzers/CSharp/Analyzers/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationDiagnosticAnalyzer.cs
index 4e4f1ae0a87..14f6f5087fb 100644
--- a/src/roslyn/src/Analyzers/CSharp/Analyzers/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationDiagnosticAnalyzer.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Analyzers/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationDiagnosticAnalyzer.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.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
@@ -80,6 +81,7 @@ public static bool Analyze(
// 3. Collection-like constructs where the type of the collection is itself explicit. For example: `new
// List { new() }` or `new C[] { new() }`.
+ var isAsync = false;
TypeSyntax? typeNode;
if (objectCreation.Parent is EqualsValueClauseSyntax
@@ -99,15 +101,15 @@ public static bool Analyze(
}
else if (objectCreation.Parent.IsKind(SyntaxKind.ArrowExpressionClause))
{
- typeNode = objectCreation.Parent.Parent switch
+ (typeNode, isAsync) = objectCreation.Parent.Parent switch
{
- LocalFunctionStatementSyntax localFunction => localFunction.ReturnType,
- MethodDeclarationSyntax method => method.ReturnType,
- ConversionOperatorDeclarationSyntax conversion => conversion.Type,
- OperatorDeclarationSyntax op => op.ReturnType,
- BasePropertyDeclarationSyntax property => property.Type,
- AccessorDeclarationSyntax(SyntaxKind.GetAccessorDeclaration) { Parent: AccessorListSyntax { Parent: BasePropertyDeclarationSyntax baseProperty } } => baseProperty.Type,
- _ => null,
+ LocalFunctionStatementSyntax localFunction => (localFunction.ReturnType, localFunction.Modifiers.Any(SyntaxKind.AsyncKeyword)),
+ MethodDeclarationSyntax method => (method.ReturnType, method.Modifiers.Any(SyntaxKind.AsyncKeyword)),
+ ConversionOperatorDeclarationSyntax conversion => (conversion.Type, false),
+ OperatorDeclarationSyntax op => (op.ReturnType, false),
+ BasePropertyDeclarationSyntax property => (property.Type, false),
+ AccessorDeclarationSyntax(SyntaxKind.GetAccessorDeclaration) { Parent: AccessorListSyntax { Parent: BasePropertyDeclarationSyntax baseProperty } } => (baseProperty.Type, false),
+ _ => default,
};
}
else if (objectCreation.Parent is InitializerExpressionSyntax { Parent: ObjectCreationExpressionSyntax { Type: var collectionType } })
@@ -147,6 +149,18 @@ public static bool Analyze(
if (leftType is null || rightType is null)
return false;
+ // In an async context, `Task` and `ValueTask` are considered the same as `T` for purposes of determining
+ // if the type is apparent. So `new()` is valid for `async Task M() { return new Goo(); }`.
+ var compilation = semanticModel.Compilation;
+ if (isAsync)
+ {
+ if (leftType.OriginalDefinition.Equals(compilation.TaskOfTType()) ||
+ leftType.OriginalDefinition.Equals(compilation.ValueTaskOfTType()))
+ {
+ leftType = leftType.GetTypeArguments().Single();
+ }
+ }
+
if (leftType.IsErrorType() || rightType.IsErrorType())
return false;
diff --git a/src/roslyn/src/Analyzers/CSharp/Analyzers/UseImplicitOrExplicitType/CSharpTypeStyleDiagnosticAnalyzerBase.cs b/src/roslyn/src/Analyzers/CSharp/Analyzers/UseImplicitOrExplicitType/CSharpTypeStyleDiagnosticAnalyzerBase.cs
index 2a10d0cd781..acd6f57ac95 100644
--- a/src/roslyn/src/Analyzers/CSharp/Analyzers/UseImplicitOrExplicitType/CSharpTypeStyleDiagnosticAnalyzerBase.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Analyzers/UseImplicitOrExplicitType/CSharpTypeStyleDiagnosticAnalyzerBase.cs
@@ -2,15 +2,24 @@
// The .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.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
-using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Diagnostics.TypeStyle;
+internal static class CSharpTypeStyleUtilities
+{
+ public const string EquivalenceyKey = nameof(EquivalenceyKey);
+
+ public const string BuiltInType = nameof(BuiltInType);
+ public const string TypeIsApparent = nameof(TypeIsApparent);
+ public const string Elsewhere = nameof(Elsewhere);
+}
+
internal abstract partial class CSharpTypeStyleDiagnosticAnalyzerBase(
string diagnosticId,
EnforceOnBuild enforceOnBuild,
@@ -21,6 +30,10 @@ internal abstract partial class CSharpTypeStyleDiagnosticAnalyzerBase(
[CSharpCodeStyleOptions.VarForBuiltInTypes, CSharpCodeStyleOptions.VarWhenTypeIsApparent, CSharpCodeStyleOptions.VarElsewhere],
title, message)
{
+ private static readonly ImmutableDictionary BuiltInTypeProperties = ImmutableDictionary.Empty.Add(CSharpTypeStyleUtilities.EquivalenceyKey, CSharpTypeStyleUtilities.BuiltInType);
+ private static readonly ImmutableDictionary TypeIsApparentProperties = ImmutableDictionary.Empty.Add(CSharpTypeStyleUtilities.EquivalenceyKey, CSharpTypeStyleUtilities.TypeIsApparent);
+ private static readonly ImmutableDictionary ElsewhereProperties = ImmutableDictionary.Empty.Add(CSharpTypeStyleUtilities.EquivalenceyKey, CSharpTypeStyleUtilities.Elsewhere);
+
protected abstract CSharpTypeStyleHelper Helper { get; }
public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
@@ -45,16 +58,25 @@ private void HandleVariableDeclaration(SyntaxNodeAnalysisContext context)
declaredType, semanticModel, simplifierOptions, cancellationToken);
if (!typeStyle.IsStylePreferred
|| ShouldSkipAnalysis(context, typeStyle.Notification)
- || !typeStyle.CanConvert())
+ || !typeStyle.CanConvert)
{
return;
}
// The severity preference is not Hidden, as indicated by IsStylePreferred.
var descriptor = Descriptor;
- context.ReportDiagnostic(CreateDiagnostic(descriptor, declarationStatement, declaredType.StripRefIfNeeded().Span, typeStyle.Notification, context.Options));
+ context.ReportDiagnostic(DiagnosticHelper.Create(
+ descriptor,
+ declarationStatement.SyntaxTree.GetLocation(declaredType.StripRefIfNeeded().Span),
+ typeStyle.Notification,
+ context.Options,
+ additionalLocations: null,
+ typeStyle.Context switch
+ {
+ CSharpTypeStyleHelper.Context.BuiltInType => BuiltInTypeProperties,
+ CSharpTypeStyleHelper.Context.TypeIsApparent => TypeIsApparentProperties,
+ CSharpTypeStyleHelper.Context.Elsewhere => ElsewhereProperties,
+ _ => throw ExceptionUtilities.UnexpectedValue(typeStyle.Context),
+ }));
}
-
- private static Diagnostic CreateDiagnostic(DiagnosticDescriptor descriptor, SyntaxNode declaration, TextSpan diagnosticSpan, NotificationOption2 notificationOption, AnalyzerOptions analyzerOptions)
- => DiagnosticHelper.Create(descriptor, declaration.SyntaxTree.GetLocation(diagnosticSpan), notificationOption, analyzerOptions, additionalLocations: null, properties: null);
}
diff --git a/src/roslyn/src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.cs b/src/roslyn/src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.cs
index c8d7838f535..e63d84195e4 100644
--- a/src/roslyn/src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.cs
@@ -329,8 +329,7 @@ private Diagnostic CreateDiagnostic(Result result, NotificationOption2 notificat
}
private static bool IsConstantInt32(IOperation operation, int? value = null)
- => operation.ConstantValue.HasValue &&
- operation.ConstantValue.Value is int i &&
+ => operation.ConstantValue is { HasValue: true, Value: int i } &&
(value == null || i == value);
private static bool IsWriteableIndexer(IInvocationOperation invocation, IPropertySymbol indexer)
diff --git a/src/roslyn/src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/Helpers.cs b/src/roslyn/src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/Helpers.cs
index 2848ad0d5f3..8f5a044ed66 100644
--- a/src/roslyn/src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/Helpers.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/Helpers.cs
@@ -34,7 +34,7 @@ public static bool IsStringRemoveMethod(IMethodSymbol method)
.FirstOrDefault();
public static bool IsPublicInstance(ISymbol symbol)
- => !symbol.IsStatic && symbol.DeclaredAccessibility == Accessibility.Public;
+ => symbol is { IsStatic: false, DeclaredAccessibility: Accessibility.Public };
///
/// Checks if this is `expr.Length` where `expr` is equivalent
@@ -42,8 +42,7 @@ public static bool IsPublicInstance(ISymbol symbol)
/// of.
///
public static bool IsInstanceLengthCheck(IPropertySymbol lengthLikeProperty, IOperation instance, IOperation operation)
- => operation is IPropertyReferenceOperation propertyRef &&
- propertyRef.Instance != null &&
+ => operation is IPropertyReferenceOperation { Instance: not null } propertyRef &&
lengthLikeProperty.Equals(propertyRef.Property) &&
CSharpSyntaxFacts.Instance.AreEquivalent(instance.Syntax, propertyRef.Instance.Syntax);
@@ -53,8 +52,7 @@ public static bool IsInstanceLengthCheck(IPropertySymbol lengthLikeProperty, IOp
///
public static bool IsSubtraction(IOperation operation, [NotNullWhen(true)] out IBinaryOperation? subtraction)
{
- if (operation is IBinaryOperation binaryOperation &&
- binaryOperation.OperatorKind == BinaryOperatorKind.Subtract)
+ if (operation is IBinaryOperation { OperatorKind: BinaryOperatorKind.Subtract } binaryOperation)
{
subtraction = binaryOperation;
return true;
diff --git a/src/roslyn/src/Analyzers/CSharp/Analyzers/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorDiagnosticAnalyzer.cs b/src/roslyn/src/Analyzers/CSharp/Analyzers/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorDiagnosticAnalyzer.cs
index 8879e612951..33cbdd42558 100644
--- a/src/roslyn/src/Analyzers/CSharp/Analyzers/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorDiagnosticAnalyzer.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Analyzers/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorDiagnosticAnalyzer.cs
@@ -78,13 +78,7 @@ private static bool IsObjectCastAndNullCheck(
var expressionType = semanticModel.GetTypeInfo(castExpression.Expression).Type;
if (expressionType != null)
{
- if (expressionType is ITypeParameterSymbol typeParameter &&
- !typeParameter.HasReferenceTypeConstraint)
- {
- return false;
- }
-
- return true;
+ return expressionType is not ITypeParameterSymbol { HasReferenceTypeConstraint: false };
}
}
}
diff --git a/src/roslyn/src/Analyzers/CSharp/Analyzers/UseLocalFunction/CSharpUseLocalFunctionDiagnosticAnalyzer.cs b/src/roslyn/src/Analyzers/CSharp/Analyzers/UseLocalFunction/CSharpUseLocalFunctionDiagnosticAnalyzer.cs
index d714d421f3d..76e737075fb 100644
--- a/src/roslyn/src/Analyzers/CSharp/Analyzers/UseLocalFunction/CSharpUseLocalFunctionDiagnosticAnalyzer.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Analyzers/UseLocalFunction/CSharpUseLocalFunctionDiagnosticAnalyzer.cs
@@ -277,8 +277,7 @@ private static bool CanReplaceAnonymousWithLocalFunction(
}
else if (nodeToCheck.Parent is MemberAccessExpressionSyntax memberAccessExpression)
{
- if (memberAccessExpression.Parent is InvocationExpressionSyntax explicitInvocationExpression &&
- memberAccessExpression.Name.Identifier.ValueText == WellKnownMemberNames.DelegateInvokeName)
+ if (memberAccessExpression is { Parent: InvocationExpressionSyntax explicitInvocationExpression, Name.Identifier.ValueText: WellKnownMemberNames.DelegateInvokeName })
{
references.Add(explicitInvocationExpression.GetLocation());
}
@@ -350,9 +349,7 @@ private static bool CheckForLocalDeclarationAndAssignment(
{
// Type t = null;
// t =
- if (anonymousFunction?.Parent is AssignmentExpressionSyntax(SyntaxKind.SimpleAssignmentExpression) assignment &&
- assignment.Parent is ExpressionStatementSyntax expressionStatement &&
- expressionStatement.Parent is BlockSyntax block)
+ if (anonymousFunction?.Parent is AssignmentExpressionSyntax(SyntaxKind.SimpleAssignmentExpression) { Parent: ExpressionStatementSyntax { Parent: BlockSyntax block } expressionStatement } assignment)
{
if (assignment.Left.IsKind(SyntaxKind.IdentifierName))
{
diff --git a/src/roslyn/src/Analyzers/CSharp/CodeFixes/AddAnonymousTypeMemberName/CSharpAddAnonymousTypeMemberNameCodeFixProvider.cs b/src/roslyn/src/Analyzers/CSharp/CodeFixes/AddAnonymousTypeMemberName/CSharpAddAnonymousTypeMemberNameCodeFixProvider.cs
index 35252af110f..1ff979d1bff 100644
--- a/src/roslyn/src/Analyzers/CSharp/CodeFixes/AddAnonymousTypeMemberName/CSharpAddAnonymousTypeMemberNameCodeFixProvider.cs
+++ b/src/roslyn/src/Analyzers/CSharp/CodeFixes/AddAnonymousTypeMemberName/CSharpAddAnonymousTypeMemberNameCodeFixProvider.cs
@@ -10,6 +10,7 @@
using Microsoft.CodeAnalysis.AddAnonymousTypeMemberName;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.AddAnonymousTypeMemberName;
@@ -39,5 +40,5 @@ protected override AnonymousObjectMemberDeclaratorSyntax WithName(AnonymousObjec
SyntaxFactory.IdentifierName(name)));
protected override IEnumerable GetAnonymousObjectMemberNames(AnonymousObjectCreationExpressionSyntax initializer)
- => initializer.Initializers.Where(i => i.NameEquals != null).Select(i => i.NameEquals!.Name.Identifier.ValueText);
+ => initializer.Initializers.SelectAsArray(i => i.NameEquals != null, i => i.NameEquals!.Name.Identifier.ValueText);
}
diff --git a/src/roslyn/src/Analyzers/CSharp/CodeFixes/CSharpCodeFixes.projitems b/src/roslyn/src/Analyzers/CSharp/CodeFixes/CSharpCodeFixes.projitems
index 968dd83fb7e..6237c865efa 100644
--- a/src/roslyn/src/Analyzers/CSharp/CodeFixes/CSharpCodeFixes.projitems
+++ b/src/roslyn/src/Analyzers/CSharp/CodeFixes/CSharpCodeFixes.projitems
@@ -75,7 +75,6 @@
-
@@ -85,8 +84,6 @@
-
-
@@ -193,4 +190,4 @@
-
\ No newline at end of file
+
diff --git a/src/roslyn/src/Analyzers/CSharp/CodeFixes/MakeLocalFunctionStatic/MakeLocalFunctionStaticCodeFixHelper.cs b/src/roslyn/src/Analyzers/CSharp/CodeFixes/MakeLocalFunctionStatic/MakeLocalFunctionStaticCodeFixHelper.cs
index 0be3c5fc586..9027b048348 100644
--- a/src/roslyn/src/Analyzers/CSharp/CodeFixes/MakeLocalFunctionStatic/MakeLocalFunctionStaticCodeFixHelper.cs
+++ b/src/roslyn/src/Analyzers/CSharp/CodeFixes/MakeLocalFunctionStatic/MakeLocalFunctionStaticCodeFixHelper.cs
@@ -98,7 +98,8 @@ public static async Task MakeLocalFunctionStaticAsync(
var seenDefaultArgumentValue = currentInvocation.ArgumentList.Arguments.Count < localFunction.ParameterList.Parameters.Count;
// Add all the non-this parameters to the end. If there is a 'this' parameter, add it to the start.
- var newArguments = parameterAndCapturedSymbols.Where(p => !p.symbol.IsThisParameter()).Select(
+ var newArguments = parameterAndCapturedSymbols.SelectAsArray(
+ p => !p.symbol.IsThisParameter(),
symbolAndCapture => (ArgumentSyntax)generator.Argument(
seenNamedArgument || seenDefaultArgumentValue ? symbolAndCapture.symbol.Name : null,
symbolAndCapture.symbol.RefKind,
diff --git a/src/roslyn/src/Analyzers/CSharp/CodeFixes/MakeMethodSynchronous/CSharpMakeMethodSynchronousCodeFixProvider.cs b/src/roslyn/src/Analyzers/CSharp/CodeFixes/MakeMethodSynchronous/CSharpMakeMethodSynchronousCodeFixProvider.cs
deleted file mode 100644
index de80287f51a..00000000000
--- a/src/roslyn/src/Analyzers/CSharp/CodeFixes/MakeMethodSynchronous/CSharpMakeMethodSynchronousCodeFixProvider.cs
+++ /dev/null
@@ -1,86 +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.Composition;
-using System.Diagnostics.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeFixes;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.RemoveAsyncModifier;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.MakeMethodSynchronous;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-
-namespace Microsoft.CodeAnalysis.CSharp.MakeMethodSynchronous;
-
-using static CSharpSyntaxTokens;
-
-[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MakeMethodSynchronous), Shared]
-[ExtensionOrder(After = PredefinedCodeFixProviderNames.AddImport)]
-[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 CSharpMakeMethodSynchronousCodeFixProvider() : AbstractMakeMethodSynchronousCodeFixProvider
-{
- private const string CS1998 = nameof(CS1998); // This async method lacks 'await' operators and will run synchronously.
-
- public override ImmutableArray FixableDiagnosticIds { get; } = [CS1998];
-
- protected override bool IsAsyncSupportingFunctionSyntax(SyntaxNode node)
- => node.IsAsyncSupportingFunctionSyntax();
-
- protected override SyntaxNode RemoveAsyncTokenAndFixReturnType(IMethodSymbol methodSymbol, SyntaxNode node, KnownTaskTypes knownTypes)
- {
- switch (node)
- {
- case MethodDeclarationSyntax method: return FixMethod(methodSymbol, method, knownTypes);
- case LocalFunctionStatementSyntax localFunction: return FixLocalFunction(methodSymbol, localFunction, knownTypes);
- case AnonymousMethodExpressionSyntax method: return RemoveAsyncModifierHelpers.WithoutAsyncModifier(method);
- case ParenthesizedLambdaExpressionSyntax lambda: return RemoveAsyncModifierHelpers.WithoutAsyncModifier(lambda);
- case SimpleLambdaExpressionSyntax lambda: return RemoveAsyncModifierHelpers.WithoutAsyncModifier(lambda);
- default: return node;
- }
- }
- private static SyntaxNode FixMethod(IMethodSymbol methodSymbol, MethodDeclarationSyntax method, KnownTaskTypes knownTypes)
- {
- var newReturnType = FixMethodReturnType(methodSymbol, method.ReturnType, knownTypes);
- return RemoveAsyncModifierHelpers.WithoutAsyncModifier(method, newReturnType);
- }
-
- private static SyntaxNode FixLocalFunction(IMethodSymbol methodSymbol, LocalFunctionStatementSyntax localFunction, KnownTaskTypes knownTypes)
- {
- var newReturnType = FixMethodReturnType(methodSymbol, localFunction.ReturnType, knownTypes);
- return RemoveAsyncModifierHelpers.WithoutAsyncModifier(localFunction, newReturnType);
- }
-
- private static TypeSyntax FixMethodReturnType(IMethodSymbol methodSymbol, TypeSyntax returnTypeSyntax, KnownTaskTypes knownTypes)
- {
- var newReturnType = returnTypeSyntax;
-
- var returnType = methodSymbol.ReturnType;
- if (returnType.OriginalDefinition.Equals(knownTypes.TaskType))
- {
- // If the return type is Task, then make the new return type "void".
- newReturnType = SyntaxFactory.PredefinedType(VoidKeyword).WithTriviaFrom(returnTypeSyntax);
- }
- else if (returnType.OriginalDefinition.Equals(knownTypes.TaskOfTType))
- {
- // If the return type is Task, then make the new return type "T".
- newReturnType = returnType.GetTypeArguments()[0].GenerateTypeSyntax().WithTriviaFrom(returnTypeSyntax);
- }
- else if (returnType.OriginalDefinition.Equals(knownTypes.IAsyncEnumerableOfTType) &&
- knownTypes.IEnumerableOfTType != null)
- {
- // If the return type is IAsyncEnumerable, then make the new return type IEnumerable.
- newReturnType = knownTypes.IEnumerableOfTType.Construct(methodSymbol.ReturnType.GetTypeArguments()[0]).GenerateTypeSyntax();
- }
- else if (returnType.OriginalDefinition.Equals(knownTypes.IAsyncEnumeratorOfTType) &&
- knownTypes.IEnumeratorOfTType != null)
- {
- // If the return type is IAsyncEnumerator, then make the new return type IEnumerator.
- newReturnType = knownTypes.IEnumeratorOfTType.Construct(methodSymbol.ReturnType.GetTypeArguments()[0]).GenerateTypeSyntax();
- }
-
- return newReturnType;
- }
-}
diff --git a/src/roslyn/src/Analyzers/CSharp/CodeFixes/RemoveAsyncModifier/CSharpRemoveAsyncModifierCodeFixProvider.cs b/src/roslyn/src/Analyzers/CSharp/CodeFixes/RemoveAsyncModifier/CSharpRemoveAsyncModifierCodeFixProvider.cs
deleted file mode 100644
index 9c5c3e27552..00000000000
--- a/src/roslyn/src/Analyzers/CSharp/CodeFixes/RemoveAsyncModifier/CSharpRemoveAsyncModifierCodeFixProvider.cs
+++ /dev/null
@@ -1,66 +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.Composition;
-using System.Diagnostics.CodeAnalysis;
-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.RemoveAsyncModifier;
-
-namespace Microsoft.CodeAnalysis.CSharp.RemoveAsyncModifier;
-
-using static CSharpSyntaxTokens;
-
-[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveAsyncModifier), Shared]
-[ExtensionOrder(After = PredefinedCodeFixProviderNames.MakeMethodSynchronous)]
-[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 CSharpRemoveAsyncModifierCodeFixProvider() : AbstractRemoveAsyncModifierCodeFixProvider
-{
- private const string CS1998 = nameof(CS1998); // This async method lacks 'await' operators and will run synchronously.
-
- public override ImmutableArray FixableDiagnosticIds { get; } = [CS1998];
-
- protected override bool IsAsyncSupportingFunctionSyntax(SyntaxNode node)
- => node.IsAsyncSupportingFunctionSyntax();
-
- protected override SyntaxNode? ConvertToBlockBody(SyntaxNode node, ExpressionSyntax expressionBody)
- {
- var semicolonToken = SemicolonToken;
- if (expressionBody.TryConvertToStatement(semicolonToken, createReturnStatementForExpression: false, out var statement))
- {
- var block = SyntaxFactory.Block(statement);
- return node switch
- {
- MethodDeclarationSyntax method => method.WithBody(block).WithExpressionBody(null).WithSemicolonToken(default),
- LocalFunctionStatementSyntax localFunction => localFunction.WithBody(block).WithExpressionBody(null).WithSemicolonToken(default),
- AnonymousFunctionExpressionSyntax anonymousFunction => anonymousFunction.WithBody(block).WithExpressionBody(null),
- _ => throw ExceptionUtilities.Unreachable()
- };
- }
-
- return null;
- }
-
- protected override SyntaxNode RemoveAsyncModifier(SyntaxGenerator generator, SyntaxNode methodLikeNode)
- => methodLikeNode switch
- {
- MethodDeclarationSyntax method => RemoveAsyncModifierHelpers.WithoutAsyncModifier(method, method.ReturnType),
- LocalFunctionStatementSyntax localFunction => RemoveAsyncModifierHelpers.WithoutAsyncModifier(localFunction, localFunction.ReturnType),
- AnonymousMethodExpressionSyntax method => AnnotateBlock(generator, RemoveAsyncModifierHelpers.WithoutAsyncModifier(method)),
- ParenthesizedLambdaExpressionSyntax lambda => AnnotateBlock(generator, RemoveAsyncModifierHelpers.WithoutAsyncModifier(lambda)),
- SimpleLambdaExpressionSyntax lambda => AnnotateBlock(generator, RemoveAsyncModifierHelpers.WithoutAsyncModifier(lambda)),
- _ => methodLikeNode,
- };
-
- // Block bodied lambdas and anonymous methods need to be formatted after changing their modifiers, or their indentation is broken
- private static SyntaxNode AnnotateBlock(SyntaxGenerator generator, SyntaxNode node)
- => generator.GetExpression(node) == null
- ? node.WithAdditionalAnnotations(Formatter.Annotation)
- : node;
-}
diff --git a/src/roslyn/src/Analyzers/CSharp/CodeFixes/RemoveAsyncModifier/RemoveAsyncModifierHelpers.cs b/src/roslyn/src/Analyzers/CSharp/CodeFixes/RemoveAsyncModifier/RemoveAsyncModifierHelpers.cs
deleted file mode 100644
index 1df3eefea5e..00000000000
--- a/src/roslyn/src/Analyzers/CSharp/CodeFixes/RemoveAsyncModifier/RemoveAsyncModifierHelpers.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 Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-
-namespace Microsoft.CodeAnalysis.CSharp.RemoveAsyncModifier;
-
-internal static class RemoveAsyncModifierHelpers
-{
- internal static SyntaxNode WithoutAsyncModifier(MethodDeclarationSyntax method, TypeSyntax returnType)
- {
- var newModifiers = RemoveAsyncModifier(method.Modifiers, ref returnType);
- return method.WithReturnType(returnType).WithModifiers(newModifiers);
- }
-
- internal static SyntaxNode WithoutAsyncModifier(LocalFunctionStatementSyntax localFunction, TypeSyntax returnType)
- {
- var newModifiers = RemoveAsyncModifier(localFunction.Modifiers, ref returnType);
- return localFunction.WithReturnType(returnType).WithModifiers(newModifiers);
- }
-
- internal static SyntaxNode WithoutAsyncModifier(ParenthesizedLambdaExpressionSyntax lambda)
- => lambda.WithAsyncKeyword(default).WithPrependedLeadingTrivia(lambda.AsyncKeyword.LeadingTrivia);
-
- internal static SyntaxNode WithoutAsyncModifier(SimpleLambdaExpressionSyntax lambda)
- => lambda.WithAsyncKeyword(default).WithPrependedLeadingTrivia(lambda.AsyncKeyword.LeadingTrivia);
-
- internal static SyntaxNode WithoutAsyncModifier(AnonymousMethodExpressionSyntax method)
- => method.WithAsyncKeyword(default).WithPrependedLeadingTrivia(method.AsyncKeyword.LeadingTrivia);
-
- private static SyntaxTokenList RemoveAsyncModifier(SyntaxTokenList modifiers, ref TypeSyntax newReturnType)
- {
- var asyncTokenIndex = modifiers.IndexOf(SyntaxKind.AsyncKeyword);
- SyntaxTokenList newModifiers;
- if (asyncTokenIndex == 0)
- {
- // Have to move the trivia on the async token appropriately.
- var asyncLeadingTrivia = modifiers[0].LeadingTrivia;
-
- if (modifiers.Count > 1)
- {
- // Move the trivia to the next modifier;
- newModifiers = modifiers.Replace(
- modifiers[1],
- modifiers[1].WithPrependedLeadingTrivia(asyncLeadingTrivia));
- newModifiers = newModifiers.RemoveAt(0);
- }
- else
- {
- // move it to the return type.
- newModifiers = default;
- newReturnType = newReturnType.WithPrependedLeadingTrivia(asyncLeadingTrivia);
- }
- }
- else
- {
- newModifiers = modifiers.RemoveAt(asyncTokenIndex);
- }
-
- return newModifiers;
- }
-}
diff --git a/src/roslyn/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseExplicitTypeCodeFixProvider.cs b/src/roslyn/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseExplicitTypeCodeFixProvider.cs
index fd0d0c27082..96db15d5bd1 100644
--- a/src/roslyn/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseExplicitTypeCodeFixProvider.cs
+++ b/src/roslyn/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseExplicitTypeCodeFixProvider.cs
@@ -10,6 +10,7 @@
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
+using Microsoft.CodeAnalysis.CSharp.Diagnostics.TypeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
@@ -35,10 +36,16 @@ public override ImmutableArray FixableDiagnosticIds
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
- RegisterCodeFix(context, CSharpAnalyzersResources.Use_explicit_type_instead_of_var, nameof(CSharpAnalyzersResources.Use_explicit_type_instead_of_var));
+ RegisterCodeFix(
+ context,
+ CSharpAnalyzersResources.Use_explicit_type_instead_of_var,
+ context.Diagnostics.First().Properties[CSharpTypeStyleUtilities.EquivalenceyKey]!);
return Task.CompletedTask;
}
+ protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic, Document document, string? equivalenceKey, CancellationToken cancellationToken)
+ => diagnostic.Properties[CSharpTypeStyleUtilities.EquivalenceyKey] == equivalenceKey;
+
protected override async Task FixAllAsync(
Document document, ImmutableArray diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
@@ -95,7 +102,7 @@ private static async Task HandleDeclarationExpressionAsync(Document document, Sy
var tupleTypeSymbol = GetConvertedType(semanticModel, typeSyntax.Parent, cancellationToken);
var leadingTrivia = declarationExpression.GetLeadingTrivia()
- .Concat(variableDesignation.GetAllPrecedingTriviaToPreviousToken().Where(t => !t.IsWhitespace()).Select(t => t.WithoutAnnotations(SyntaxAnnotation.ElasticAnnotation)));
+ .Concat(variableDesignation.GetAllPrecedingTriviaToPreviousToken().SelectAsArray(t => !t.IsWhitespace(), t => t.WithoutAnnotations(SyntaxAnnotation.ElasticAnnotation)));
var tupleDeclaration = GenerateTupleDeclaration(
semanticModel, tupleTypeSymbol, variableDesignation, cancellationToken).WithLeadingTrivia(leadingTrivia);
diff --git a/src/roslyn/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseImplicitTypeCodeFixProvider.cs b/src/roslyn/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseImplicitTypeCodeFixProvider.cs
index 9e7e7aefb59..8de161fe7de 100644
--- a/src/roslyn/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseImplicitTypeCodeFixProvider.cs
+++ b/src/roslyn/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseImplicitTypeCodeFixProvider.cs
@@ -5,9 +5,11 @@
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
+using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
+using Microsoft.CodeAnalysis.CSharp.Diagnostics.TypeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
@@ -25,10 +27,16 @@ public override ImmutableArray FixableDiagnosticIds
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
- RegisterCodeFix(context, CSharpAnalyzersResources.use_var_instead_of_explicit_type, nameof(CSharpAnalyzersResources.use_var_instead_of_explicit_type));
+ RegisterCodeFix(
+ context,
+ CSharpAnalyzersResources.use_var_instead_of_explicit_type,
+ context.Diagnostics.First().Properties[CSharpTypeStyleUtilities.EquivalenceyKey]!);
return Task.CompletedTask;
}
+ protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic, Document document, string? equivalenceKey, CancellationToken cancellationToken)
+ => diagnostic.Properties[CSharpTypeStyleUtilities.EquivalenceyKey] == equivalenceKey;
+
protected override Task FixAllAsync(
Document document, ImmutableArray diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
diff --git a/src/roslyn/src/Analyzers/CSharp/Tests/CSharpAnalyzers.UnitTests.projitems b/src/roslyn/src/Analyzers/CSharp/Tests/CSharpAnalyzers.UnitTests.projitems
index bd9e6cf7e65..ea632d2d4b2 100644
--- a/src/roslyn/src/Analyzers/CSharp/Tests/CSharpAnalyzers.UnitTests.projitems
+++ b/src/roslyn/src/Analyzers/CSharp/Tests/CSharpAnalyzers.UnitTests.projitems
@@ -50,8 +50,6 @@
-
-
@@ -66,7 +64,6 @@
-
@@ -172,7 +169,7 @@
-
+
@@ -205,4 +202,4 @@
-
\ No newline at end of file
+
diff --git a/src/roslyn/src/Analyzers/CSharp/Tests/GenerateConstructor/GenerateConstructorTests.cs b/src/roslyn/src/Analyzers/CSharp/Tests/GenerateConstructor/GenerateConstructorTests.cs
index 5ddc54f833a..2a4674e2160 100644
--- a/src/roslyn/src/Analyzers/CSharp/Tests/GenerateConstructor/GenerateConstructorTests.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Tests/GenerateConstructor/GenerateConstructorTests.cs
@@ -25,7 +25,7 @@ public sealed class GenerateConstructorTests(ITestOutputHelper logger)
internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (null, new GenerateConstructorCodeFixProvider());
- private readonly NamingStylesTestOptionSets options = new NamingStylesTestOptionSets(LanguageNames.CSharp);
+ private readonly NamingStylesTestOptionSets options = new(LanguageNames.CSharp);
[Fact]
public Task TestWithSimpleArgument()
diff --git a/src/roslyn/src/Analyzers/CSharp/Tests/ImplementAbstractClass/ImplementAbstractClassTests_ThroughMember.cs b/src/roslyn/src/Analyzers/CSharp/Tests/ImplementAbstractClass/ImplementAbstractClassTests_ThroughMember.cs
index 37a1d66bd08..dd8c167d88a 100644
--- a/src/roslyn/src/Analyzers/CSharp/Tests/ImplementAbstractClass/ImplementAbstractClassTests_ThroughMember.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Tests/ImplementAbstractClass/ImplementAbstractClassTests_ThroughMember.cs
@@ -24,7 +24,7 @@ internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProvide
=> (null, new CSharpImplementAbstractClassCodeFixProvider());
private OptionsCollection AllOptionsOff
- => new OptionsCollection(GetLanguage())
+ => new(GetLanguage())
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
diff --git a/src/roslyn/src/Analyzers/CSharp/Tests/InlineDeclaration/CSharpInlineDeclarationTests.cs b/src/roslyn/src/Analyzers/CSharp/Tests/InlineDeclaration/CSharpInlineDeclarationTests.cs
index b6b375a5ded..eed2e944d8b 100644
--- a/src/roslyn/src/Analyzers/CSharp/Tests/InlineDeclaration/CSharpInlineDeclarationTests.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Tests/InlineDeclaration/CSharpInlineDeclarationTests.cs
@@ -11,7 +11,7 @@
using Microsoft.CodeAnalysis.CSharp.InlineDeclaration;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
-using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseImplicitType;
+using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseImplicitOrExplicitType;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
diff --git a/src/roslyn/src/Analyzers/CSharp/Tests/MakeMethodAsynchronous/MakeMethodAsynchronousTests.cs b/src/roslyn/src/Analyzers/CSharp/Tests/MakeMethodAsynchronous/MakeMethodAsynchronousTests.cs
deleted file mode 100644
index ac66ce324df..00000000000
--- a/src/roslyn/src/Analyzers/CSharp/Tests/MakeMethodAsynchronous/MakeMethodAsynchronousTests.cs
+++ /dev/null
@@ -1,1522 +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.CodeFixes;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.MakeMethodAsynchronous;
-using Microsoft.CodeAnalysis.Diagnostics;
-using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
-using Microsoft.CodeAnalysis.Test.Utilities;
-using Roslyn.Test.Utilities;
-using Xunit;
-using Xunit.Abstractions;
-
-namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeMethodAsynchronous;
-
-[Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)]
-public sealed partial class MakeMethodAsynchronousTests(ITestOutputHelper logger)
- : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest_NoEditor(logger)
-{
- internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
- => (null, new CSharpMakeMethodAsynchronousCodeFixProvider());
-
- [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33082")]
- public Task AwaitInVoidMethodWithModifiers()
- => TestInRegularAndScriptAsync("""
- using System;
- using System.Threading.Tasks;
-
- class Program
- {
- public static void Test()
- {
- [|await Task.Delay(1);|]
- }
- }
- """, """
- using System;
- using System.Threading.Tasks;
-
- class Program
- {
- public static async void Test()
- {
- await Task.Delay(1);
- }
- }
- """, index: 1);
-
- [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26312")]
- public async Task AwaitInTaskMainMethodWithModifiers()
- {
- var initial =
- """
- using System;
- using System.Threading.Tasks;
-
- class Program
- {
- public static void Main()
- {
- [|await Task.Delay(1);|]
- }
- }
- """;
- await TestAsync(initial, """
- using System;
- using System.Threading.Tasks;
-
- class Program
- {
- public static async Task Main()
- {
- await Task.Delay(1);
- }
- }
- """, new(parseOptions: CSharpParseOptions.Default,
- compilationOptions: new CSharpCompilationOptions(OutputKind.ConsoleApplication)));
-
- // no option offered to keep void
- await TestActionCountAsync(initial, count: 1, new TestParameters(compilationOptions: new CSharpCompilationOptions(OutputKind.ConsoleApplication)));
- }
-
- [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26312")]
- [WorkItem("https://github.com/dotnet/roslyn/issues/33082")]
- public Task AwaitInVoidMainMethodWithModifiers_NotEntryPoint()
- => TestInRegularAndScriptAsync("""
- using System;
- using System.Threading.Tasks;
-
- class Program
- {
- public void Main()
- {
- [|await Task.Delay(1);|]
- }
- }
- """, """
- using System;
- using System.Threading.Tasks;
-
- class Program
- {
- public async void Main()
- {
- await Task.Delay(1);
- }
- }
- """, index: 1);
-
- [Fact]
- public Task AwaitInVoidMethodWithModifiers2()
- => TestInRegularAndScriptAsync("""
- using System;
- using System.Threading.Tasks;
-
- class Program
- {
- public static void Test()
- {
- [|await Task.Delay(1);|]
- }
- }
- """, """
- using System;
- using System.Threading.Tasks;
-
- class Program
- {
- public static async Task TestAsync()
- {
- await Task.Delay(1);
- }
- }
- """);
-
- [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33082")]
- public Task AwaitInTaskMethodNoModifiers()
- => TestInRegularAndScriptAsync("""
- using System;
- using System.Threading.Tasks;
-
- class Program
- {
- Task Test()
- {
- [|await Task.Delay(1);|]
- }
- }
- """, """
- using System;
- using System.Threading.Tasks;
-
- class Program
- {
- async Task Test()
- {
- await Task.Delay(1);
- }
- }
- """);
-
- [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33082")]
- public Task AwaitInTaskMethodWithModifiers()
- => TestInRegularAndScriptAsync("""
- using System;
- using System.Threading.Tasks;
-
- class Program
- {
- public/*Comment*/static/*Comment*/Task/*Comment*/Test()
- {
- [|await Task.Delay(1);|]
- }
- }
- """, """
- using System;
- using System.Threading.Tasks;
-
- class Program
- {
- public/*Comment*/static/*Comment*/async Task/*Comment*/Test()
- {
- await Task.Delay(1);
- }
- }
- """);
-
- [Fact]
- public Task AwaitInLambdaFunction()
- => TestInRegularAndScriptAsync("""
- using System;
- using System.Threading.Tasks;
-
- class Program
- {
- static void Main(string[] args)
- {
- Action a = () => Console.WriteLine();
- Func b = () => [|await Task.Run(a);|]
- }
- }
- """, """
- using System;
- using System.Threading.Tasks;
-
- class Program
- {
- static void Main(string[] args)
- {
- Action a = () => Console.WriteLine();
- Func b = async () => await Task.Run(a);
- }
- }
- """);
-
- [Fact]
- public Task AwaitInLambdaAction()
- => TestInRegularAndScriptAsync("""
- using System;
- using System.Threading.Tasks;
-
- class Program
- {
- static void Main(string[] args)
- {
- Action a = () => [|await Task.Delay(1);|]
- }
- }
- """, """
- using System;
- using System.Threading.Tasks;
-
- class Program
- {
- static void Main(string[] args)
- {
- Action a = async () => await Task.Delay(1);
- }
- }
- """);
-
- [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33082")]
- public Task BadAwaitInNonAsyncMethod()
- => TestInRegularAndScriptAsync("""
- using System.Threading.Tasks;
- class Program
- {
- void Test()
- {
- [|await Task.Delay(1);|]
- }
- }
- """, """
- using System.Threading.Tasks;
- class Program
- {
- async void Test()
- {
- await Task.Delay(1);
- }
- }
- """, index: 1);
-
- [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33082")]
- public Task BadAwaitInNonAsyncMethod2()
- => TestInRegularAndScriptAsync("""
- using System.Threading.Tasks;
- class Program
- {
- Task Test()
- {
- [|await Task.Delay(1);|]
- }
- }
- """, """
- using System.Threading.Tasks;
- class Program
- {
- async Task Test()
- {
- await Task.Delay(1);
- }
- }
- """);
-
- [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33082")]
- public Task BadAwaitInNonAsyncMethod3()
- => TestInRegularAndScriptAsync("""
- using System.Threading.Tasks;
- class Program
- {
- Task Test()
- {
- [|await Task.Delay(1);|]
- }
- }
- """, """
- using System.Threading.Tasks;
- class Program
- {
- async Task Test()
- {
- await Task.Delay(1);
- }
- }
- """);
-
- [Fact]
- public Task BadAwaitInNonAsyncMethod4()
- => TestInRegularAndScriptAsync("""
- using System.Threading.Tasks;
- class Program
- {
- int Test()
- {
- [|await Task.Delay(1);|]
- }
- }
- """, """
- using System.Threading.Tasks;
- class Program
- {
- async Task TestAsync()
- {
- await Task.Delay(1);
- }
- }
- """);
-
- [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33082")]
- public Task BadAwaitInNonAsyncMethod5()
- => TestInRegularAndScriptAsync("""
- class Program
- {
- void Test()
- {
- [|await Task.Delay(1);|]
- }
- }
- """, """
- class Program
- {
- async void Test()
- {
- await Task.Delay(1);
- }
- }
- """, index: 1);
-
- [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33082")]
- public Task BadAwaitInNonAsyncMethod6()
- => TestInRegularAndScriptAsync("""
- class Program
- {
- Task Test()
- {
- [|await Task.Delay(1);|]
- }
- }
- """, """
- class Program
- {
- async Task Test()
- {
- await Task.Delay(1);
- }
- }
- """);
-
- [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33082")]
- public Task BadAwaitInNonAsyncMethod7()
- => TestInRegularAndScriptAsync("""
- class Program
- {
- Task Test()
- {
- [|await Task.Delay(1);|]
- }
- }
- """, """
- class Program
- {
- async Task Test()
- {
- await Task.Delay(1);
- }
- }
- """);
-
- [Fact]
- public Task BadAwaitInNonAsyncMethod8()
- => TestInRegularAndScriptAsync("""
- class Program
- {
- int Test()
- {
- [|await Task.Delay(1);|]
- }
- }
- """, """
- using System.Threading.Tasks;
-
- class Program
- {
- async Task TestAsync()
- {
- await Task.Delay(1);
- }
- }
- """);
-
- [Fact]
- public Task BadAwaitInNonAsyncMethod9()
- => TestInRegularAndScriptAsync("""
- class Program
- {
- Program Test()
- {
- [|await Task.Delay(1);|]
- }
- }
- """, """
- using System.Threading.Tasks;
-
- class Program
- {
- async Task TestAsync()
- {
- await Task.Delay(1);
- }
- }
- """);
-
- [Fact]
- public Task BadAwaitInNonAsyncMethod10()
- => TestInRegularAndScriptAsync("""
- class Program
- {
- asdf Test()
- {
- [|await Task.Delay(1);|]
- }
- }
- """, """
- class Program
- {
- async System.Threading.Tasks.Task TestAsync()
- {
- await Task.Delay(1);
- }
- }
- """);
-
- [Fact]
- public async Task BadAwaitInEnumerableMethod()
- {
- var initial =
- """
- using System.Threading.Tasks;
- using System.Collections.Generic;
- class Program
- {
- IEnumerable Test()
- {
- yield return 1;
- [|await Task.Delay(1);|]
- }
- }
- """ + IAsyncEnumerable;
-
- var expected =
- """
- using System.Threading.Tasks;
- using System.Collections.Generic;
- class Program
- {
- async IAsyncEnumerable TestAsync()
- {
- yield return 1;
- await Task.Delay(1);
- }
- }
- """ + IAsyncEnumerable;
- await TestInRegularAndScriptAsync(initial, expected);
- }
-
- [Fact]
- public Task BadAwaitInEnumerableMethodMissingIAsyncEnumerableType()
- => TestInRegularAndScriptAsync("""
- using System.Threading.Tasks;
- using System.Collections.Generic;
- class Program
- {
- IEnumerable Test()
- {
- yield return 1;
- [|await Task.Delay(1);|]
- }
- }
- """, """
- using System.Threading.Tasks;
- using System.Collections.Generic;
- class Program
- {
- async IAsyncEnumerable TestAsync()
- {
- yield return 1;
- await Task.Delay(1);
- }
- }
- """);
-
- [Fact]
- public Task BadAwaitInEnumerableMethodWithReturn()
- => TestInRegularAndScriptAsync("""
- using System.Threading.Tasks;
- using System.Collections.Generic;
- class Program
- {
- IEnumerable Test()
- {
- [|await Task.Delay(1);|]
- return null;
- }
- }
- """, """
- using System.Threading.Tasks;
- using System.Collections.Generic;
- class Program
- {
- async Task> TestAsync()
- {
- await Task.Delay(1);
- return null;
- }
- }
- """);
-
- [Fact]
- public Task BadAwaitInEnumerableMethodWithYieldInsideLocalFunction()
- => TestInRegularAndScriptAsync("""
- using System.Threading.Tasks;
- using System.Collections.Generic;
- class Program
- {
- IEnumerable Test()
- {
- [|await Task.Delay(1);|]
- return local();
-
- IEnumerable local()
- {
- yield return 1;
- }
- }
- }
- """, """
- using System.Threading.Tasks;
- using System.Collections.Generic;
- class Program
- {
- async Task> TestAsync()
- {
- await Task.Delay(1);
- return local();
-
- IEnumerable local()
- {
- yield return 1;
- }
- }
- }
- """);
-
- [Fact]
- public Task BadAwaitInEnumeratorMethodWithReturn()
- => TestInRegularAndScriptAsync("""
- using System.Threading.Tasks;
- using System.Collections.Generic;
- class Program
- {
- IEnumerator Test()
- {
- [|await Task.Delay(1);|]
- return null;
- }
- }
- """, """
- using System.Threading.Tasks;
- using System.Collections.Generic;
- class Program
- {
- async Task> TestAsync()
- {
- await Task.Delay(1);
- return null;
- }
- }
- """);
-
- [Fact]
- public async Task BadAwaitInEnumeratorMethod()
- {
- var initial =
- """
- using System.Threading.Tasks;
- using System.Collections.Generic;
- class Program
- {
- IEnumerator Test()
- {
- yield return 1;
- [|await Task.Delay(1);|]
- }
- }
- """ + IAsyncEnumerable;
-
- var expected =
- """
- using System.Threading.Tasks;
- using System.Collections.Generic;
- class Program
- {
- async IAsyncEnumerator TestAsync()
- {
- yield return 1;
- await Task.Delay(1);
- }
- }
- """ + IAsyncEnumerable;
- await TestInRegularAndScriptAsync(initial, expected);
- }
-
- [Fact]
- public async Task BadAwaitInEnumeratorLocalFunction()
- {
- var initial =
- """
- using System.Threading.Tasks;
- using System.Collections.Generic;
- class Program
- {
- void M()
- {
- IEnumerator Test()
- {
- yield return 1;
- [|await Task.Delay(1);|]
- }
- }
- }
- """ + IAsyncEnumerable;
-
- var expected =
- """
- using System.Threading.Tasks;
- using System.Collections.Generic;
- class Program
- {
- void M()
- {
- async IAsyncEnumerator TestAsync()
- {
- yield return 1;
- await Task.Delay(1);
- }
- }
- }
- """ + IAsyncEnumerable;
- await TestInRegularAndScriptAsync(initial, expected);
- }
-
- [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33082")]
- public async Task BadAwaitInIAsyncEnumerableMethod()
- {
- var initial =
- """
- using System.Threading.Tasks;
- using System.Collections.Generic;
- class Program
- {
- IAsyncEnumerable Test()
- {
- yield return 1;
- [|await Task.Delay(1);|]
- }
- }
- """ + IAsyncEnumerable;
-
- var expected =
- """
- using System.Threading.Tasks;
- using System.Collections.Generic;
- class Program
- {
- async IAsyncEnumerable Test()
- {
- yield return 1;
- await Task.Delay(1);
- }
- }
- """ + IAsyncEnumerable;
- await TestInRegularAndScriptAsync(initial, expected);
- }
-
- [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33082")]
- public async Task BadAwaitInIAsyncEnumeratorMethod()
- {
- var initial =
- """
- using System.Threading.Tasks;
- using System.Collections.Generic;
- class Program
- {
- IAsyncEnumerator Test()
- {
- yield return 1;
- [|await Task.Delay(1);|]
- }
- }
- """ + IAsyncEnumerable;
-
- var expected =
- """
- using System.Threading.Tasks;
- using System.Collections.Generic;
- class Program
- {
- async IAsyncEnumerator Test()
- {
- yield return 1;
- await Task.Delay(1);
- }
- }
- """ + IAsyncEnumerable;
- await TestInRegularAndScriptAsync(initial, expected);
- }
-
- [Fact]
- public Task AwaitInMember()
- => TestMissingInRegularAndScriptAsync("""
- using System.Threading.Tasks;
-
- class Program
- {
- var x = [|await Task.Delay(3)|];
- }
- """);
-
- [Fact]
- public Task AddAsyncInDelegate()
- => TestInRegularAndScriptAsync(
- """
- using System;
- using System.Threading.Tasks;
-
- class Program
- {
- private async void method()
- {
- string content = await Task.Run(delegate () {
- [|await Task.Delay(1000)|];
- return "Test";
- });
- }
- }
- """,
- """
- using System;
- using System.Threading.Tasks;
-
- class Program
- {
- private async void method()
- {
- string content = await Task.Run(async delegate () {
- await Task.Delay(1000);
- return "Test";
- });
- }
- }
- """);
-
- [Fact]
- public Task AddAsyncInDelegate2()
- => TestInRegularAndScriptAsync(
- """
- using System;
- using System.Threading.Tasks;
-
- class Program
- {
- private void method()
- {
- string content = await Task.Run(delegate () {
- [|await Task.Delay(1000)|];
- return "Test";
- });
- }
- }
- """,
- """
- using System;
- using System.Threading.Tasks;
-
- class Program
- {
- private void method()
- {
- string content = await Task.Run(async delegate () {
- await Task.Delay(1000);
- return "Test";
- });
- }
- }
- """);
-
- [Fact]
- public Task AddAsyncInDelegate3()
- => TestInRegularAndScriptAsync(
- """
- using System;
- using System.Threading.Tasks;
-
- class Program
- {
- private void method()
- {
- string content = await Task.Run(delegate () {
- [|await Task.Delay(1000)|];
- return "Test";
- });
- }
- }
- """,
- """
- using System;
- using System.Threading.Tasks;
-
- class Program
- {
- private void method()
- {
- string content = await Task.Run(async delegate () {
- await Task.Delay(1000);
- return "Test";
- });
- }
- }
- """);
-
- [Fact, WorkItem(6477, @"https://github.com/dotnet/roslyn/issues/6477")]
- public Task NullNodeCrash()
- => TestMissingInRegularAndScriptAsync(
- """
- using System.Threading.Tasks;
-
- class C
- {
- static async void Main()
- {
- try
- {
- [|await|] await Task.Delay(100);
- }
- finally
- {
- }
- }
- }
- """);
-
- [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33082")]
- [WorkItem("https://github.com/dotnet/roslyn/issues/17470")]
- public Task AwaitInValueTaskMethod()
- => TestInRegularAndScriptAsync("""
- using System;
- using System.Threading.Tasks;
-
- namespace System.Threading.Tasks {
- struct ValueTask
- {
- }
- }
-
- class Program
- {
- ValueTask Test()
- {
- [|await Task.Delay(1);|]
- }
- }
- """, """
- using System;
- using System.Threading.Tasks;
-
- namespace System.Threading.Tasks {
- struct ValueTask
- {
- }
- }
-
- class Program
- {
- async ValueTask Test()
- {
- await Task.Delay(1);
- }
- }
- """);
-
- [Fact]
- public Task AwaitInValueTaskWithoutGenericMethod()
- => TestInRegularAndScriptAsync("""
- using System;
- using System.Threading.Tasks;
-
- namespace System.Threading.Tasks {
- struct ValueTask
- {
- }
- }
-
- class Program
- {
- ValueTask Test()
- {
- [|await Task.Delay(1);|]
- }
- }
- """, """
- using System;
- using System.Threading.Tasks;
-
- namespace System.Threading.Tasks {
- struct ValueTask
- {
- }
- }
-
- class Program
- {
- async ValueTask Test()
- {
- await Task.Delay(1);
- }
- }
- """);
-
- [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14133")]
- public Task AddAsyncInLocalFunction()
- => TestInRegularAndScriptAsync(
- """
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- void M2()
- {
- [|await M3Async();|]
- }
- }
-
- async Task M3Async()
- {
- return 1;
- }
- }
- """,
- """
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- async Task M2Async()
- {
- await M3Async();
- }
- }
-
- async Task M3Async()
- {
- return 1;
- }
- }
- """);
-
- [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14133")]
- [WorkItem("https://github.com/dotnet/roslyn/issues/33082")]
- public Task AddAsyncInLocalFunctionKeepVoidReturn()
- => TestInRegularAndScriptAsync(
- """
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- void M2()
- {
- [|await M3Async();|]
- }
- }
-
- async Task M3Async()
- {
- return 1;
- }
- }
- """,
- """
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- async void M2()
- {
- await M3Async();
- }
- }
-
- async Task M3Async()
- {
- return 1;
- }
- }
- """,
- index: 1);
-
- [Theory]
- [InlineData(0, "void", "Task", "M2Async")]
- [InlineData(1, "void", "void", "M2")]
- [InlineData(0, "int", "Task", "M2Async")]
- [InlineData(0, "Task", "Task", "M2")]
- [WorkItem("https://github.com/dotnet/roslyn/issues/18307")]
- [WorkItem("https://github.com/dotnet/roslyn/issues/33082")]
- public Task AddAsyncInLocalFunctionKeepsTrivia(int codeFixIndex, string initialReturn, string expectedReturn, string expectedName)
- => TestInRegularAndScriptAsync(
- $$"""
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- // Leading trivia
- /*1*/ {{initialReturn}} /*2*/ M2/*3*/() /*4*/
- {
- [|await M3Async();|]
- }
- }
-
- async Task M3Async()
- {
- return 1;
- }
- }
- """,
- $$"""
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- // Leading trivia
- /*1*/ async {{expectedReturn}} /*2*/ {{expectedName}}/*3*/() /*4*/
- {
- await M3Async();
- }
- }
-
- async Task M3Async()
- {
- return 1;
- }
- }
- """,
- index: codeFixIndex);
-
- [Theory]
- [InlineData("", 0, "Task", "M2Async")]
- [InlineData("", 1, "void", "M2")]
- [InlineData("public", 0, "Task", "M2Async")]
- [InlineData("public", 1, "void", "M2")]
- [WorkItem("https://github.com/dotnet/roslyn/issues/18307")]
- [WorkItem("https://github.com/dotnet/roslyn/issues/33082")]
- public Task AddAsyncKeepsTrivia(string modifiers, int codeFixIndex, string expectedReturn, string expectedName)
- => TestInRegularAndScriptAsync(
- $$"""
- using System.Threading.Tasks;
-
- class C
- {
- // Leading trivia
- {{modifiers}}/*1*/ void /*2*/ M2/*3*/() /*4*/
- {
- [|await M3Async();|]
- }
-
- async Task M3Async()
- {
- return 1;
- }
- }
- """,
- $$"""
- using System.Threading.Tasks;
-
- class C
- {
- // Leading trivia
- {{modifiers}}/*1*/ async {{expectedReturn}} /*2*/ {{expectedName}}/*3*/() /*4*/
- {
- await M3Async();
- }
-
- async Task M3Async()
- {
- return 1;
- }
- }
- """,
- index: codeFixIndex);
-
- [Fact]
- public Task MethodWithAwaitUsing()
- => TestInRegularAndScriptAsync(
- """
- class C
- {
- void M()
- {
- [|await using (var x = new object())|]
- {
- }
- }
- }
- """,
- """
- using System.Threading.Tasks;
-
- class C
- {
- async Task MAsync()
- {
- await using (var x = new object())
- {
- }
- }
- }
- """);
-
- [Fact]
- public Task MethodWithRegularUsing()
- => TestMissingInRegularAndScriptAsync(
- """
- class C
- {
- void M()
- {
- [|using (var x = new object())|]
- {
- }
- }
- }
- """);
-
- [Fact]
- public Task MethodWithAwaitForEach()
- => TestInRegularAndScriptAsync(
- """
- class C
- {
- void M()
- {
- [|await foreach (var n in new int[] { })|]
- {
- }
- }
- }
- """,
- """
- using System.Threading.Tasks;
-
- class C
- {
- async Task MAsync()
- {
- await foreach (var n in new int[] { })
- {
- }
- }
- }
- """);
-
- [Fact]
- public Task MethodWithRegularForEach()
- => TestMissingInRegularAndScriptAsync(
- """
- class C
- {
- void M()
- {
- [|foreach (var n in new int[] { })|]
- {
- }
- }
- }
- """);
-
- [Fact]
- public Task MethodWithAwaitForEachVariable()
- => TestInRegularAndScriptAsync(
- """
- class C
- {
- void M()
- {
- [|await foreach (var (a, b) in new(int, int)[] { })|]
- {
- }
- }
- }
- """,
- """
- using System.Threading.Tasks;
-
- class C
- {
- async Task MAsync()
- {
- await foreach (var (a, b) in new(int, int)[] { })
- {
- }
- }
- }
- """);
-
- [Fact]
- public Task MethodWithRegularForEachVariable()
- => TestMissingInRegularAndScriptAsync(
- """
- class C
- {
- void M()
- {
- [|foreach (var (a, b) in new(int, int)[] { })|]
- {
- }
- }
- }
- """);
-
- [Fact]
- public Task MethodWithNullableReturn()
- => TestInRegularAndScriptAsync(
- """
- #nullable enable
- using System.Threading.Tasks;
- class C
- {
- string? M()
- {
- [|await Task.Delay(1);|]
- return null;
- }
- }
- """,
- """
- #nullable enable
- using System.Threading.Tasks;
- class C
- {
- async Task MAsync()
- {
- await Task.Delay(1);
- return null;
- }
- }
- """);
-
- [Fact]
- public async Task EnumerableMethodWithNullableType()
- {
- var initial =
- """
- #nullable enable
- using System.Threading.Tasks;
- using System.Collections.Generic;
- class Program
- {
- IEnumerable Test()
- {
- yield return string.Empty;
- [|await Task.Delay(1);|]
- }
- }
- """ + IAsyncEnumerable;
-
- var expected =
- """
- #nullable enable
- using System.Threading.Tasks;
- using System.Collections.Generic;
- class Program
- {
- async IAsyncEnumerable TestAsync()
- {
- yield return string.Empty;
- await Task.Delay(1);
- }
- }
- """ + IAsyncEnumerable;
- await TestInRegularAndScriptAsync(initial, expected);
- }
-
- [Fact]
- public async Task EnumeratorMethodWithNullableType()
- {
- var initial =
- """
- #nullable enable
- using System.Threading.Tasks;
- using System.Collections.Generic;
- class Program
- {
- IEnumerator Test()
- {
- yield return string.Empty;
- [|await Task.Delay(1);|]
- }
- }
- """ + IAsyncEnumerable;
-
- var expected =
- """
- #nullable enable
- using System.Threading.Tasks;
- using System.Collections.Generic;
- class Program
- {
- async IAsyncEnumerator TestAsync()
- {
- yield return string.Empty;
- await Task.Delay(1);
- }
- }
- """ + IAsyncEnumerable;
- await TestInRegularAndScriptAsync(initial, expected);
- }
-
- [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25446")]
- public Task TestOnAwaitParsedAsType()
- => TestInRegularAndScriptAsync("""
- using System.Threading.Tasks;
-
- class C
- {
- void M()
- {
- Task task = null;
- [|await|] task;
- }
- }
- """, """
- using System.Threading.Tasks;
-
- class C
- {
- async Task MAsync()
- {
- Task task = null;
- await task;
- }
- }
- """);
-
- [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63404")]
- public Task PartialMethod1()
- => TestInRegularAndScriptAsync("""
- using System.Threading.Tasks;
-
- public partial class C
- {
- partial void M();
- }
-
- public partial class C
- {
- partial void M()
- {
- [|await|] Task.Delay(1);
- }
- }
- """, """
- using System.Threading.Tasks;
-
- public partial class C
- {
- partial Task MAsync();
- }
-
- public partial class C
- {
- async partial Task MAsync()
- {
- await Task.Delay(1);
- }
- }
- """);
-
- [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63404")]
- public Task PartialMethod2()
- => TestInRegularAndScriptAsync("""
- using System.Threading.Tasks;
-
- public partial class C
- {
- public partial void M();
- }
-
- public partial class C
- {
- public partial void M()
- {
- [|await|] Task.Delay(1);
- }
- }
- """, """
- using System.Threading.Tasks;
-
- public partial class C
- {
- public partial Task MAsync();
- }
-
- public partial class C
- {
- public async partial Task MAsync()
- {
- await Task.Delay(1);
- }
- }
- """);
-
- [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63404")]
- public Task PartialMethod3()
- => TestInRegularAndScriptAsync("""
- using System.Threading.Tasks;
-
- public partial class C
- {
- partial void M();
- }
-
- public partial class C
- {
- partial void M()
- {
- [|await|] Task.Delay(1);
- }
- }
- """, """
- using System.Threading.Tasks;
-
- public partial class C
- {
- partial void M();
- }
-
- public partial class C
- {
- async partial void M()
- {
- await Task.Delay(1);
- }
- }
- """, index: 1);
-
- [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63404")]
- public Task PartialMethod4()
- => TestInRegularAndScriptAsync("""
- using System.Threading.Tasks;
-
- public partial class C
- {
- public partial void M();
- }
-
- public partial class C
- {
- public partial void M()
- {
- [|await|] Task.Delay(1);
- }
- }
- """, """
- using System.Threading.Tasks;
-
- public partial class C
- {
- public partial void M();
- }
-
- public partial class C
- {
- public async partial void M()
- {
- await Task.Delay(1);
- }
- }
- """, index: 1);
-}
diff --git a/src/roslyn/src/Analyzers/CSharp/Tests/MakeMethodSynchronous/MakeMethodSynchronousTests.cs b/src/roslyn/src/Analyzers/CSharp/Tests/MakeMethodSynchronous/MakeMethodSynchronousTests.cs
deleted file mode 100644
index 2ab8c1bf6b9..00000000000
--- a/src/roslyn/src/Analyzers/CSharp/Tests/MakeMethodSynchronous/MakeMethodSynchronousTests.cs
+++ /dev/null
@@ -1,1045 +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.CSharp.MakeMethodSynchronous;
-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.MakeMethodSynchronous;
-
-using VerifyCS = CSharpCodeFixVerifier<
- EmptyDiagnosticAnalyzer,
- CSharpMakeMethodSynchronousCodeFixProvider>;
-
-[Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)]
-public sealed class MakeMethodSynchronousTests
-{
- [Fact]
- public Task TestTaskReturnType()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System.Threading.Tasks;
-
- class C
- {
- async Task {|CS1998:Goo|}()
- {
- }
- }
- """,
- """
- using System.Threading.Tasks;
-
- class C
- {
- void Goo()
- {
- }
- }
- """);
-
- [Fact]
- public Task TestTaskOfTReturnType()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System.Threading.Tasks;
-
- class C
- {
- async Task {|CS1998:Goo|}()
- {
- return 1;
- }
- }
- """,
- """
- using System.Threading.Tasks;
-
- class C
- {
- int {|#0:Goo|}()
- {
- return 1;
- }
- }
- """);
-
- [Fact]
- public Task TestSecondModifier()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System.Threading.Tasks;
-
- class C
- {
- public async Task {|CS1998:Goo|}()
- {
- }
- }
- """,
- """
- using System.Threading.Tasks;
-
- class C
- {
- public void Goo()
- {
- }
- }
- """);
-
- [Fact]
- public Task TestFirstModifier()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System.Threading.Tasks;
-
- class C
- {
- async public Task {|CS1998:Goo|}()
- {
- }
- }
- """,
- """
- using System.Threading.Tasks;
-
- class C
- {
- public void Goo()
- {
- }
- }
- """);
-
- [Fact]
- public Task TestTrailingTrivia()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System.Threading.Tasks;
-
- class C
- {
- async // comment
- Task {|CS1998:Goo|}()
- {
- }
- }
- """,
- """
- using System.Threading.Tasks;
-
- class C
- {
- void Goo()
- {
- }
- }
- """);
-
- [Fact]
- public Task TestRenameMethod()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System.Threading.Tasks;
-
- class C
- {
- async Task {|CS1998:GooAsync|}()
- {
- }
- }
- """,
- """
- using System.Threading.Tasks;
-
- class C
- {
- void Goo()
- {
- }
- }
- """);
-
- [Fact]
- public Task TestRenameMethod1()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System.Threading.Tasks;
-
- class C
- {
- async Task {|CS1998:GooAsync|}()
- {
- }
-
- void Bar()
- {
- GooAsync();
- }
- }
- """,
- """
- using System.Threading.Tasks;
-
- class C
- {
- void Goo()
- {
- }
-
- void Bar()
- {
- Goo();
- }
- }
- """);
-
- [Fact]
- public async Task TestParenthesizedLambda()
- {
- var expected =
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- void Goo()
- {
- Func f =
- () {|#0:=>|} { };
- }
- }
- """;
-
- await new VerifyCS.Test
- {
- TestCode = """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- void Goo()
- {
- Func f =
- async () {|CS1998:=>|} { };
- }
- }
- """,
- FixedState =
- {
- Sources = { expected },
- ExpectedDiagnostics =
- {
- // /0/Test0.cs(10,16): error CS1643: Not all code paths return a value in lambda expression of type 'Func'
- DiagnosticResult.CompilerError("CS1643").WithLocation(0),
- },
- },
- }.RunAsync();
- }
-
- [Fact]
- public async Task TestSimpleLambda()
- {
- var expected =
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- void Goo()
- {
- Func f =
- a {|#0:=>|} { };
- }
- }
- """;
-
- await new VerifyCS.Test
- {
- TestCode = """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- void Goo()
- {
- Func f =
- async a {|CS1998:=>|} { };
- }
- }
- """,
- FixedState =
- {
- Sources = { expected },
- ExpectedDiagnostics =
- {
- // /0/Test0.cs(10,15): error CS1643: Not all code paths return a value in lambda expression of type 'Func'
- DiagnosticResult.CompilerError("CS1643").WithLocation(0),
- },
- },
- }.RunAsync();
- }
-
- [Fact]
- public async Task TestLambdaWithExpressionBody()
- {
- var expected =
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- void Goo()
- {
- Func> f =
- a => {|#0:1|};
- }
- }
- """;
-
- await new VerifyCS.Test
- {
- TestCode = """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- void Goo()
- {
- Func> f =
- async a {|CS1998:=>|} 1;
- }
- }
- """,
- FixedState =
- {
- Sources = { expected },
- ExpectedDiagnostics =
- {
- // /0/Test0.cs(10,18): error CS0029: Cannot implicitly convert type 'int' to 'System.Threading.Tasks.Task'
- DiagnosticResult.CompilerError("CS0029").WithLocation(0).WithArguments("int", "System.Threading.Tasks.Task"),
- // /0/Test0.cs(10,18): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
- DiagnosticResult.CompilerError("CS1662").WithLocation(0),
- },
- },
- }.RunAsync();
- }
-
- [Fact]
- public async Task TestAnonymousMethod()
- {
- var expected =
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- void Goo()
- {
- Func f =
- {|#0:delegate|} { };
- }
- }
- """;
-
- await new VerifyCS.Test
- {
- TestCode = """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- void Goo()
- {
- Func f =
- async {|CS1998:delegate|} { };
- }
- }
- """,
- FixedState =
- {
- Sources = { expected },
- ExpectedDiagnostics =
- {
- // /0/Test0.cs(10,13): error CS1643: Not all code paths return a value in anonymous method of type 'Func'
- DiagnosticResult.CompilerError("CS1643").WithLocation(0),
- },
- },
- }.RunAsync();
- }
-
- [Fact]
- public Task TestFixAll()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System.Threading.Tasks;
-
- public class Class1
- {
- async Task {|CS1998:GooAsync|}()
- {
- BarAsync();
- }
-
- async Task {|#0:{|CS1998:BarAsync|}|}()
- {
- GooAsync();
- return 1;
- }
- }
- """,
- """
- using System.Threading.Tasks;
-
- public class Class1
- {
- void Goo()
- {
- Bar();
- }
-
- int {|#0:Bar|}()
- {
- Goo();
- return 1;
- }
- }
- """);
-
- [Fact]
- [WorkItem("https://github.com/dotnet/roslyn/issues/13961")]
- public async Task TestRemoveAwaitFromCaller1()
- {
- var expected =
- """
- using System.Threading.Tasks;
-
- public class Class1
- {
- void Goo()
- {
- }
-
- async void {|CS1998:BarAsync|}()
- {
- Goo();
- }
- }
- """;
-
- await new VerifyCS.Test
- {
- TestCode = """
- using System.Threading.Tasks;
-
- public class Class1
- {
- async Task {|CS1998:GooAsync|}()
- {
- }
-
- async void BarAsync()
- {
- await GooAsync();
- }
- }
- """,
- FixedState =
- {
- Sources = { expected },
- MarkupHandling = MarkupMode.Allow,
- },
- CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne,
- }.RunAsync();
- }
-
- [Fact]
- [WorkItem("https://github.com/dotnet/roslyn/issues/13961")]
- public async Task TestRemoveAwaitFromCaller2()
- {
- var expected =
- """
- using System.Threading.Tasks;
-
- public class Class1
- {
- void Goo()
- {
- }
-
- async void {|CS1998:BarAsync|}()
- {
- Goo();
- }
- }
- """;
-
- await new VerifyCS.Test
- {
- TestCode = """
- using System.Threading.Tasks;
-
- public class Class1
- {
- async Task {|CS1998:GooAsync|}()
- {
- }
-
- async void BarAsync()
- {
- await GooAsync().ConfigureAwait(false);
- }
- }
- """,
- FixedState =
- {
- Sources = { expected },
- MarkupHandling = MarkupMode.Allow,
- },
- CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne,
- }.RunAsync();
- }
-
- [Fact]
- [WorkItem("https://github.com/dotnet/roslyn/issues/13961")]
- public async Task TestRemoveAwaitFromCaller3()
- {
- var expected =
- """
- using System.Threading.Tasks;
-
- public class Class1
- {
- void Goo()
- {
- }
-
- async void {|CS1998:BarAsync|}()
- {
- this.Goo();
- }
- }
- """;
-
- await new VerifyCS.Test
- {
- TestCode = """
- using System.Threading.Tasks;
-
- public class Class1
- {
- async Task {|CS1998:GooAsync|}()
- {
- }
-
- async void BarAsync()
- {
- await this.GooAsync();
- }
- }
- """,
- FixedState =
- {
- Sources = { expected },
- MarkupHandling = MarkupMode.Allow,
- },
- CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne,
- }.RunAsync();
- }
-
- [Fact]
- [WorkItem("https://github.com/dotnet/roslyn/issues/13961")]
- public async Task TestRemoveAwaitFromCaller4()
- {
- var expected =
- """
- using System.Threading.Tasks;
-
- public class Class1
- {
- void Goo()
- {
- }
-
- async void {|CS1998:BarAsync|}()
- {
- this.Goo();
- }
- }
- """;
-
- await new VerifyCS.Test
- {
- TestCode = """
- using System.Threading.Tasks;
-
- public class Class1
- {
- async Task {|CS1998:GooAsync|}()
- {
- }
-
- async void BarAsync()
- {
- await this.GooAsync().ConfigureAwait(false);
- }
- }
- """,
- FixedState =
- {
- Sources = { expected },
- MarkupHandling = MarkupMode.Allow,
- },
- CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne,
- }.RunAsync();
- }
-
- [Fact]
- [WorkItem("https://github.com/dotnet/roslyn/issues/13961")]
- public async Task TestRemoveAwaitFromCallerNested1()
- {
- var expected =
- """
- using System.Threading.Tasks;
-
- public class Class1
- {
- int Goo(int i)
- {
- return 1;
- }
-
- async void {|CS1998:BarAsync|}()
- {
- this.Goo(this.Goo(0));
- }
- }
- """;
-
- await new VerifyCS.Test
- {
- TestCode = """
- using System.Threading.Tasks;
-
- public class Class1
- {
- async Task {|CS1998:GooAsync|}(int i)
- {
- return 1;
- }
-
- async void BarAsync()
- {
- await this.GooAsync(await this.GooAsync(0));
- }
- }
- """,
- FixedState =
- {
- Sources = { expected },
- MarkupHandling = MarkupMode.Allow,
- },
- CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne,
- }.RunAsync();
- }
-
- [Fact]
- [WorkItem("https://github.com/dotnet/roslyn/issues/13961")]
- public async Task TestRemoveAwaitFromCallerNested()
- {
- var expected =
- """
- using System.Threading.Tasks;
-
- public class Class1
- {
- int Goo(int i)
- {
- return 1;
- }
-
- async void {|CS1998:BarAsync|}()
- {
- this.Goo(this.Goo(0));
- }
- }
- """;
-
- await new VerifyCS.Test
- {
- TestCode = """
- using System.Threading.Tasks;
-
- public class Class1
- {
- async Task {|CS1998:GooAsync|}(int i)
- {
- return 1;
- }
-
- async void BarAsync()
- {
- await this.GooAsync(await this.GooAsync(0).ConfigureAwait(false)).ConfigureAwait(false);
- }
- }
- """,
- FixedState =
- {
- Sources = { expected },
- MarkupHandling = MarkupMode.Allow,
- },
- CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne,
- }.RunAsync();
- }
-
- [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)]
- [WorkItem("https://github.com/dotnet/roslyn/issues/14133")]
- public Task RemoveAsyncInLocalFunction()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- async Task {|CS1998:M2Async|}()
- {
- }
- }
- }
- """,
- """
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- void M2()
- {
- }
- }
- }
- """);
-
- [Theory]
- [InlineData("Task", "C")]
- [InlineData("Task", "int")]
- [InlineData("Task", "void")]
- [InlineData("void", "void")]
- [Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)]
- [WorkItem("https://github.com/dotnet/roslyn/issues/18307")]
- public Task RemoveAsyncInLocalFunctionKeepsTrivia(string asyncReturn, string expectedReturn)
- => VerifyCS.VerifyCodeFixAsync(
- $$"""
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- // Leading trivia
- /*1*/ async {{asyncReturn}} /*2*/ {|CS1998:M2Async|}/*3*/() /*4*/
- {
- throw new NotImplementedException();
- }
- }
- }
- """,
- $$"""
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- // Leading trivia
- /*1*/
- {{expectedReturn}} /*2*/ M2/*3*/() /*4*/
- {
- throw new NotImplementedException();
- }
- }
- }
- """);
-
- [Theory]
- [InlineData("", "Task", "\r\n C")]
- [InlineData("", "Task", "\r\n int")]
- [InlineData("", "Task", "\r\n void")]
- [InlineData("", "void", "\r\n void")]
- [InlineData("public", "Task", " C")]
- [InlineData("public", "Task", " int")]
- [InlineData("public", "Task", " void")]
- [InlineData("public", "void", " void")]
- [Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)]
- [WorkItem("https://github.com/dotnet/roslyn/issues/18307")]
- public Task RemoveAsyncKeepsTrivia(string modifiers, string asyncReturn, string expectedReturn)
- => VerifyCS.VerifyCodeFixAsync(
- $$"""
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- // Leading trivia
- {{modifiers}}/*1*/ async {{asyncReturn}} /*2*/ {|CS1998:M2Async|}/*3*/() /*4*/
- {
- throw new NotImplementedException();
- }
- }
- """,
- $$"""
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- // Leading trivia
- {{modifiers}}/*1*/{{expectedReturn}} /*2*/ M2/*3*/() /*4*/
- {
- throw new NotImplementedException();
- }
- }
- """);
-
- [Fact]
- public async Task MethodWithUsingAwait()
- {
- var source =
- """
- class C
- {
- async System.Threading.Tasks.Task MAsync()
- {
- await using ({|#0:var x = new object()|})
- {
- }
- }
- }
- """;
-
- await new VerifyCS.Test
- {
- ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
- TestCode = source,
- ExpectedDiagnostics =
- {
- // /0/Test0.cs(5,22): error CS8410: 'object': type used in an asynchronous using statement must implement 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
- DiagnosticResult.CompilerError("CS8410").WithLocation(0).WithArguments("object"),
- },
- FixedCode = source,
- }.RunAsync();
- }
-
- [Fact]
- public Task MethodWithUsingNoAwait()
- => VerifyCS.VerifyCodeFixAsync(
- """
- class C
- {
- async System.Threading.Tasks.Task {|CS1998:MAsync|}()
- {
- using ({|#0:var x = new object()|})
- {
- }
- }
- }
- """,
- // /0/Test0.cs(5,16): error CS1674: 'object': type used in a using statement must implement 'System.IDisposable'.
- DiagnosticResult.CompilerError("CS1674").WithLocation(0).WithArguments("object"),
- """
- class C
- {
- void M()
- {
- using ({|#0:var x = new object()|})
- {
- }
- }
- }
- """);
-
- [Fact]
- public async Task MethodWithAwaitForEach()
- {
- var source =
- """
- class C
- {
- async System.Threading.Tasks.Task MAsync()
- {
- await foreach (var n in {|#0:new int[] { }|})
- {
- }
- }
- }
- """;
-
- await VerifyCS.VerifyCodeFixAsync(
- source,
- // /0/Test0.cs(5,33): error CS1061: 'bool' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'bool' could be found (are you missing a using directive or an assembly reference?)
- DiagnosticResult.CompilerError("CS1061").WithLocation(0).WithArguments("bool", "GetAwaiter"),
- source);
- }
-
- [Fact]
- public Task MethodWithForEachNoAwait()
- => VerifyCS.VerifyCodeFixAsync(
- """
- class C
- {
- async System.Threading.Tasks.Task {|CS1998:MAsync|}()
- {
- foreach (var n in new int[] { })
- {
- }
- }
- }
- """,
- """
- class C
- {
- void M()
- {
- foreach (var n in new int[] { })
- {
- }
- }
- }
- """);
-
- [Fact]
- public async Task MethodWithForEachVariableAwait()
- {
- var source =
- """
- class C
- {
- async System.Threading.Tasks.Task MAsync()
- {
- await foreach (var (a, b) in {|#0:new(int, int)[] { }|})
- {
- }
- }
- }
- """;
-
- await VerifyCS.VerifyCodeFixAsync(
- source,
- // /0/Test0.cs(5,38): error CS1061: 'bool' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'bool' could be found (are you missing a using directive or an assembly reference?)
- DiagnosticResult.CompilerError("CS1061").WithLocation(0).WithArguments("bool", "GetAwaiter"),
- source);
- }
-
- [Fact]
- public Task MethodWithForEachVariableNoAwait()
- => VerifyCS.VerifyCodeFixAsync(
- """
- class C
- {
- async System.Threading.Tasks.Task {|CS1998:MAsync|}()
- {
- foreach (var (a, b) in new(int, int)[] { })
- {
- }
- }
- }
- """,
- """
- class C
- {
- void M()
- {
- foreach (var (a, b) in new (int, int)[] { })
- {
- }
- }
- }
- """);
-
- [Fact]
- public Task TestIAsyncEnumerableReturnType()
- => new VerifyCS.Test
- {
- ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
- TestCode = """
- using System.Threading.Tasks;
- using System.Collections.Generic;
-
- class C
- {
- async IAsyncEnumerable {|CS1998:MAsync|}()
- {
- yield return 1;
- }
- }
- """,
- FixedCode = """
- using System.Threading.Tasks;
- using System.Collections.Generic;
-
- class C
- {
- IEnumerable M()
- {
- yield return 1;
- }
- }
- """,
- }.RunAsync();
-
- [Fact]
- public Task TestIAsyncEnumeratorReturnTypeOnLocalFunction()
- => new VerifyCS.Test
- {
- ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
- TestCode = """
- using System.Threading.Tasks;
- using System.Collections.Generic;
-
- class C
- {
- void Method()
- {
- async IAsyncEnumerator {|CS1998:MAsync|}()
- {
- yield return 1;
- }
- }
- }
- """,
- FixedCode = """
- using System.Threading.Tasks;
- using System.Collections.Generic;
-
- class C
- {
- void Method()
- {
- IEnumerator M()
- {
- yield return 1;
- }
- }
- }
- """,
- }.RunAsync();
-}
diff --git a/src/roslyn/src/Analyzers/CSharp/Tests/Nullable/CSharpDeclareAsNullableCodeFixTests.cs b/src/roslyn/src/Analyzers/CSharp/Tests/Nullable/CSharpDeclareAsNullableCodeFixTests.cs
index a93373e0cdc..f65576cce4a 100644
--- a/src/roslyn/src/Analyzers/CSharp/Tests/Nullable/CSharpDeclareAsNullableCodeFixTests.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Tests/Nullable/CSharpDeclareAsNullableCodeFixTests.cs
@@ -21,7 +21,7 @@ public sealed class CSharpDeclareAsNullableCodeFixTests(ITestOutputHelper logger
internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (null, new CSharpDeclareAsNullableCodeFixProvider());
- private static readonly TestParameters s_nullableFeature = new TestParameters(parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
+ private static readonly TestParameters s_nullableFeature = new(parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
[Fact]
public Task FixAll()
diff --git a/src/roslyn/src/Analyzers/CSharp/Tests/RemoveAsyncModifier/RemoveAsyncModifierTests.cs b/src/roslyn/src/Analyzers/CSharp/Tests/RemoveAsyncModifier/RemoveAsyncModifierTests.cs
deleted file mode 100644
index 59c4359e893..00000000000
--- a/src/roslyn/src/Analyzers/CSharp/Tests/RemoveAsyncModifier/RemoveAsyncModifierTests.cs
+++ /dev/null
@@ -1,1224 +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.CSharp.RemoveAsyncModifier;
-using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
-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.RemoveAsyncModifier;
-
-using VerifyCS = CSharpCodeFixVerifier<
- EmptyDiagnosticAnalyzer,
- CSharpRemoveAsyncModifierCodeFixProvider>;
-
-[Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
-public sealed class RemoveAsyncModifierTests
-{
- [Fact]
- public Task Method_Task_MultipleAndNested()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- async Task {|CS1998:Goo|}()
- {
- if (DateTime.Now.Ticks > 0)
- {
- return;
- }
- }
-
- async Task {|CS1998:Foo|}()
- {
- Console.WriteLine(1);
- }
-
- async Task {|CS1998:Bar|}()
- {
- async Task {|CS1998:Baz|}()
- {
- Func> g = async () {|CS1998:=>|} 5;
- }
- }
-
- async Task {|CS1998:Tur|}()
- {
- async Task {|CS1998:Duck|}()
- {
- async Task {|CS1998:En|}()
- {
- return "Developers!";
- }
-
- return "Developers! Developers!";
- }
-
- return "Developers! Developers! Developers!";
- }
-
- async Task {|CS1998:Nurk|}()
- {
- Func> f = async () {|CS1998:=>|} 4;
-
- if (DateTime.Now.Ticks > f().Result)
- {
- }
- }
- }
- """,
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- Task Goo()
- {
- if (DateTime.Now.Ticks > 0)
- {
- return Task.CompletedTask;
- }
-
- return Task.CompletedTask;
- }
-
- Task Foo()
- {
- Console.WriteLine(1);
- return Task.CompletedTask;
- }
-
- Task Bar()
- {
- Task Baz()
- {
- Func> g = () => Task.FromResult(5);
- return Task.CompletedTask;
- }
-
- return Task.CompletedTask;
- }
-
- Task Tur()
- {
- Task Duck()
- {
- Task En()
- {
- return Task.FromResult("Developers!");
- }
-
- return Task.FromResult("Developers! Developers!");
- }
-
- return Task.FromResult("Developers! Developers! Developers!");
- }
-
- Task Nurk()
- {
- Func> f = () => Task.FromResult(4);
-
- if (DateTime.Now.Ticks > f().Result)
- {
- }
-
- return Task.CompletedTask;
- }
- }
- """);
-
- [Fact]
- public Task Method_Task_EmptyBlockBody()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System.Threading.Tasks;
-
- class C
- {
- async Task {|CS1998:Goo|}(){}
- }
- """,
- """
- using System.Threading.Tasks;
-
- class C
- {
- Task Goo()
- {
- return Task.CompletedTask;
- }
- }
- """);
-
- [Fact]
- public Task Method_Task_BlockBody()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System.Threading.Tasks;
-
- class C
- {
- async Task {|CS1998:Goo|}()
- {
- if (System.DateTime.Now.Ticks > 0)
- {
- return;
- }
- }
- }
- """,
- """
- using System.Threading.Tasks;
-
- class C
- {
- Task Goo()
- {
- if (System.DateTime.Now.Ticks > 0)
- {
- return Task.CompletedTask;
- }
-
- return Task.CompletedTask;
- }
- }
- """);
-
- [Fact]
- public Task Method_ValueTask_BlockBody()
- => new VerifyCS.Test
- {
- ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
- TestCode = """
- using System.Threading.Tasks;
-
- class C
- {
- async ValueTask {|CS1998:Goo|}()
- {
- if (System.DateTime.Now.Ticks > 0)
- {
- return;
- }
- }
- }
- """,
- FixedCode = """
- using System.Threading.Tasks;
-
- class C
- {
- ValueTask Goo()
- {
- if (System.DateTime.Now.Ticks > 0)
- {
- return new ValueTask();
- }
-
- return new ValueTask();
- }
- }
- """,
- }.RunAsync();
-
- [Fact]
- public Task Method_ValueTaskOfT_BlockBody()
- => new VerifyCS.Test
- {
- ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
- TestCode = """
- using System.Threading.Tasks;
-
- class C
- {
- async ValueTask {|CS1998:Goo|}()
- {
- if (System.DateTime.Now.Ticks > 0)
- {
- return 2;
- }
-
- return 3;
- }
- }
- """,
- FixedCode = """
- using System.Threading.Tasks;
-
- class C
- {
- ValueTask Goo()
- {
- if (System.DateTime.Now.Ticks > 0)
- {
- return new ValueTask(2);
- }
-
- return new ValueTask(3);
- }
- }
- """,
- }.RunAsync();
-
- [Fact]
- 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);
- }
- """,
- FixedCode = """
- using System.Threading.Tasks;
-
- class C
- {
- ValueTask Goo()
- {
- System.Console.WriteLine(1);
- return new ValueTask();
- }
- }
- """,
- }.RunAsync();
-
- [Fact]
- public Task Method_ValueTaskOfT_ExpressionBody()
- => new VerifyCS.Test
- {
- ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
- TestCode = """
- using System.Threading.Tasks;
-
- class C
- {
- async ValueTask {|CS1998:Goo|}() => 3;
- }
- """,
- FixedCode = """
- using System.Threading.Tasks;
-
- class C
- {
- ValueTask Goo() => new ValueTask(3);
- }
- """,
- }.RunAsync();
-
- [Fact]
- public Task Method_Task_BlockBody_Throws()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System.Threading.Tasks;
-
- class C
- {
- async Task {|CS1998:Goo|}()
- {
- if (System.DateTime.Now.Ticks > 0)
- {
- return;
- }
-
- throw new System.ApplicationException();
- }
- }
- """,
- """
- using System.Threading.Tasks;
-
- class C
- {
- Task Goo()
- {
- if (System.DateTime.Now.Ticks > 0)
- {
- return Task.CompletedTask;
- }
-
- throw new System.ApplicationException();
- }
- }
- """);
-
- [Fact]
- public Task Method_Task_BlockBody_WithLocalFunction()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System.Threading.Tasks;
-
- class C
- {
- async Task {|CS1998:Goo|}()
- {
- if (GetTicks() > 0)
- {
- return;
- }
-
- long GetTicks()
- {
- return System.DateTime.Now.Ticks;
- }
- }
- }
- """,
- """
- using System.Threading.Tasks;
-
- class C
- {
- Task Goo()
- {
- if (GetTicks() > 0)
- {
- return Task.CompletedTask;
- }
-
- long GetTicks()
- {
- return System.DateTime.Now.Ticks;
- }
-
- return Task.CompletedTask;
- }
- }
- """);
-
- [Fact]
- public Task Method_Task_BlockBody_WithLambda()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System.Threading.Tasks;
-
- class C
- {
- async Task {|CS1998:Goo|}()
- {
- System.Func getTicks = () => {
- return System.DateTime.Now.Ticks;
- };
-
- if (getTicks() > 0)
- {
- return;
- }
-
- }
- }
- """,
- """
- using System.Threading.Tasks;
-
- class C
- {
- Task Goo()
- {
- System.Func getTicks = () => {
- return System.DateTime.Now.Ticks;
- };
-
- if (getTicks() > 0)
- {
- return Task.CompletedTask;
- }
-
- return Task.CompletedTask;
- }
- }
- """);
-
- [Fact]
- public Task Method_TaskOfT_BlockBody()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System.Threading.Tasks;
-
- class C
- {
- async Task {|CS1998:Goo|}()
- {
- if (System.DateTime.Now.Ticks > 0)
- {
- return 2;
- }
-
- return 3;
- }
- }
- """,
- """
- using System.Threading.Tasks;
-
- class C
- {
- Task Goo()
- {
- if (System.DateTime.Now.Ticks > 0)
- {
- return Task.FromResult(2);
- }
-
- return Task.FromResult(3);
- }
- }
- """);
-
- [Fact]
- public Task Method_TaskOfT_ExpressionBody()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System.Threading.Tasks;
-
- class C
- {
- async Task {|CS1998:Goo|}() => 2;
- }
- """,
- """
- using System.Threading.Tasks;
-
- class C
- {
- Task Goo() => Task.FromResult(2);
- }
- """);
-
- [Fact]
- public Task Method_Task_ExpressionBody()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- async Task {|CS1998:Goo|}() => Console.WriteLine("Hello");
- }
- """,
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- Task Goo()
- {
- Console.WriteLine("Hello");
- return Task.CompletedTask;
- }
- }
- """);
-
- [Fact]
- public Task LocalFunction_Task_BlockBody()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- async Task {|CS1998:Goo|}()
- {
- if (System.DateTime.Now.Ticks > 0)
- {
- return;
- }
- }
- }
- }
- """,
- """
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- Task Goo()
- {
- if (System.DateTime.Now.Ticks > 0)
- {
- return Task.CompletedTask;
- }
-
- return Task.CompletedTask;
- }
- }
- }
- """);
-
- [Fact]
- public Task LocalFunction_Task_ExpressionBody()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- async Task {|CS1998:Goo|}() => Console.WriteLine(1);
- }
- }
- """,
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- Task Goo() { Console.WriteLine(1); return Task.CompletedTask; }
- }
- }
- """);
-
- [Fact]
- public Task LocalFunction_TaskOfT_BlockBody()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- async Task {|CS1998:Goo|}()
- {
- return 1;
- }
- }
- }
- """,
- """
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- Task Goo()
- {
- return Task.FromResult(1);
- }
- }
- }
- """);
-
- [Fact]
- public Task LocalFunction_TaskOfT_ExpressionBody()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- async Task {|CS1998:Goo|}() => 1;
- }
- }
- """,
- """
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- Task Goo() => Task.FromResult(1);
- }
- }
- """);
-
- [Fact]
- public Task AnonymousFunction_Task_BlockBody()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- Func foo = (Func)async {|CS1998:delegate|} {
- if (System.DateTime.Now.Ticks > 0)
- {
- return;
- }
- };
- }
- }
- """,
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- Func foo = (Func)delegate
- {
- if (System.DateTime.Now.Ticks > 0)
- {
- return Task.CompletedTask;
- }
-
- return Task.CompletedTask;
- };
- }
- }
- """);
-
- [Fact]
- public Task AnonymousFunction_TaskOfT_BlockBody()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- Func> foo = (Func>)async {|CS1998:delegate|}
- {
- return 1;
- };
- }
- }
- """,
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- Func> foo = (Func>)delegate
- {
- return Task.FromResult(1);
- };
- }
- }
- """);
-
- [Fact]
- public Task SimpleLambda_TaskOfT_ExpressionBody()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- Func> foo = async x {|CS1998:=>|} 1;
- }
- }
- """,
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- Func> foo = x => Task.FromResult(1);
- }
- }
- """);
-
- [Fact]
- public Task SimpleLambda_TaskOfT_BlockBody()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- Func> foo = async x {|CS1998:=>|} {
- return 1;
- };
- }
- }
- """,
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- Func> foo = x =>
- {
- return Task.FromResult(1);
- };
- }
- }
- """);
-
- [Fact]
- public Task SimpleLambda_Task_ExpressionBody()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- Func foo = async x {|CS1998:=>|} Console.WriteLine(1);
- }
- }
- """,
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- Func foo = x => { Console.WriteLine(1); return Task.CompletedTask; };
- }
- }
- """);
-
- [Fact]
- public Task SimpleLambda_Task_BlockBody()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- Func foo = async x {|CS1998:=>|}
- {
- if (System.DateTime.Now.Ticks > 0)
- {
- return;
- }
- };
- }
- }
- """,
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- Func foo = x =>
- {
- if (System.DateTime.Now.Ticks > 0)
- {
- return Task.CompletedTask;
- }
-
- return Task.CompletedTask;
- };
- }
- }
- """);
-
- [Fact]
- public Task ParenthesizedLambda_TaskOfT_ExpressionBody()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- Func> foo = async () {|CS1998:=>|} 1;
- }
- }
- """,
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- Func> foo = () => Task.FromResult(1);
- }
- }
- """);
-
- [Fact]
- public Task ParenthesizedLambda_TaskOfT_BlockBody()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- Func> foo = async () {|CS1998:=>|} {
- return 1;
- };
- }
- }
- """,
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- Func> foo = () =>
- {
- return Task.FromResult(1);
- };
- }
- }
- """);
-
- [Fact]
- public Task ParenthesizedLambda_Task_ExpressionBody()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- Func foo = async () {|CS1998:=>|} Console.WriteLine(1);
- }
- }
- """,
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- Func foo = () => { Console.WriteLine(1); return Task.CompletedTask; };
- }
- }
- """);
-
- [Fact]
- public Task ParenthesizedLambda_Task_BlockBody()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- Func foo = async () {|CS1998:=>|}
- {
- if (System.DateTime.Now.Ticks > 0)
- {
- return;
- }
- };
- }
- }
- """,
- """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- public void M1()
- {
- Func foo = () =>
- {
- if (System.DateTime.Now.Ticks > 0)
- {
- return Task.CompletedTask;
- }
-
- return Task.CompletedTask;
- };
- }
- }
- """);
-
- [Fact]
- public Task Method_Task_BlockBody_FullyQualified()
- => VerifyCS.VerifyCodeFixAsync(
- """
- class C
- {
- async System.Threading.Tasks.Task {|CS1998:Goo|}()
- {
- if (System.DateTime.Now.Ticks > 0)
- {
- return;
- }
- }
- }
- """,
- """
- class C
- {
- System.Threading.Tasks.Task Goo()
- {
- if (System.DateTime.Now.Ticks > 0)
- {
- return System.Threading.Tasks.Task.CompletedTask;
- }
-
- return System.Threading.Tasks.Task.CompletedTask;
- }
- }
- """);
-
- [Fact]
- public Task Method_TaskOfT_BlockBody_FullyQualified()
- => VerifyCS.VerifyCodeFixAsync(
- """
- class C
- {
- async System.Threading.Tasks.Task {|CS1998:Goo|}()
- {
- if (System.DateTime.Now.Ticks > 0)
- {
- return 1;
- }
-
- return 2;
- }
- }
- """,
- """
- class C
- {
- System.Threading.Tasks.Task Goo()
- {
- if (System.DateTime.Now.Ticks > 0)
- {
- return System.Threading.Tasks.Task.FromResult(1);
- }
-
- return System.Threading.Tasks.Task.FromResult(2);
- }
- }
- """);
-
- [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65536")]
- public Task Method_TaskOfT_BlockBody_QualifyTaskFromResultType()
- => VerifyCS.VerifyCodeFixAsync("""
- using System.Threading.Tasks;
- using System.Collections.Generic;
-
- class C
- {
- public async Task> {|CS1998:M|}()
- {
- return new int[0];
- }
- }
- """, """
- using System.Threading.Tasks;
- using System.Collections.Generic;
-
- class C
- {
- public Task> M()
- {
- return Task.FromResult>(new int[0]);
- }
- }
- """);
-
- [Fact]
- public async Task IAsyncEnumerable_Missing()
- {
- var source = """
- using System.Threading.Tasks;
- using System.Collections.Generic;
-
- class C
- {
- async IAsyncEnumerable M()
- {
- yield return 1;
- }
- }
- """ + CSharpTestBase.AsyncStreamsTypes;
-
- await new VerifyCS.Test
- {
- ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
- TestCode = source,
- ExpectedDiagnostics =
- {
- // /0/Test0.cs(7,33): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
- DiagnosticResult.CompilerWarning("CS1998").WithSpan(6, 33, 6, 34),
- },
- FixedCode = source,
- }.RunAsync();
- }
-
- [Fact]
- public async Task Method_AsyncVoid_Missing()
- {
- var source = """
- using System.Threading.Tasks;
-
- class C
- {
- async void M()
- {
- System.Console.WriteLine(1);
- }
- }
- """;
-
- await new VerifyCS.Test
- {
- ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
- TestCode = source,
- ExpectedDiagnostics =
- {
- // /0/Test0.cs(6,16): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
- DiagnosticResult.CompilerWarning("CS1998").WithSpan(5, 16, 5, 17),
- },
- FixedCode = source,
- }.RunAsync();
- }
-
- [Fact]
- public async Task ParenthesizedLambda_AsyncVoid_Missing()
- {
- var source = """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- void M()
- {
- Action a = async () => Console.WriteLine(1);
- }
- }
- """;
-
- await new VerifyCS.Test
- {
- ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
- TestCode = source,
- ExpectedDiagnostics =
- {
- // /0/Test0.cs(9,29): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
- DiagnosticResult.CompilerWarning("CS1998").WithSpan(8, 29, 8, 31),
- },
- FixedCode = source,
- }.RunAsync();
- }
-
- [Fact]
- public async Task SimpleLambda_AsyncVoid_Missing()
- {
- var source = """
- using System;
- using System.Threading.Tasks;
-
- class C
- {
- void M()
- {
- Action a = async x => Console.WriteLine(x);
- }
- }
- """;
-
- await new VerifyCS.Test
- {
- ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
- TestCode = source,
- ExpectedDiagnostics =
- {
- // /0/Test0.cs(9,33): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
- DiagnosticResult.CompilerWarning("CS1998").WithSpan(8, 33, 8, 35),
- },
- FixedCode = source,
- }.RunAsync();
- }
- [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65380")]
- public Task TestCloseBraceTrivia()
- => VerifyCS.VerifyCodeFixAsync(
- """
- using System;
- using System.Threading.Tasks;
-
- public class Class1
- {
- public async Task {|CS1998:Goo|}()
- {
- //Hello
- Console.WriteLine("Goo");
- //World
- }
- }
- """,
- """
- using System;
- using System.Threading.Tasks;
-
- public class Class1
- {
- public Task Goo()
- {
- //Hello
- Console.WriteLine("Goo");
- return Task.CompletedTask;
- //World
- }
- }
- """);
-}
diff --git a/src/roslyn/src/Analyzers/CSharp/Tests/SimplifyInterpolation/SimplifyInterpolationTests.cs b/src/roslyn/src/Analyzers/CSharp/Tests/SimplifyInterpolation/SimplifyInterpolationTests.cs
index e0e67a008e3..3cbecc86a5d 100644
--- a/src/roslyn/src/Analyzers/CSharp/Tests/SimplifyInterpolation/SimplifyInterpolationTests.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Tests/SimplifyInterpolation/SimplifyInterpolationTests.cs
@@ -1056,10 +1056,65 @@ struct TypeNotImplementingIFormattable
}
""");
- [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42936")]
- public Task ToStringSimplificationIsNotOfferedOnRefStruct()
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/80132")]
+ public Task ToStringSimplificationIsNotOfferedOnRefStructIfInterpolatedStringHandlersUnavailable()
+ => TestMissingInRegularAndScriptAsync(
+ """
+ class C
+ {
+ string M(RefStruct someValue) => $"Test: {someValue[||].ToString()}";
+ }
+
+ ref struct RefStruct
+ {
+ public override string ToString() => "A";
+ }
+ """);
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/80132")]
+ public Task ToStringSimplificationIsNotOfferedOnReadOnlySpanIfInterpolatedStringHandlersUnavailable()
+ => TestMissingInRegularAndScriptAsync(
+ """
+ using System;
+
+ namespace System
+ {
+ public ref struct ReadOnlySpan { }
+ }
+
+ class C
+ {
+ string M(ReadOnlySpan span) => $"Test: {span[||].ToString()}";
+ }
+ """);
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/80132")]
+ public Task ToStringSimplificationIsNotOfferedOnSpanIfInterpolatedStringHandlersUnavailable()
=> TestMissingInRegularAndScriptAsync(
"""
+ using System;
+
+ namespace System
+ {
+ public ref struct Span { }
+ public ref struct ReadOnlySpan { }
+ }
+
+ class C
+ {
+ string M(Span span) => $"Test: {span[||].ToString()}";
+ }
+ """);
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/80132")]
+ public Task ToStringSimplificationIsNotOfferedOnRefStructIfInterpolatedStringHandlersAvailable()
+ => TestMissingInRegularAndScriptAsync(
+ """
+ namespace System.Runtime.CompilerServices
+ {
+ public class InterpolatedStringHandlerAttribute { }
+ }
+
class C
{
string M(RefStruct someValue) => $"Test: {someValue[||].ToString()}";
@@ -1071,6 +1126,223 @@ ref struct RefStruct
}
""");
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/80132")]
+ public Task ToStringSimplificationIsOfferedOnReadOnlySpanOfCharIfInterpolatedStringHandlersAvailable()
+ => TestInRegularAndScriptAsync(
+ """
+ using System;
+
+ namespace System
+ {
+ public ref struct ReadOnlySpan { }
+ }
+
+ namespace System.Runtime.CompilerServices
+ {
+ public class InterpolatedStringHandlerAttribute { }
+ }
+
+ class C
+ {
+ string M(ReadOnlySpan span) => $"Test: {span[||].ToString()}";
+ }
+ """,
+ """
+ using System;
+
+ namespace System
+ {
+ public ref struct ReadOnlySpan { }
+ }
+
+ namespace System.Runtime.CompilerServices
+ {
+ public class InterpolatedStringHandlerAttribute { }
+ }
+
+ class C
+ {
+ string M(ReadOnlySpan span) => $"Test: {span}";
+ }
+ """);
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/80132")]
+ public Task ToStringSimplificationIsOfferedOnSpanOfCharIfInterpolatedStringHandlersAvailable()
+ => TestInRegularAndScriptAsync(
+ """
+ using System;
+
+ namespace System
+ {
+ public ref struct Span { }
+ public ref struct ReadOnlySpan { }
+ }
+
+ namespace System.Runtime.CompilerServices
+ {
+ public class InterpolatedStringHandlerAttribute { }
+ }
+
+ class C
+ {
+ string M(Span span) => $"Test: {span[||].ToString()}";
+ }
+ """,
+ """
+ using System;
+
+ namespace System
+ {
+ public ref struct Span { }
+ public ref struct ReadOnlySpan { }
+ }
+
+ namespace System.Runtime.CompilerServices
+ {
+ public class InterpolatedStringHandlerAttribute { }
+ }
+
+ class C
+ {
+ string M(Span span) => $"Test: {span}";
+ }
+ """);
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/80132")]
+ public Task ToStringSimplificationIsNotOfferedOnReadOnlySpanOfIntIfInterpolatedStringHandlersAvailable()
+ => TestMissingInRegularAndScriptAsync(
+ """
+ using System;
+
+ namespace System
+ {
+ public ref struct ReadOnlySpan { }
+ }
+
+ namespace System.Runtime.CompilerServices
+ {
+ public class InterpolatedStringHandlerAttribute { }
+ }
+
+ class C
+ {
+ string M(ReadOnlySpan span) => $"Test: {span[||].ToString()}";
+ }
+ """);
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/80132")]
+ public Task ToStringSimplificationIsNotOfferedOnSpanOfIntIfInterpolatedStringHandlersAvailable()
+ => TestMissingInRegularAndScriptAsync(
+ """
+ using System;
+
+ namespace System
+ {
+ public ref struct Span { }
+ public ref struct ReadOnlySpan { }
+ }
+
+ namespace System.Runtime.CompilerServices
+ {
+ public class InterpolatedStringHandlerAttribute { }
+ }
+
+ class C
+ {
+ string M(Span span) => $"Test: {span[||].ToString()}";
+ }
+ """);
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/80132")]
+ public Task ToStringSimplificationIsNotOfferedOnReadOnlySpanIfTargetsFormattableStringAndInterpolatedStringHandlersAvailable()
+ => TestMissingInRegularAndScriptAsync(
+ """
+ using System;
+
+ namespace System
+ {
+ public ref struct ReadOnlySpan { }
+ }
+
+ namespace System.Runtime.CompilerServices
+ {
+ public class InterpolatedStringHandlerAttribute { }
+ }
+
+ class C
+ {
+ FormattableString M(ReadOnlySpan span) => $"Test: {span[||].ToString()}";
+ }
+ """);
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/80132")]
+ public Task ToStringSimplificationIsNotOfferedOnSpanIfTargetsFormattableStringAndInterpolatedStringHandlersAvailable()
+ => TestMissingInRegularAndScriptAsync(
+ """
+ using System;
+
+ namespace System
+ {
+ public ref struct Span { }
+ public ref struct ReadOnlySpan { }
+ }
+
+ namespace System.Runtime.CompilerServices
+ {
+ public class InterpolatedStringHandlerAttribute { }
+ }
+
+ class C
+ {
+ FormattableString M(Span span) => $"Test: {span[||].ToString()}";
+ }
+ """);
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/80132")]
+ public Task ToStringSimplificationIsNotOfferedOnReadOnlySpanIfTargetsIFormattableAndInterpolatedStringHandlersAvailable()
+ => TestMissingInRegularAndScriptAsync(
+ """
+ using System;
+
+ namespace System
+ {
+ public ref struct ReadOnlySpan { }
+ }
+
+ namespace System.Runtime.CompilerServices
+ {
+ public class InterpolatedStringHandlerAttribute { }
+ }
+
+ class C
+ {
+ IFormattable M(ReadOnlySpan span) => $"Test: {span[||].ToString()}";
+ }
+ """);
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/80132")]
+ public Task ToStringSimplificationIsNotOfferedOnSpanIfTargetsIFormattableAndInterpolatedStringHandlersAvailable()
+ => TestMissingInRegularAndScriptAsync(
+ """
+ using System;
+
+ namespace System
+ {
+ public ref struct Span { }
+ public ref struct ReadOnlySpan { }
+ }
+
+ namespace System.Runtime.CompilerServices
+ {
+ public class InterpolatedStringHandlerAttribute { }
+ }
+
+ class C
+ {
+ IFormattable M(Span span) => $"Test: {span[||].ToString()}";
+ }
+ """);
+
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42936")]
public Task PadLeftSimplificationIsStillOfferedOnRefStruct()
=> TestInRegularAndScriptAsync(
@@ -1232,7 +1504,7 @@ public Task TestNotPassedToFormattableString1()
"""
class C
{
- void B() => M($"{args[||].Length.ToString()}");
+ void B(string[] args) => M($"{args[||].Length.ToString()}");
void M(FormattableString fs)
{
@@ -1242,6 +1514,32 @@ void M(FormattableString fs)
}
""");
+ [Fact]
+ public Task TestNotPassedToIFormattable()
+ => TestMissingAsync(
+ """
+ class C : ICustomFormatter, IFormatProvider
+ {
+ void B(string[] args) => M($"{args[||].Length.ToString()}");
+
+ void M(IFormattable fs)
+ {
+ fs.ToString(null, formatProvider: this);
+ }
+
+ object? IFormatProvider.GetFormat(Type? formatType)
+ {
+ return formatType == typeof(ICustomFormatter) ? this : null;
+ }
+
+ string ICustomFormatter.Format(string? format, object? arg, IFormatProvider? formatProvider)
+ {
+ Console.WriteLine(arg?.GetType());
+ return "";
+ }
+ }
+ """);
+
[Theory]
[InlineData("DateTime", "ToLongDateString", "D")]
[InlineData("DateTime", "ToShortDateString", "d")]
diff --git a/src/roslyn/src/Analyzers/CSharp/Tests/UseCoalesceExpression/UseCoalesceExpressionForNullableTernaryConditionalCheckTests.cs b/src/roslyn/src/Analyzers/CSharp/Tests/UseCoalesceExpression/UseCoalesceExpressionForNullableTernaryConditionalCheckTests.cs
index c0ce194d899..d7f28579c60 100644
--- a/src/roslyn/src/Analyzers/CSharp/Tests/UseCoalesceExpression/UseCoalesceExpressionForNullableTernaryConditionalCheckTests.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Tests/UseCoalesceExpression/UseCoalesceExpressionForNullableTernaryConditionalCheckTests.cs
@@ -16,13 +16,9 @@
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseCoalesceExpression;
[Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)]
-public sealed class UseCoalesceExpressionForNullableTernaryConditionalCheckTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest_NoEditor
+public sealed class UseCoalesceExpressionForNullableTernaryConditionalCheckTests(ITestOutputHelper logger)
+ : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest_NoEditor(logger)
{
- public UseCoalesceExpressionForNullableTernaryConditionalCheckTests(ITestOutputHelper logger)
- : base(logger)
- {
- }
-
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpUseCoalesceExpressionForNullableTernaryConditionalCheckDiagnosticAnalyzer(),
new UseCoalesceExpressionForNullableTernaryConditionalCheckCodeFixProvider());
diff --git a/src/roslyn/src/Analyzers/CSharp/Tests/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationTests.cs b/src/roslyn/src/Analyzers/CSharp/Tests/UseImplicitObjectCreation/UseImplicitObjectCreationTests.cs
similarity index 92%
rename from src/roslyn/src/Analyzers/CSharp/Tests/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationTests.cs
rename to src/roslyn/src/Analyzers/CSharp/Tests/UseImplicitObjectCreation/UseImplicitObjectCreationTests.cs
index f21849ab4a6..656a00662c8 100644
--- a/src/roslyn/src/Analyzers/CSharp/Tests/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationTests.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Tests/UseImplicitObjectCreation/UseImplicitObjectCreationTests.cs
@@ -884,4 +884,75 @@ class C
""",
LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9,
}.RunAsync();
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/77670")]
+ public Task TestWithTask1()
+ => new VerifyCS.Test
+ {
+ TestCode = """
+ using System.Threading.Tasks;
+
+ class C
+ {
+ async Task Func() => [|new|] C();
+ }
+ """,
+ FixedCode = """
+ using System.Threading.Tasks;
+
+ class C
+ {
+ async Task Func() => new();
+ }
+ """,
+ LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9,
+ }.RunAsync();
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/77670")]
+ public Task TestWithValueTask1()
+ => new VerifyCS.Test
+ {
+ TestCode = """
+ using System.Threading.Tasks;
+
+ class C
+ {
+ async ValueTask Func() => [|new|] C();
+ }
+ """,
+ FixedCode = """
+ using System.Threading.Tasks;
+
+ class C
+ {
+ async ValueTask Func() => new();
+ }
+ """,
+ LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9,
+ ReferenceAssemblies = ReferenceAssemblies.Net.Net90,
+ }.RunAsync();
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/77670")]
+ public Task TestWithValueTask2()
+ => new VerifyCS.Test
+ {
+ TestCode = """
+ using System.Threading.Tasks;
+
+ class C
+ {
+ ValueTask Func() => [|new|] ValueTask(new C());
+ }
+ """,
+ FixedCode = """
+ using System.Threading.Tasks;
+
+ class C
+ {
+ ValueTask Func() => new(new C());
+ }
+ """,
+ LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9,
+ ReferenceAssemblies = ReferenceAssemblies.Net.Net90,
+ }.RunAsync();
}
diff --git a/src/roslyn/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests.cs b/src/roslyn/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests.cs
index f691b50c914..752d47982a6 100644
--- a/src/roslyn/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests.cs
@@ -15,7 +15,7 @@
using Xunit;
using Xunit.Abstractions;
-namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseExplicitType;
+namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseImplicitOrExplicitType;
[Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public sealed partial class UseExplicitTypeTests(ITestOutputHelper logger)
diff --git a/src/roslyn/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests_FixAllTests.cs b/src/roslyn/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests_FixAllTests.cs
index 579fa8661e1..f519af2ce8f 100644
--- a/src/roslyn/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests_FixAllTests.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests_FixAllTests.cs
@@ -8,7 +8,7 @@
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
-namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseExplicitType;
+namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseImplicitOrExplicitType;
public partial class UseExplicitTypeTests
{
@@ -81,8 +81,8 @@ class Program
static int F(int x, int y)
{
int i1 = 0;
- Program p = new Program();
- Tuple<bool, int> tuple = Tuple.Create(true, 1);
+ var p = new Program();
+ var tuple = Tuple.Create(true, 1);
return i1;
}
@@ -191,8 +191,8 @@ class Program
static int F(int x, int y)
{
int i1 = 0;
- Program p = new Program();
- Tuple<bool, int> tuple = Tuple.Create(true, 1);
+ var p = new Program();
+ var tuple = Tuple.Create(true, 1);
return i1;
}
@@ -206,8 +206,8 @@ class Program2
static int F(int x, int y)
{
int i2 = 0;
- Program2 p2 = new Program2();
- Tuple<bool, int> tuple2 = Tuple.Create(true, 1);
+ var p2 = new Program2();
+ var tuple2 = Tuple.Create(true, 1);
return i2;
}
@@ -301,8 +301,8 @@ class Program
static int F(int x, int y)
{
int i1 = 0;
- Program p = new Program();
- Tuple<bool, int> tuple = Tuple.Create(true, 1);
+ var p = new Program();
+ var tuple = Tuple.Create(true, 1);
return i1;
}
@@ -316,8 +316,8 @@ class Program2
static int F(int x, int y)
{
int i2 = 0;
- Program2 p2 = new Program2();
- Tuple<bool, int> tuple2 = Tuple.Create(true, 1);
+ var p2 = new Program2();
+ var tuple2 = Tuple.Create(true, 1);
return i2;
}
@@ -333,8 +333,8 @@ class Program2
static int F(int x, int y)
{
int i3 = 0;
- Program2 p3 = new Program2();
- Tuple<bool, int> tuple3 = Tuple.Create(true, 1);
+ var p3 = new Program2();
+ var tuple3 = Tuple.Create(true, 1);
return i3;
}
@@ -359,6 +359,7 @@ class Program
static int F(int x, int y)
{
{|FixAllInDocument:var|} p = this;
+ var p2 = this;
var i1 = 0;
var tuple = Tuple.Create(true, 1);
@@ -379,7 +380,8 @@ class Program
static int F(int x, int y)
{
Program p = this;
- int i1 = 0;
+ Program p2 = this;
+ var i1 = 0;
var tuple = Tuple.Create(true, 1);
return i1;
diff --git a/src/roslyn/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseImplicitTypeTests.cs b/src/roslyn/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseImplicitTypeTests.cs
index a2edd1f4c3f..42d3dfe99da 100644
--- a/src/roslyn/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseImplicitTypeTests.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseImplicitTypeTests.cs
@@ -16,7 +16,7 @@
using Xunit;
using Xunit.Abstractions;
-namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseImplicitType;
+namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseImplicitOrExplicitType;
[Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public sealed partial class UseImplicitTypeTests(ITestOutputHelper? logger = null)
diff --git a/src/roslyn/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseImplicitTypeTests_FixAllTests.cs b/src/roslyn/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseImplicitTypeTests_FixAllTests.cs
index 3a16dd2dbb7..3e1f52b2d2d 100644
--- a/src/roslyn/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseImplicitTypeTests_FixAllTests.cs
+++ b/src/roslyn/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseImplicitTypeTests_FixAllTests.cs
@@ -8,7 +8,7 @@
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
-namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseImplicitType;
+namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseImplicitOrExplicitType;
public partial class UseImplicitTypeTests
{
@@ -81,8 +81,8 @@ class Program
static int F(int x, int y)
{
var i1 = 0;
- var p = new Program();
- var tuple = Tuple.Create(true, 1);
+ Program p = new Program();
+ Tuple<bool, int> tuple = Tuple.Create(true, 1);
return i1;
}
@@ -191,8 +191,8 @@ class Program
static int F(int x, int y)
{
var i1 = 0;
- var p = new Program();
- var tuple = Tuple.Create(true, 1);
+ Program p = new Program();
+ Tuple<bool, int> tuple = Tuple.Create(true, 1);
return i1;
}
@@ -206,8 +206,8 @@ class Program2
static int F(int x, int y)
{
var i2 = 0;
- var p2 = new Program2();
- var tuple2 = Tuple.Create(true, 1);
+ Program2 p2 = new Program2();
+ Tuple<bool, int> tuple2 = Tuple.Create(true, 1);
return i2;
}
@@ -301,8 +301,8 @@ class Program
static int F(int x, int y)
{
var i1 = 0;
- var p = new Program();
- var tuple = Tuple.Create(true, 1);
+ Program p = new Program();
+ Tuple<bool, int> tuple = Tuple.Create(true, 1);
return i1;
}
@@ -316,8 +316,8 @@ class Program2
static int F(int x, int y)
{
var i2 = 0;
- var p2 = new Program2();
- var tuple2 = Tuple.Create(true, 1);
+ Program2 p2 = new Program2();
+ Tuple<bool, int> tuple2 = Tuple.Create(true, 1);
return i2;
}
@@ -333,8 +333,8 @@ class Program2
static int F(int x, int y)
{
var i3 = 0;
- var p3 = new Program2();
- var tuple3 = Tuple.Create(true, 1);
+ Program2 p3 = new Program2();
+ Tuple<bool, int> tuple3 = Tuple.Create(true, 1);
return i3;
}
diff --git a/src/roslyn/src/Analyzers/CSharp/Tests/UseNullPropagation/UseNullPropagationTests.cs b/src/roslyn/src/Analyzers/CSharp/Tests/UseNullPropagation/UseNullPropagationTests.cs
index 44a84832f08..6416757e777 100644
--- a/src/roslyn/src/Analyzers/CSharp/Tests/UseNullPropagation/UseNullPropagationTests.cs
+++ b/src/roslyn/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.Shared.Extensions;
using Microsoft.CodeAnalysis.CSharp.UseNullPropagation;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
@@ -48,6 +47,7 @@ private static Task TestMissingInRegularAndScriptAsync(
=> new VerifyCS.Test
{
TestCode = testCode,
+ FixedCode = testCode,
LanguageVersion = languageVersion,
}.RunAsync();
@@ -2664,4 +2664,119 @@ void X(string s) { }
}
""",
languageVersion: LanguageVersion.CSharp14);
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64431")]
+ public Task TestUnconstrainedGenericType()
+ => TestMissingInRegularAndScriptAsync(
+ """
+ public sealed class Element
+ {
+ public T Key { get; }
+
+ public bool Equals(Element x)
+ {
+ return Equals(null, x is null ? null : x.Key);
+ }
+ }
+ """,
+ languageVersion: LanguageVersion.CSharp14);
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64431")]
+ public Task TestInterfaceTypeConstrainedGenericType()
+ => TestMissingInRegularAndScriptAsync(
+ """
+ public sealed class Element : System.IDisposable
+ {
+ public T Key { get; }
+
+ public bool Equals(Element x)
+ {
+ return Equals(null, x is null ? null : x.Key);
+ }
+
+ public void Dispose() { }
+ }
+ """,
+ languageVersion: LanguageVersion.CSharp14);
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64431")]
+ public Task TestClassConstrainedGenericType()
+ => TestInRegularAndScriptAsync(
+ """
+ public sealed class Element where T : class
+ {
+ public T Key { get; }
+
+ public bool Equals(Element x)
+ {
+ return Equals(null, [|x is null ? null : x.Key|]);
+ }
+ }
+ """,
+ """
+ public sealed class Element where T : class
+ {
+ public T Key { get; }
+
+ public bool Equals(Element x)
+ {
+ return Equals(null, x?.Key);
+ }
+ }
+ """,
+ languageVersion: LanguageVersion.CSharp14);
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64431")]
+ public Task TestStructConstrainedGenericType()
+ => TestInRegularAndScriptAsync(
+ """
+ public sealed class Element where T : struct
+ {
+ public T Key { get; }
+
+ public bool Equals(Element x)
+ {
+ return Equals(null, [|x is null ? null : x.Key|]);
+ }
+ }
+ """,
+ """
+ public sealed class Element where T : struct
+ {
+ public T Key { get; }
+
+ public bool Equals(Element x)
+ {
+ return Equals(null, x?.Key);
+ }
+ }
+ """,
+ languageVersion: LanguageVersion.CSharp14);
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64431")]
+ public Task TestRefTypeConstrainedGenericType()
+ => TestInRegularAndScriptAsync(
+ """
+ public sealed class Element where T : System.Exception
+ {
+ public T Key { get; }
+
+ public bool Equals(Element x)
+ {
+ return Equals(null, [|x is null ? null : x.Key|]);
+ }
+ }
+ """,
+ """
+ public sealed class Element where T : System.Exception
+ {
+ public T Key { get; }
+
+ public bool Equals(Element x)
+ {
+ return Equals(null, x?.Key);
+ }
+ }
+ """,
+ languageVersion: LanguageVersion.CSharp14);
}
diff --git a/src/roslyn/src/Analyzers/Core/Analyzers/IDEDiagnosticIdToOptionMappingHelper.cs b/src/roslyn/src/Analyzers/Core/Analyzers/IDEDiagnosticIdToOptionMappingHelper.cs
index e3ae127f772..ab070b6da8c 100644
--- a/src/roslyn/src/Analyzers/Core/Analyzers/IDEDiagnosticIdToOptionMappingHelper.cs
+++ b/src/roslyn/src/Analyzers/Core/Analyzers/IDEDiagnosticIdToOptionMappingHelper.cs
@@ -31,9 +31,9 @@ public static bool TryGetMappedOptions(string diagnosticId, string language, [No
public static bool TryGetMappedFadingOption(string diagnosticId, [NotNullWhen(true)] out PerLanguageOption2? fadingOption)
=> s_diagnosticIdToFadingOptionMap.TryGetValue(diagnosticId, out fadingOption);
- public static bool IsKnownIDEDiagnosticId(string diagnosticId)
- => s_diagnosticIdToOptionMap.ContainsKey(diagnosticId) ||
- s_diagnosticIdToLanguageSpecificOptionsMap.Values.Any(map => map.ContainsKey(diagnosticId));
+ public static ImmutableHashSet KnownIDEDiagnosticIds
+ => [.. s_diagnosticIdToOptionMap.Keys,
+ .. s_diagnosticIdToLanguageSpecificOptionsMap.Values.SelectMany(map => map.Keys)];
public static void AddOptionMapping(string diagnosticId, ImmutableHashSet options)
{
diff --git a/src/roslyn/src/Analyzers/Core/Analyzers/RemoveUnnecessarySuppressions/AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer.cs b/src/roslyn/src/Analyzers/Core/Analyzers/RemoveUnnecessarySuppressions/AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer.cs
index e8555ba286a..e968035ca61 100644
--- a/src/roslyn/src/Analyzers/Core/Analyzers/RemoveUnnecessarySuppressions/AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer.cs
+++ b/src/roslyn/src/Analyzers/Core/Analyzers/RemoveUnnecessarySuppressions/AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer.cs
@@ -68,7 +68,7 @@ protected sealed override void InitializeWorker(AnalysisContext context)
protected sealed class CompilationAnalyzer(Compilation compilation, INamedTypeSymbol suppressMessageAttributeType)
{
- private readonly SuppressMessageAttributeState _state = new SuppressMessageAttributeState(compilation, suppressMessageAttributeType);
+ private readonly SuppressMessageAttributeState _state = new(compilation, suppressMessageAttributeType);
public void AnalyzeAssemblyOrModuleAttribute(SyntaxNode attributeSyntax, SemanticModel model, Action reportDiagnostic, CancellationToken cancellationToken)
{
diff --git a/src/roslyn/src/Analyzers/Core/Analyzers/SimplifyInterpolation/AbstractSimplifyInterpolationDiagnosticAnalyzer.cs b/src/roslyn/src/Analyzers/Core/Analyzers/SimplifyInterpolation/AbstractSimplifyInterpolationDiagnosticAnalyzer.cs
index feae0e74b51..b24f3b83f33 100644
--- a/src/roslyn/src/Analyzers/Core/Analyzers/SimplifyInterpolation/AbstractSimplifyInterpolationDiagnosticAnalyzer.cs
+++ b/src/roslyn/src/Analyzers/Core/Analyzers/SimplifyInterpolation/AbstractSimplifyInterpolationDiagnosticAnalyzer.cs
@@ -36,13 +36,20 @@ protected override void InitializeWorker(AnalysisContext context)
{
var compilation = context.Compilation;
var knownToStringFormats = Helpers.BuildKnownToStringFormatsLookupTable(compilation);
- context.RegisterOperationAction(context => AnalyzeInterpolation(context, compilation.FormattableStringType(), knownToStringFormats), OperationKind.Interpolation);
+
+ var readOnlySpanOfCharType = compilation.ReadOnlySpanOfTType()?.Construct(compilation.GetSpecialType(SpecialType.System_Char));
+ var handlersAvailable = compilation.InterpolatedStringHandlerAttributeType() != null;
+
+ context.RegisterOperationAction(context => AnalyzeInterpolation(context, compilation.FormattableStringType(), compilation.IFormattableType(), readOnlySpanOfCharType, knownToStringFormats, handlersAvailable), OperationKind.Interpolation);
});
private void AnalyzeInterpolation(
OperationAnalysisContext context,
INamedTypeSymbol? formattableStringType,
- ImmutableDictionary knownToStringFormats)
+ INamedTypeSymbol? iFormattableType,
+ INamedTypeSymbol? readOnlySpanOfCharType,
+ ImmutableDictionary knownToStringFormats,
+ bool handlersAvailable)
{
var option = context.GetAnalyzerOptions().PreferSimplifiedInterpolation;
@@ -55,7 +62,7 @@ private void AnalyzeInterpolation(
// Formattable strings can observe the inner types of the arguments passed to them. So we can't safely change
// to drop ToString in that.
if (interpolation.Parent is IInterpolatedStringOperation { Parent: IConversionOperation { Type: { } convertedType } conversion } &&
- convertedType.Equals(formattableStringType))
+ (convertedType.Equals(formattableStringType) || convertedType.Equals(iFormattableType)))
{
// One exception to this is calling directly into FormattableString.Invariant. That method has known good
// behavior that is fine to continue calling into.
@@ -68,7 +75,7 @@ private void AnalyzeInterpolation(
}
this.Helpers.UnwrapInterpolation(
- this.VirtualCharService, this.SyntaxFacts, interpolation, knownToStringFormats, out _, out var alignment, out _,
+ this.VirtualCharService, this.SyntaxFacts, interpolation, knownToStringFormats, readOnlySpanOfCharType, handlersAvailable, out _, out var alignment, out _,
out var formatString, out var unnecessaryLocations);
if (alignment == null && formatString == null)
diff --git a/src/roslyn/src/Analyzers/Core/Analyzers/SimplifyInterpolation/AbstractSimplifyInterpolationHelpers.cs b/src/roslyn/src/Analyzers/Core/Analyzers/SimplifyInterpolation/AbstractSimplifyInterpolationHelpers.cs
index dfe238707ed..a66b3581257 100644
--- a/src/roslyn/src/Analyzers/Core/Analyzers/SimplifyInterpolation/AbstractSimplifyInterpolationHelpers.cs
+++ b/src/roslyn/src/Analyzers/Core/Analyzers/SimplifyInterpolation/AbstractSimplifyInterpolationHelpers.cs
@@ -65,6 +65,8 @@ public void UnwrapInterpolation(
ISyntaxFacts syntaxFacts,
IInterpolationOperation interpolation,
ImmutableDictionary knownToStringFormats,
+ INamedTypeSymbol? readOnlySpanOfCharType,
+ bool handlersAvailable,
out TExpressionSyntax? unwrapped,
out TExpressionSyntax? alignment,
out bool negate,
@@ -82,7 +84,7 @@ public void UnwrapInterpolation(
UnwrapAlignmentPadding(expression, out expression, out alignment, out negate, unnecessarySpans);
if (interpolation.FormatString == null)
- UnwrapFormatString(virtualCharService, syntaxFacts, expression, knownToStringFormats, out expression, out formatString, unnecessarySpans);
+ UnwrapFormatString(virtualCharService, syntaxFacts, expression, knownToStringFormats, readOnlySpanOfCharType, handlersAvailable, out expression, out formatString, unnecessarySpans);
unwrapped = GetPreservedInterpolationExpressionSyntax(expression) as TExpressionSyntax;
@@ -118,6 +120,8 @@ private void UnwrapFormatString(
ISyntaxFacts syntaxFacts,
IOperation expression,
ImmutableDictionary knownToStringFormats,
+ INamedTypeSymbol? readOnlySpanOfCharType,
+ bool handlersAvailable,
out IOperation unwrapped,
out string? formatString,
ArrayBuilder unnecessarySpans)
@@ -128,41 +132,43 @@ private void UnwrapFormatString(
HasNonImplicitInstance(invocation, out var instance) &&
!syntaxFacts.IsBaseExpression(instance.Syntax))
{
- if (targetMethod.Name == nameof(ToString) &&
- instance.Type is { IsRefLikeType: false })
+ if (targetMethod.Name == nameof(ToString))
{
- if (invocation.Arguments.Length == 1
- || (invocation.Arguments.Length == 2 && UsesInvariantCultureReferenceInsideFormattableStringInvariant(invocation, formatProviderArgumentIndex: 1)))
+ // If type of instance is not ref-like type or is {ReadOnly}Span that is allowed in interpolated strings in .NET 6+
+ if (instance.Type is { IsRefLikeType: false } || IsRefLikeTypeAllowed(instance.Type))
{
- if (invocation.Arguments[0].Value is ILiteralOperation { ConstantValue: { HasValue: true, Value: string value } } literal &&
- FindType(expression.SemanticModel) is { } systemIFormattable &&
- instance.Type.Implements(systemIFormattable))
+ if (invocation.Arguments.Length == 1
+ || (invocation.Arguments.Length == 2 && UsesInvariantCultureReferenceInsideFormattableStringInvariant(invocation, formatProviderArgumentIndex: 1)))
{
+ if (invocation.Arguments[0].Value is ILiteralOperation { ConstantValue: { HasValue: true, Value: string value } } literal &&
+ FindType(expression.SemanticModel) is { } systemIFormattable &&
+ instance.Type.Implements(systemIFormattable))
+ {
+ unwrapped = instance;
+ formatString = value;
+
+ unnecessarySpans.AddRange(invocation.Syntax.Span
+ .Subtract(GetPreservedInterpolationExpressionSyntax(instance).FullSpan)
+ .Subtract(GetSpanWithinLiteralQuotes(virtualCharService, literal.Syntax.GetFirstToken())));
+ return;
+ }
+ }
+
+ if (IsObjectToStringOverride(invocation.TargetMethod)
+ || (invocation.Arguments.Length == 1 && UsesInvariantCultureReferenceInsideFormattableStringInvariant(invocation, formatProviderArgumentIndex: 0)))
+ {
+ // A call to `.ToString()` at the end of the interpolation. This is unnecessary.
+ // Just remove entirely.
unwrapped = instance;
- formatString = value;
+ formatString = "";
unnecessarySpans.AddRange(invocation.Syntax.Span
- .Subtract(GetPreservedInterpolationExpressionSyntax(instance).FullSpan)
- .Subtract(GetSpanWithinLiteralQuotes(virtualCharService, literal.Syntax.GetFirstToken())));
+ .Subtract(GetPreservedInterpolationExpressionSyntax(instance).FullSpan));
return;
}
}
-
- if (IsObjectToStringOverride(invocation.TargetMethod)
- || (invocation.Arguments.Length == 1 && UsesInvariantCultureReferenceInsideFormattableStringInvariant(invocation, formatProviderArgumentIndex: 0)))
- {
- // A call to `.ToString()` at the end of the interpolation. This is unnecessary.
- // Just remove entirely.
- unwrapped = instance;
- formatString = "";
-
- unnecessarySpans.AddRange(invocation.Syntax.Span
- .Subtract(GetPreservedInterpolationExpressionSyntax(instance).FullSpan));
- return;
- }
}
-
- if (knownToStringFormats.TryGetValue(targetMethod, out var format))
+ else if (knownToStringFormats.TryGetValue(targetMethod, out var format))
{
// A call to a known ToString-like method, e.g. `DateTime.ToLongDateString()`
// We replace this call with predefined format specifier
@@ -177,6 +183,13 @@ private void UnwrapFormatString(
unwrapped = expression;
formatString = null;
+
+ bool IsRefLikeTypeAllowed([NotNullWhen(true)] ITypeSymbol? type)
+ {
+ var compilation = expression.SemanticModel.Compilation;
+ // {ReadOnly}Span is allowed if interpolated string handlers are available in the compilation (.NET 6+)
+ return handlersAvailable && compilation.HasImplicitConversion(type, readOnlySpanOfCharType);
+ }
}
private static bool IsObjectToStringOverride(IMethodSymbol method)
diff --git a/src/roslyn/src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractObjectCreationExpressionAnalyzer.cs b/src/roslyn/src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractObjectCreationExpressionAnalyzer.cs
index 682ab67dc11..0425165f060 100644
--- a/src/roslyn/src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractObjectCreationExpressionAnalyzer.cs
+++ b/src/roslyn/src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractObjectCreationExpressionAnalyzer.cs
@@ -42,7 +42,6 @@ public readonly record struct AnalysisResult(
protected UpdateExpressionState State;
protected TObjectCreationExpressionSyntax _objectCreationExpression = null!;
- protected bool _analyzeForCollectionExpression;
protected ISyntaxFacts SyntaxFacts => this.State.SyntaxFacts;
protected SemanticModel SemanticModel => this.State.SemanticModel;
@@ -65,19 +64,16 @@ public void Dispose()
public void Initialize(
UpdateExpressionState state,
- TObjectCreationExpressionSyntax objectCreationExpression,
- bool analyzeForCollectionExpression)
+ TObjectCreationExpressionSyntax objectCreationExpression)
{
State = state;
_objectCreationExpression = objectCreationExpression;
- _analyzeForCollectionExpression = analyzeForCollectionExpression;
}
- protected void Clear()
+ protected virtual void Clear()
{
State = default;
_objectCreationExpression = null!;
- _analyzeForCollectionExpression = false;
}
protected AnalysisResult AnalyzeWorker(CancellationToken cancellationToken)
@@ -93,11 +89,10 @@ protected AnalysisResult AnalyzeWorker(CancellationToken cancellationToken)
return new(preMatches.ToImmutableAndClear(), postMatches.ToImmutableAndClear(), mayChangeSemantics);
}
- protected UpdateExpressionState? TryInitializeState(
+ protected UpdateExpressionState TryInitializeState(
SemanticModel semanticModel,
ISyntaxFacts syntaxFacts,
TObjectCreationExpressionSyntax rootExpression,
- bool analyzeForCollectionExpression,
CancellationToken cancellationToken)
{
var statement = rootExpression.FirstAncestorOrSelf()!;
@@ -107,18 +102,11 @@ protected AnalysisResult AnalyzeWorker(CancellationToken cancellationToken)
TryInitializeVariableDeclarationCase(semanticModel, syntaxFacts, rootExpression, statement, cancellationToken) ??
TryInitializeAssignmentCase(semanticModel, syntaxFacts, rootExpression, statement, cancellationToken);
if (result != null)
- return result;
+ return result.Value;
}
- // Even if the above cases didn't work, we always support converting a `new List()` collection over to
- // a collection expression. We just won't analyze later statements.
- if (analyzeForCollectionExpression)
- {
- return new UpdateExpressionState(
- semanticModel, syntaxFacts, rootExpression, valuePattern: default, initializedSymbol: null);
- }
-
- return null;
+ return new UpdateExpressionState(
+ semanticModel, syntaxFacts, rootExpression, valuePattern: default, initializedSymbol: null);
}
private UpdateExpressionState? TryInitializeVariableDeclarationCase(
diff --git a/src/roslyn/src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractUseCollectionInitializerAnalyzer.cs b/src/roslyn/src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractUseCollectionInitializerAnalyzer.cs
index 86321d0d833..9020d3fa328 100644
--- a/src/roslyn/src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractUseCollectionInitializerAnalyzer.cs
+++ b/src/roslyn/src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractUseCollectionInitializerAnalyzer.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;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
@@ -11,7 +10,6 @@
using Microsoft.CodeAnalysis.LanguageService;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.UseCollectionExpression;
-using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.UseCollectionInitializer;
@@ -50,6 +48,8 @@ internal abstract class AbstractUseCollectionInitializerAnalyzer<
TVariableDeclaratorSyntax,
TAnalyzer>, new()
{
+ protected bool _analyzeForCollectionExpression;
+
protected abstract bool IsComplexElementInitializer(SyntaxNode expression);
protected abstract bool HasExistingInvalidInitializerForCollection();
protected abstract bool AnalyzeMatchesAndCollectionConstructorForCollectionExpression(
@@ -60,6 +60,12 @@ protected abstract bool AnalyzeMatchesAndCollectionConstructorForCollectionExpre
protected abstract IUpdateExpressionSyntaxHelper SyntaxHelper { get; }
+ protected override void Clear()
+ {
+ base.Clear();
+ _analyzeForCollectionExpression = false;
+ }
+
public AnalysisResult Analyze(
SemanticModel semanticModel,
ISyntaxFacts syntaxFacts,
@@ -67,11 +73,16 @@ public AnalysisResult Analyze(
bool analyzeForCollectionExpression,
CancellationToken cancellationToken)
{
- var state = TryInitializeState(semanticModel, syntaxFacts, objectCreationExpression, analyzeForCollectionExpression, cancellationToken);
- if (state is null)
+ _analyzeForCollectionExpression = analyzeForCollectionExpression;
+ var state = TryInitializeState(semanticModel, syntaxFacts, objectCreationExpression, cancellationToken);
+
+ // If we didn't find something we're assigned to, then we normally can't continue. However, we always support
+ // converting a `new List()` collection over to a collection expression. We just won't analyze later
+ // statements.
+ if (state.ValuePattern == default && !analyzeForCollectionExpression)
return default;
- this.Initialize(state.Value, objectCreationExpression, analyzeForCollectionExpression);
+ this.Initialize(state, objectCreationExpression);
var (preMatches, postMatches, mayChangeSemantics) = this.AnalyzeWorker(cancellationToken);
// If analysis failed entirely, immediately bail out.
diff --git a/src/roslyn/src/Analyzers/Core/Analyzers/UseCollectionInitializer/UpdateExpressionState.cs b/src/roslyn/src/Analyzers/Core/Analyzers/UseCollectionInitializer/UpdateExpressionState.cs
index 274f8c9dc8f..bb8f49943b6 100644
--- a/src/roslyn/src/Analyzers/Core/Analyzers/UseCollectionInitializer/UpdateExpressionState.cs
+++ b/src/roslyn/src/Analyzers/Core/Analyzers/UseCollectionInitializer/UpdateExpressionState.cs
@@ -20,7 +20,12 @@ namespace Microsoft.CodeAnalysis.UseCollectionInitializer;
///
internal readonly struct UpdateExpressionState<
TExpressionSyntax,
- TStatementSyntax>
+ TStatementSyntax>(
+ SemanticModel semanticModel,
+ ISyntaxFacts syntaxFacts,
+ TExpressionSyntax startExpression,
+ SyntaxNodeOrToken valuePattern,
+ ISymbol? initializedSymbol)
where TExpressionSyntax : SyntaxNode
where TStatementSyntax : SyntaxNode
{
@@ -31,44 +36,29 @@ internal readonly struct UpdateExpressionState<
(nameof(Enumerable.Append), isLinq: true),
];
- public readonly SemanticModel SemanticModel;
- public readonly ISyntaxFacts SyntaxFacts;
+ public readonly SemanticModel SemanticModel = semanticModel;
+ public readonly ISyntaxFacts SyntaxFacts = syntaxFacts;
///
/// The original object-creation or collection-builder-creation expression.
///
- public readonly TExpressionSyntax StartExpression;
+ public readonly TExpressionSyntax StartExpression = startExpression;
///
/// The statement containing
///
- public readonly TStatementSyntax? ContainingStatement;
+ public readonly TStatementSyntax? ContainingStatement = startExpression.FirstAncestorOrSelf()!;
///
/// The name of the value being mutated. It is whatever the new object-creation or collection-builder is assigned to.
///
- public readonly SyntaxNodeOrToken ValuePattern;
+ public readonly SyntaxNodeOrToken ValuePattern = valuePattern;
///
/// If a different symbol was initialized (for example, a field rather than a local) this will be that symbol. This
/// only applies to the object-creation case.
///
- public readonly ISymbol? InitializedSymbol;
-
- public UpdateExpressionState(
- SemanticModel semanticModel,
- ISyntaxFacts syntaxFacts,
- TExpressionSyntax startExpression,
- SyntaxNodeOrToken valuePattern,
- ISymbol? initializedSymbol)
- {
- SemanticModel = semanticModel;
- SyntaxFacts = syntaxFacts;
- StartExpression = startExpression;
- ContainingStatement = startExpression.FirstAncestorOrSelf()!;
- ValuePattern = valuePattern;
- InitializedSymbol = initializedSymbol;
- }
+ public readonly ISymbol? InitializedSymbol = initializedSymbol;
public IEnumerable GetSubsequentStatements()
=> ContainingStatement is null
diff --git a/src/roslyn/src/Analyzers/Core/Analyzers/UseNullPropagation/AbstractUseNullPropagationDiagnosticAnalyzer.cs b/src/roslyn/src/Analyzers/Core/Analyzers/UseNullPropagation/AbstractUseNullPropagationDiagnosticAnalyzer.cs
index ab6ac47e21d..fd6b8ce86af 100644
--- a/src/roslyn/src/Analyzers/Core/Analyzers/UseNullPropagation/AbstractUseNullPropagationDiagnosticAnalyzer.cs
+++ b/src/roslyn/src/Analyzers/Core/Analyzers/UseNullPropagation/AbstractUseNullPropagationDiagnosticAnalyzer.cs
@@ -215,6 +215,19 @@ private void AnalyzeTernaryConditionalExpressionAndReportDiagnostic(
if (memberSymbol is IMethodSymbol)
return null;
+ // we're converting from `x.M` to `x?.M`. This is not legal if 'M' is an unconstrained type parameter as
+ // the lang/compiler doesn't know what final type to make out of this.
+
+ var memberType = semanticModel.GetTypeInfo(whenPartToCheck, cancellationToken).Type;
+ if (memberType is null or ITypeParameterSymbol
+ {
+ IsReferenceType: false,
+ IsValueType: false,
+ })
+ {
+ return null;
+ }
+
// `x == null ? x : x.Value` will be converted to just 'x'.
if (UseNullPropagationHelpers.IsSystemNullableValueProperty(memberSymbol))
isTrivialNullableValueAccess = true;
diff --git a/src/roslyn/src/Analyzers/Core/Analyzers/UseObjectInitializer/AbstractUseObjectInitializerDiagnosticAnalyzer.cs b/src/roslyn/src/Analyzers/Core/Analyzers/UseObjectInitializer/AbstractUseObjectInitializerDiagnosticAnalyzer.cs
index e13de8a6c92..d2a85c0cf4f 100644
--- a/src/roslyn/src/Analyzers/Core/Analyzers/UseObjectInitializer/AbstractUseObjectInitializerDiagnosticAnalyzer.cs
+++ b/src/roslyn/src/Analyzers/Core/Analyzers/UseObjectInitializer/AbstractUseObjectInitializerDiagnosticAnalyzer.cs
@@ -8,7 +8,6 @@
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageService;
-using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.UseObjectInitializer;
diff --git a/src/roslyn/src/Analyzers/Core/Analyzers/UseObjectInitializer/UseNamedMemberInitializerAnalyzer.cs b/src/roslyn/src/Analyzers/Core/Analyzers/UseObjectInitializer/UseNamedMemberInitializerAnalyzer.cs
index 6760960332f..21ebd6e7b4f 100644
--- a/src/roslyn/src/Analyzers/Core/Analyzers/UseObjectInitializer/UseNamedMemberInitializerAnalyzer.cs
+++ b/src/roslyn/src/Analyzers/Core/Analyzers/UseObjectInitializer/UseNamedMemberInitializerAnalyzer.cs
@@ -52,11 +52,13 @@ public ImmutableArray(string language) where TLanguageService : ILanguageService
- => _document.Project.Solution.Workspace.Services.GetExtendedLanguageServices(language).GetRequiredService();
+ => _document.Project.Solution.GetRequiredLanguageService(language);
private bool ClashesWithExistingConstructor()
{
diff --git a/src/roslyn/src/Analyzers/Core/CodeFixes/GenerateEnumMember/AbstractGenerateEnumMemberService.CodeAction.cs b/src/roslyn/src/Analyzers/Core/CodeFixes/GenerateEnumMember/AbstractGenerateEnumMemberService.CodeAction.cs
index 51855dbec33..c008fab550a 100644
--- a/src/roslyn/src/Analyzers/Core/CodeFixes/GenerateEnumMember/AbstractGenerateEnumMemberService.CodeAction.cs
+++ b/src/roslyn/src/Analyzers/Core/CodeFixes/GenerateEnumMember/AbstractGenerateEnumMemberService.CodeAction.cs
@@ -8,6 +8,7 @@
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.LanguageService;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.GenerateMember.GenerateEnumMember;
@@ -21,7 +22,7 @@ private sealed partial class GenerateEnumMemberCodeAction(Document document, Sta
protected override async Task GetChangedDocumentAsync(CancellationToken cancellationToken)
{
- var languageServices = _document.Project.Solution.Workspace.Services.GetExtendedLanguageServices(_state.TypeToGenerateIn.Language);
+ var languageServices = _document.Project.Solution.GetExtendedLanguageServices(_state.TypeToGenerateIn.Language);
var codeGenerator = languageServices.GetRequiredService();
var semanticFacts = languageServices.GetRequiredService();
diff --git a/src/roslyn/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateParameterizedMemberService.SignatureInfo.cs b/src/roslyn/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateParameterizedMemberService.SignatureInfo.cs
index 3a0fca8de4c..efe083d293c 100644
--- a/src/roslyn/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateParameterizedMemberService.SignatureInfo.cs
+++ b/src/roslyn/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateParameterizedMemberService.SignatureInfo.cs
@@ -118,9 +118,7 @@ public async ValueTask GenerateMethodAsync(
methodKind: State.MethodKind);
// Ensure no conflicts between type parameter names and parameter names.
- var languageServiceProvider = Document.Project.Solution.Workspace.Services.GetExtendedLanguageServices(State.TypeToGenerateIn.Language);
-
- var syntaxFacts = languageServiceProvider.GetService();
+ var syntaxFacts = Document.Project.Solution.GetLanguageService(State.TypeToGenerateIn.Language);
var equalityComparer = syntaxFacts.StringComparer;
var reservedParameterNames = DetermineParameterNames(cancellationToken)
diff --git a/src/roslyn/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateParameterizedMemberService.State.cs b/src/roslyn/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateParameterizedMemberService.State.cs
index ce6a1619e54..24c4323b4a1 100644
--- a/src/roslyn/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateParameterizedMemberService.State.cs
+++ b/src/roslyn/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateParameterizedMemberService.State.cs
@@ -82,7 +82,7 @@ protected async Task TryFinishInitializingStateAsync(TService service, Sem
.GetMembers(IdentifierToken.ValueText)
.OfType