diff --git a/.editorconfig b/.editorconfig index 150c8862e728a..6d966e98ae243 100644 --- a/.editorconfig +++ b/.editorconfig @@ -233,9 +233,6 @@ csharp_prefer_braces = true:silent csharp_preserve_single_line_blocks = true csharp_preserve_single_line_statements = true -# warning RS0037: PublicAPI.txt is missing '#nullable enable' -dotnet_diagnostic.RS0037.severity = none - [src/CodeStyle/**.{cs,vb}] # warning RS0005: Do not use generic CodeAction.Create to create CodeAction dotnet_diagnostic.RS0005.severity = none diff --git a/.vscode/launch.json b/.vscode/launch.json index 2b657e358e6e7..32446ed83fc9c 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,27 +1,54 @@ { - // Use IntelliSense to find out which attributes exist for C# debugging - // Use hover for the description of the existing attributes - // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md - "version": "0.2.0", - "configurations": [ - { - "name": ".NET Core Launch (console)", - "type": "coreclr", - "request": "launch", - "preLaunchTask": "build", - // If you have changed target frameworks, make sure to update the program path. - "program": "${workspaceFolder}/src/Compilers/CSharp/csc/bin/Debug/netcoreapp2.1/csc.dll", - "args": [], - "cwd": "${workspaceFolder}/src/Compilers/CSharp/csc", - // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console - "console": "internalConsole", - "stopAtEntry": false - }, - { - "name": ".NET Core Attach", - "type": "coreclr", - "request": "attach", - "processId": "${command:pickProcess}" - } - ] + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md + "version": "0.2.0", + "configurations": [ + { + "name": "Launch RunTests.dll", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/artifacts/bin/RunTests/Debug/netcoreapp3.1/RunTests.dll", + "args": ["--tfm", "netcoreapp3.1", "--sequential", "--html"], + "cwd": "${workspaceFolder}/artifacts/bin/RunTests", + "stopAtEntry": false, + "console": "internalConsole" + }, + { + "name": "Launch PrepareTests.dll", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/artifacts/bin/PrepareTests/Debug/net5.0/PrepareTests.dll", + "args": [ + "${workspaceFolder}", + "${workspaceFolder}/artifacts/testPayload" + ], + "cwd": "${workspaceFolder}/artifacts/bin/PrepareTests", + "stopAtEntry": false, + "console": "internalConsole" + }, + { + "name": ".NET Core Launch (console)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/src/Compilers/CSharp/csc/bin/Debug/netcoreapp2.1/csc.dll", + "args": [], + "cwd": "${workspaceFolder}/src/Compilers/CSharp/csc", + // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console + "console": "internalConsole", + "stopAtEntry": false + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach", + "processId": "${command:pickProcess}" + } + ] } \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 871242672e0e8..2e24069befded 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -37,7 +37,7 @@ "type": "shell", "args": [ "msbuild", - "-p:UseRoslynAnalyzers=false", + "-p:RunAnalyzersDuringBuild=false", "-p:GenerateFullPaths=true", "src/Compilers/CSharp/csc/csc.csproj" ], diff --git a/Compilers.sln b/Compilers.sln index f1f53fe9ddba3..0894f112eb8d9 100644 --- a/Compilers.sln +++ b/Compilers.sln @@ -301,10 +301,10 @@ Global {288089C5-8721-458E-BE3E-78990DAB5E2E}.Debug|Any CPU.Build.0 = Debug|x64 {288089C5-8721-458E-BE3E-78990DAB5E2E}.Release|Any CPU.ActiveCfg = Release|x64 {288089C5-8721-458E-BE3E-78990DAB5E2E}.Release|Any CPU.Build.0 = Release|x64 - {288089C5-8721-458E-BE3E-78990DAB5E2D}.Debug|Any CPU.ActiveCfg = Debug|x64 - {288089C5-8721-458E-BE3E-78990DAB5E2D}.Debug|Any CPU.Build.0 = Debug|x64 - {288089C5-8721-458E-BE3E-78990DAB5E2D}.Release|Any CPU.ActiveCfg = Release|x64 - {288089C5-8721-458E-BE3E-78990DAB5E2D}.Release|Any CPU.Build.0 = Release|x64 + {288089C5-8721-458E-BE3E-78990DAB5E2D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {288089C5-8721-458E-BE3E-78990DAB5E2D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {288089C5-8721-458E-BE3E-78990DAB5E2D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {288089C5-8721-458E-BE3E-78990DAB5E2D}.Release|Any CPU.Build.0 = Release|Any CPU {D0A79850-B32A-45E5-9FD5-D43CB345867A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D0A79850-B32A-45E5-9FD5-D43CB345867A}.Debug|Any CPU.Build.0 = Debug|Any CPU {D0A79850-B32A-45E5-9FD5-D43CB345867A}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/Roslyn.sln b/Roslyn.sln index 33657f3b8d9ea..187d89e076007 100644 --- a/Roslyn.sln +++ b/Roslyn.sln @@ -471,6 +471,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Edit EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Test.Utilities", "src\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj", "{5D94ED65-EFA3-44EB-A5DA-62E85BAC9DD6}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.TestSourceGenerator", "src\Workspaces\TestSourceGenerator\Microsoft.CodeAnalysis.TestSourceGenerator.csproj", "{21B50E65-D601-4D82-B98A-FFE6DE3B25DC}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.XunitHook", "src\EditorFeatures\XunitHook\Microsoft.CodeAnalysis.XunitHook.csproj", "{967A8F5E-7D18-436C-97ED-1DB303FE5DE0}" +EndProject Global GlobalSection(SharedMSBuildProjectFiles) = preSolution src\Analyzers\VisualBasic\CodeFixes\VisualBasicCodeFixes.projitems*{0141285d-8f6c-42c7-baf3-3c0ccd61c716}*SharedItemsImports = 5 @@ -662,10 +666,10 @@ Global {288089C5-8721-458E-BE3E-78990DAB5E2E}.Debug|Any CPU.Build.0 = Debug|x64 {288089C5-8721-458E-BE3E-78990DAB5E2E}.Release|Any CPU.ActiveCfg = Release|x64 {288089C5-8721-458E-BE3E-78990DAB5E2E}.Release|Any CPU.Build.0 = Release|x64 - {288089C5-8721-458E-BE3E-78990DAB5E2D}.Debug|Any CPU.ActiveCfg = Debug|x64 - {288089C5-8721-458E-BE3E-78990DAB5E2D}.Debug|Any CPU.Build.0 = Debug|x64 - {288089C5-8721-458E-BE3E-78990DAB5E2D}.Release|Any CPU.ActiveCfg = Release|x64 - {288089C5-8721-458E-BE3E-78990DAB5E2D}.Release|Any CPU.Build.0 = Release|x64 + {288089C5-8721-458E-BE3E-78990DAB5E2D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {288089C5-8721-458E-BE3E-78990DAB5E2D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {288089C5-8721-458E-BE3E-78990DAB5E2D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {288089C5-8721-458E-BE3E-78990DAB5E2D}.Release|Any CPU.Build.0 = Release|Any CPU {6AA96934-D6B7-4CC8-990D-DB6B9DD56E34}.Debug|Any CPU.ActiveCfg = Debug|x64 {6AA96934-D6B7-4CC8-990D-DB6B9DD56E34}.Debug|Any CPU.Build.0 = Debug|x64 {6AA96934-D6B7-4CC8-990D-DB6B9DD56E34}.Release|Any CPU.ActiveCfg = Release|x64 @@ -1230,6 +1234,14 @@ Global {5D94ED65-EFA3-44EB-A5DA-62E85BAC9DD6}.Debug|Any CPU.Build.0 = Debug|Any CPU {5D94ED65-EFA3-44EB-A5DA-62E85BAC9DD6}.Release|Any CPU.ActiveCfg = Release|Any CPU {5D94ED65-EFA3-44EB-A5DA-62E85BAC9DD6}.Release|Any CPU.Build.0 = Release|Any CPU + {21B50E65-D601-4D82-B98A-FFE6DE3B25DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {21B50E65-D601-4D82-B98A-FFE6DE3B25DC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {21B50E65-D601-4D82-B98A-FFE6DE3B25DC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {21B50E65-D601-4D82-B98A-FFE6DE3B25DC}.Release|Any CPU.Build.0 = Release|Any CPU + {967A8F5E-7D18-436C-97ED-1DB303FE5DE0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {967A8F5E-7D18-436C-97ED-1DB303FE5DE0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {967A8F5E-7D18-436C-97ED-1DB303FE5DE0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {967A8F5E-7D18-436C-97ED-1DB303FE5DE0}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -1447,6 +1459,8 @@ Global {9B25E472-DF94-4E24-9F5D-E487CE5A91FB} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} {67F44564-759B-4643-BD86-407B010B0B74} = {EE97CB90-33BB-4F3A-9B3D-69375DEC6AC6} {5D94ED65-EFA3-44EB-A5DA-62E85BAC9DD6} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} + {21B50E65-D601-4D82-B98A-FFE6DE3B25DC} = {55A62CFA-1155-46F1-ADF3-BEEE51B58AB5} + {967A8F5E-7D18-436C-97ED-1DB303FE5DE0} = {EE97CB90-33BB-4F3A-9B3D-69375DEC6AC6} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {604E6B91-7BC0-4126-AE07-D4D2FEFC3D29} diff --git a/azure-pipelines.yml b/azure-pipelines.yml index ce7ed7e0e2ccd..a51ee2abbb05c 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -112,8 +112,8 @@ jobs: - template: eng/pipelines/test-unix-job.yml parameters: - testRunName: 'Test OSX Debug' - jobName: Test_OSX_Debug + testRunName: 'Test macOS Debug' + jobName: Test_macOS_Debug buildJobName: Build_Unix_Debug testArtifactName: Transport_Artifacts_Unix_Debug configuration: Debug diff --git a/docs/contributing/Building, Debugging, and Testing on Windows.md b/docs/contributing/Building, Debugging, and Testing on Windows.md index b688f84dd2ae6..6c6dcbc7ae5d8 100644 --- a/docs/contributing/Building, Debugging, and Testing on Windows.md +++ b/docs/contributing/Building, Debugging, and Testing on Windows.md @@ -15,12 +15,12 @@ The minimal required version of .NET Framework is 4.7.2. ## Developing with Visual Studio 2019 -1. [Visual Studio 2019 16.8p2](https://visualstudio.microsoft.com/downloads/) +1. [Visual Studio 2019 16.8](https://visualstudio.microsoft.com/downloads/) - Ensure C#, VB, MSBuild, .NET Core and Visual Studio Extensibility are included in the selected work loads - - Ensure Visual Studio is on Version "16.8 Preview 3" or greater + - Ensure Visual Studio is on Version "16.8" or greater - Ensure "Use previews of the .NET Core SDK" is checked in Tools -> Options -> Environment -> Preview Features - Restart Visual Studio -1. [.NET Core SDK 5.0 Release Candidate 2](https://dotnet.microsoft.com/download/dotnet-core/5.0) [Windows x64 installer](https://dotnet.microsoft.com/download/dotnet/thank-you/sdk-5.0.100-rc.2-windows-x64-installer) +1. [.NET Core SDK 5.0](https://dotnet.microsoft.com/download/dotnet-core/5.0) [Windows x64 installer](https://dotnet.microsoft.com/download/dotnet/thank-you/sdk-5.0.100-windows-x64-installer) 1. [PowerShell 5.0 or newer](https://docs.microsoft.com/en-us/powershell/scripting/setup/installing-windows-powershell). If you are on Windows 10, you are fine; you'll only need to upgrade if you're on earlier versions of Windows. The download link is under the ["Upgrading existing Windows PowerShell"](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-windows-powershell?view=powershell-6#upgrading-existing-windows-powershell) heading. 1. Run Restore.cmd 1. Open Roslyn.sln diff --git a/docs/ide/api-designs/Workspace and Source Generated Documents.md b/docs/ide/api-designs/Workspace and Source Generated Documents.md new file mode 100644 index 0000000000000..d23ee4b20b076 --- /dev/null +++ b/docs/ide/api-designs/Workspace and Source Generated Documents.md @@ -0,0 +1,73 @@ +# Source Generator / Workspace API Proposal + +In Visual Studio 16.8, we shipped only limited source generator support in the Workspace APIs; any caller requesting a Compilation would get a Compilation that contained the correct generated SyntaxTrees, but there was no way to know where the trees came from, nor interact with the generated documents in any other way. This proposal describes how we are going to shore these APIs up. + +## SourceGeneratedDocument Type + +A new type will be introduced, `SourceGeneratedDocument`, that inherits from `Document`. `GetSyntaxTreeAsync`, `GetSyntaxRootAsync`, and `GetTextAsync` (and the corresponding synchronous and Try methods) will return the generated text or trees. The trees will be the same instances as would be found in the `Compilation.SyntaxTrees`. + +The `Id` of the `Document` will be generated dynamically by the workspace. As much as possible, the Id will be persistent between snapshots as much as is practical. When a generator produces a document, it provides a "hint name" which is intended to be used for the IDE to allow for 'permanence' between runs. `DocumentId`s are defined by a GUID in the implementation, so to ensure the DocumentId can be stable, we will generate the GUID as a hash of the hint name, the generator name, and any other pertinent information. Although the implementation may do extra caching behind the scenes where it won't have to recompute hashes in this way, this will ensure the `DocumentId` stays stable even if the caches fail to avoid any surprises. + +`SourceGeneratedDocument` will have some additional members: + +1. `HintName`: the exact hint name that was provided by the generator. +1. `SourceGenerator`: the ISourceGenerator instance that produced this document. + +For now, any _mutation_ of a SourceGeneratedDocument will not be supported. Calls to the following members will throw `NotSupportedException`: + +1. `WithText` +2. `WithSyntaxRoot` +3. `WithName` +4. `WithFolders` +5. `WithFilePath` + +Down the road, I hope that we might offer an extension point for a source generator to participate in WithText and WithSyntaxRoot. In many cases the generated source may contain expressions that are verbatim C# (think a .cshtml file having a C# section), and so we could have WithText or WithSyntaxRoot apply the resulting edit back to the document that the verbatim C# came from. The design of this is out of scope here. + +## APIs on `Project` + +### Existing API: `Documents` + +Note the Documents collection will _not_ change, and will only include regular documents. It cannot include source generated documents because since it is a property access, there is no opportunity to make this async, nor have any way to express cancellation. Since a generator could produce any number of documents, there's simply no way to make this answer quickly without fundamentally taking a different approach to the API. + +### New API: `ImmutableArray GetSourceGeneratedDocumentsAsync(CancelationToken)` + +This will run generators if they have not already ran, and then return a `SourceGeneratedDocument` for each generated document. + +The implementation of this will run `GetCompilationAsync` if the documents have not been generated; if the Compilation had already been generated, we would have cached the generated document information and so this would be cheap. We will hold onto the list of documents strongly (the tree will be a recoverable tree), so even if the `Compilation` is GC'ed we won't have to recompute this part a second time. + +### New API: `SourceGeneratedDocument? GetSourceGeneratedDocumentAsync(DocumentId, CancellationToken)` + +Fetches a single document by ID; equivalent to calling the API and filtering down to the right document. + +### Existing API: `GetDocument(SyntaxTree)` + +No changes, it will potentially return a `SourceGeneratedDocument` now. Callers _may_ have to check whether it's a generated document before they try to offer a fix or refactoring on the document. + +This API is the hardest API to figure out what to do in this entire spec. If it doesn't return generated documents, many features would break, since it's very common to assume that if a syntax tree exists in a `Compilation`, that there must be a `Document` that matches it. However, some features might _not_ want to see a generated document returned here because then they're going to try to modify that, and that won't make sense either. An audit of the code fixes in Roslyn discovered that for many of the places that would need an update to _ignore_ a generated document would also need an update to deal with the null reference that would come back from `GetDocument`. + +The other odd thing here is whether this function needs to be asynchronous or not. The current belief is no, because the only way you can have gotten a SyntaxTree to pass to it from the same `Solution` is either from: + +1. The `Compilation` or a symbol that came from it, which means generators have ran. +2. You inspected some `SourceGeneratedDocument` and got it's tree, which means that generator has already ran. + +The only surprise you might run into is taking a `SyntaxTree` from an earlier `Solution`, passing it to a newer `Solution`, and getting a document that no longer exists because in the later `Solution` is no longer generating this document. However, passing a `SyntaxTree` between snapshots like that is questionable in the first place. Any code that is working with multiple snapshots and knew that a Document between the snapshots had the same tree could have done something like this, but that code is potentially broken _anyways_ with source generators since now one tree can change due to another tree changing. + +## APIs on `Workspace` + +### Existing APIs: `OpenDocument(DocumentId)`/`CloseDocument(DocumentId)` + +This API today is used by any feature that wants to tell the host to open a file. This will accept the DocumentId of a generated document and work properly. + +### Existing APIs: `IsDocumentOpen(DocumentId)` / `GetOpenDocumentIds(...)` +These will behave no differently than before. + +### Existing APIs: `OnDocumentOpened`/`OnDocumentClosed` +These APIs today associate a Workspace and a SourceTextContainer. Besides allowing APIs like `GetOpenDocumentInCurrentContextWithChanges` to work, this also ensures that a change to the text buffer updates the Workspace automatically. For generated documents, it will wire up the first part (assocating the container) but will not update the Workspace contents when the buffer changes. This is because the updates flow in the _other_ direction, and for now that updating is being managed by a Visual Studio-layer component. Further refactoring may move the core updating into the Workspace layer directly, but not for now. + +## APIs for Fetching Documents + +### Existing API: `GetOpenDocumentInCurrentContextWithChanges(ITextSnapshot)` + +Because we want source generated documents to have the same IDE affordances as any other open file, this API will still work but return a `SourceGeneratedDocument` in that case. Some special handling is required though due to asynchrony. If a user has a generated document open, we may have an async process running in the background that may be trying to refresh this open generated document. The call to `GetOpenDocumentInCurrentContextWithChanges` however will "freeze" the generated document to match the `ITextSnapshot`, so any calls to `GetSourceGeneratedDocumentsAsync()` will return that exact same text, even if that content is out of sync with what would be generated given that project state. + +This does mean that in this case, the contents of this document won't match if you compared the document to Workspace.CurrentSolution, got the generated document by ID, and then asked for it's text. This however is OK: that can _always_ be the case for any caller to `GetOpenDocumentInCurrentContextWithChanges` since it always forks to match the `ITextSnapshot`. We're just making the window where this can happen to be bigger than usual. \ No newline at end of file diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 2e0500c85c62f..b362f701ae504 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -3,13 +3,13 @@ - + https://github.com/dotnet/arcade - 4f384ab6a49fc642aec2acc4bcc938172a0744d1 + 1ceac96c54fcf33eb745649c4e7b8d7507a9b730 - + https://github.com/dotnet/roslyn - a76ac7f4039ac1e240f7807fe8a350a2ba5b9ad7 + 2d0cd2ab2d6bf2ae05d57ffb1fd8abe8c1756086 diff --git a/eng/Versions.props b/eng/Versions.props index 6209790a67834..af94377fa9f92 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -8,7 +8,7 @@ 3 9 0 - 2 + 3 $(MajorVersion).$(MinorVersion).$(PatchVersion) 3.3.2-beta1.20528.2 5.0.0-rc2.20453.1 - 3.7.0 1.0.1-beta1.20407.3 - 3.8.0-2.20414.4 + 3.8.0 16.8.181 5.0.0-alpha1.19409.1 16.9.43 16.8.30406.65-pre + + 3.8.0 12.0.2 2.6.104 - 5.0.0-preview.8.20407.11 - 5.0.0-preview.8.20407.11 + 5.0.0 + 5.0.0 1.1.1 diff --git a/eng/build-utils.ps1 b/eng/build-utils.ps1 index 73016ef81b35f..964b074bc614c 100644 --- a/eng/build-utils.ps1 +++ b/eng/build-utils.ps1 @@ -283,7 +283,7 @@ function Run-MSBuild([string]$projectFilePath, [string]$buildArgs = "", [string] } if ($runAnalyzers) { - $args += " /p:UseRoslynAnalyzers=true" + $args += " /p:RunAnalyzersDuringBuild=true" } if ($binaryLog) { @@ -331,7 +331,7 @@ function Make-BootstrapBuild([switch]$force32 = $false) { $projectPath = "src\NuGet\$packageName\$packageName.Package.csproj" $force32Flag = if ($force32) { " /p:BOOTSTRAP32=true" } else { "" } - Run-MSBuild $projectPath "/restore /t:Pack /p:RoslynEnforceCodeStyle=false /p:UseRoslynAnalyzers=false /p:DotNetUseShippingVersions=true /p:InitialDefineConstants=BOOTSTRAP /p:PackageOutputPath=`"$dir`" /p:EnableNgenOptimization=false /p:PublishWindowsPdb=false $force32Flag" -logFileName "Bootstrap" -configuration $bootstrapConfiguration -runAnalyzers + Run-MSBuild $projectPath "/restore /t:Pack /p:RoslynEnforceCodeStyle=false /p:RunAnalyzersDuringBuild=false /p:DotNetUseShippingVersions=true /p:InitialDefineConstants=BOOTSTRAP /p:PackageOutputPath=`"$dir`" /p:EnableNgenOptimization=false /p:PublishWindowsPdb=false $force32Flag" -logFileName "Bootstrap" -configuration $bootstrapConfiguration -runAnalyzers $packageFile = Get-ChildItem -Path $dir -Filter "$packageName.*.nupkg" Unzip "$dir\$packageFile" $dir diff --git a/eng/build.ps1 b/eng/build.ps1 index b19a31acfbdfa..8517b7374808b 100644 --- a/eng/build.ps1 +++ b/eng/build.ps1 @@ -216,8 +216,6 @@ function BuildSolution() { $projects = Join-Path $RepoRoot $solution $toolsetBuildProj = InitializeToolset - $testTargetFrameworks = if ($testCoreClr) { 'net5.0%3Bnetcoreapp3.1' } else { "" } - $ibcDropName = GetIbcDropName # Do not set this property to true explicitly, since that would override values set in projects. @@ -241,16 +239,14 @@ function BuildSolution() { /p:RepoRoot=$RepoRoot ` /p:Restore=$restore ` /p:Build=$build ` - /p:Test=$testCoreClr ` /p:Rebuild=$rebuild ` /p:Pack=$pack ` /p:Sign=$sign ` /p:Publish=$publish ` /p:ContinuousIntegrationBuild=$ci ` /p:OfficialBuildId=$officialBuildId ` - /p:UseRoslynAnalyzers=$runAnalyzers ` + /p:RunAnalyzersDuringBuild=$runAnalyzers ` /p:BootstrapBuildPath=$bootstrapDir ` - /p:TestTargetFrameworks=$testTargetFrameworks ` /p:TreatWarningsAsErrors=$warnAsError ` /p:EnableNgenOptimization=$applyOptimizationData ` /p:IbcOptimizationDataDir=$ibcDir ` @@ -305,7 +301,7 @@ function GetIbcDropName() { # Bring in the ibc tools $packagePath = Join-Path (Get-PackageDir "Microsoft.DevDiv.Optimization.Data.PowerShell") "lib\net461" Import-Module (Join-Path $packagePath "Optimization.Data.PowerShell.dll") - + # Find the matching drop $branch = GetIbcSourceBranchName Write-Host "Optimization data branch name is '$branch'." @@ -316,7 +312,7 @@ function GetIbcDropName() { } # Core function for running our unit / integration tests tests -function TestUsingOptimizedRunner() { +function TestUsingRunTests() { # Tests need to locate .NET Core SDK $dotnet = InitializeDotNetCli @@ -336,8 +332,7 @@ function TestUsingOptimizedRunner() { } $testResultsDir = Join-Path $ArtifactsDir "TestResults\$configuration" - $binDir = Join-Path $ArtifactsDir "bin" - $runTests = GetProjectOutputBinary "RunTests.exe" + $runTests = GetProjectOutputBinary "RunTests.dll" -tfm "netcoreapp3.1" if (!(Test-Path $runTests)) { Write-Host "Test runner not found: '$runTests'. Run Build.cmd first." -ForegroundColor Red @@ -348,53 +343,33 @@ function TestUsingOptimizedRunner() { $args += " --dotnet `"$dotnetExe`"" $args += " --out `"$testResultsDir`"" $args += " --logs `"$LogDir`"" - $args += " --tfm net472" - - if ($testDesktop -or $testIOperation) { - if ($test32) { - $dlls = Get-ChildItem -Recurse -Include "*.UnitTests.dll" $binDir - } else { - $dlls = Get-ChildItem -Recurse -Include "*.UnitTests.dll" -Exclude "*InteractiveHost*" $binDir - } - } elseif ($testVsi) { - # Since they require Visual Studio to be installed, ensure that the MSBuildWorkspace tests run along with our VS - # integration tests in CI. - if ($ci) { - $dlls += @(Get-Item (GetProjectOutputBinary "Microsoft.CodeAnalysis.Workspaces.MSBuild.UnitTests.dll")) - $args += " --retry" - } + $args += " --configuration $configuration" - $dlls += @(Get-ChildItem -Recurse -Include "*.IntegrationTests.dll" $binDir) - $args += " --testvsi" - } else { - $dlls = Get-ChildItem -Recurse -Include "*.IntegrationTests.dll" $binDir - $args += " --trait:Feature=NetCore" + if ($testCoreClr) { + $args += " --tfm net5.0" + $args += " --tfm netcoreapp3.1" + $args += " --include '\.UnitTests'" + $args += " --timeout 90" } + elseif ($testDesktop -or $testIOperation) { + $args += " --tfm net472" + $args += " --include '\.UnitTests'" + $args += " --timeout 90" - # Exclude out the multi-targetted netcore app projects - $dlls = $dlls | ?{ -not ($_.FullName -match ".*netcoreapp.*") } - $dlls = $dlls | ?{ -not ($_.FullName -match ".*net5.0.*") } - - # Exclude out the ref assemblies - $dlls = $dlls | ?{ -not ($_.FullName -match ".*\\ref\\.*") } - $dlls = $dlls | ?{ -not ($_.FullName -match ".*/ref/.*") } + if (-not $test32) { + $args += " --exclude '\.InteractiveHost'" + } - if ($configuration -eq 'Debug') { - $excludedConfiguration = 'Release' - } else { - $excludedConfiguration = 'Debug' + } elseif ($testVsi) { + $args += " --timeout 110" + $args += " --tfm net472" + $args += " --retry" + $args += " --sequential" + $args += " --include '\.IntegrationTests'" + $args += " --include 'Microsoft.CodeAnalysis.Workspaces.MSBuild.UnitTests'" } - $dlls = $dlls | ?{ -not (($_.FullName -match ".*\\$excludedConfiguration\\.*") -or ($_.FullName -match ".*/$excludedConfiguration/.*")) } - - if ($ci) { - if ($testVsi) { - $args += " --timeout 110" - } else { - $args += " --timeout 90" - } - } - else { + if (-not $ci -and -not $testVsi) { $args += " --html" } @@ -415,12 +390,9 @@ function TestUsingOptimizedRunner() { $args += " --sequential" } - foreach ($dll in $dlls) { - $args += " $dll" - } - try { - Exec-Console $runTests $args + Write-Host "$runTests $args" + Exec-Console $dotnetExe "$runTests $args" } finally { Get-Process "xunit*" -ErrorAction SilentlyContinue | Stop-Process if ($testIOperation) { @@ -452,10 +424,10 @@ function EnablePreviewSdks() { # Deploy our core VSIX libraries to Visual Studio via the Roslyn VSIX tool. This is an alternative to # deploying at build time. -function Deploy-VsixViaTool() { +function Deploy-VsixViaTool() { $vsixDir = Get-PackageDir "RoslynTools.VSIXExpInstaller" $vsixExe = Join-Path $vsixDir "tools\VsixExpInstaller.exe" - + $vsInfo = LocateVisualStudio if ($vsInfo -eq $null) { throw "Unable to locate required Visual Studio installation" @@ -616,7 +588,7 @@ try { Prepare-TempDir EnablePreviewSdks if ($testVsi) { - Setup-IntegrationTestRun + Setup-IntegrationTestRun } $global:_DotNetInstallDir = Join-Path $RepoRoot ".dotnet" @@ -641,14 +613,14 @@ try { throw $_ } - if ($restore -or $build -or $rebuild -or $pack -or $sign -or $publish -or $testCoreClr) { + if ($restore -or $build -or $rebuild -or $pack -or $sign -or $publish) { BuildSolution } try { - if ($testDesktop -or $testVsi -or $testIOperation) { - TestUsingOptimizedRunner + if ($testDesktop -or $testVsi -or $testIOperation -or $testCoreClr) { + TestUsingRunTests } } catch diff --git a/eng/build.sh b/eng/build.sh index f28f8972d0d0a..496005b7a803f 100755 --- a/eng/build.sh +++ b/eng/build.sh @@ -6,7 +6,7 @@ set -u # Stop script if subcommand fails -set -e +set -e usage() { @@ -23,7 +23,7 @@ usage() echo " --publish Publish build artifacts" echo " --help Print help and exit" echo "" - echo "Test actions:" + echo "Test actions:" echo " --testCoreClr Run unit tests on .NET Core (short: --test, -t)" echo " --testMono Run unit tests on Mono" echo " --testIOperation Run unit tests with the IOperation test hook" @@ -70,7 +70,6 @@ run_analyzers=false prepare_machine=false warn_as_error=false properties="" -disable_parallel_restore=false source_build=false docker=false @@ -220,24 +219,19 @@ function BuildSolution { InitializeToolset local toolset_build_proj=$_InitializeToolset - + local bl="" if [[ "$binary_log" = true ]]; then bl="/bl:\"$log_dir/Build.binlog\"" fi - - local projects="$repo_root/$solution" - - # https://github.com/dotnet/roslyn/issues/23736 - UNAME="$(uname)" - if [[ "$UNAME" == "Darwin" ]]; then - run_analyzers=false - fi + local projects="$repo_root/$solution" + + UNAME="$(uname)" # NuGet often exceeds the limit of open files on Mac and Linux # https://github.com/NuGet/Home/issues/2163 if [[ "$UNAME" == "Darwin" || "$UNAME" == "Linux" ]]; then - disable_parallel_restore=true + ulimit -n 6500 fi if [[ "$test_ioperation" == true ]]; then @@ -264,10 +258,6 @@ function BuildSolution { test_runtime="/p:TestRuntime=Mono" mono_tool="/p:MonoTool=\"$mono_path\"" test_runtime_args="--debug" - elif [[ "$test_core_clr" == true ]]; then - test=true - test_runtime="/p:TestRuntime=Core /p:TestTargetFrameworks=net5.0%3Bnetcoreapp3.1 /p:TestRunnerAdditionalArguments=-verbose" - mono_tool="" fi # Setting /p:TreatWarningsAsErrors=true is a workaround for https://github.com/Microsoft/msbuild/issues/3062. @@ -285,11 +275,10 @@ function BuildSolution { /p:Test=$test \ /p:Pack=$pack \ /p:Publish=$publish \ - /p:UseRoslynAnalyzers=$run_analyzers \ + /p:RunAnalyzersDuringBuild=$run_analyzers \ /p:BootstrapBuildPath="$bootstrap_dir" \ /p:ContinuousIntegrationBuild=$ci \ /p:TreatWarningsAsErrors=true \ - /p:RestoreDisableParallel=$disable_parallel_restore \ /p:TestRuntimeAdditionalArguments=$test_runtime_args \ /p:DotNetBuildFromSource=$source_build \ $test_runtime \ @@ -297,7 +286,11 @@ function BuildSolution { $properties } -InitializeDotNetCli $restore +install=false +if [[ "$restore" == true || "$test_core_clr" == true ]]; then + install=true +fi +InitializeDotNetCli $install if [[ "$restore" == true ]]; then dotnet tool restore fi @@ -308,5 +301,16 @@ if [[ "$bootstrap" == true ]]; then bootstrap_dir=$_MakeBootstrapBuild fi -BuildSolution +if [[ "$restore" == true || "$build" == true || "$rebuild" == true || "$test_mono" == true ]]; then + BuildSolution +fi + +if [[ "$test_core_clr" == true ]]; then + if [[ "$ci" == true ]]; then + runtests_args="" + else + runtests_args="--html" + fi + dotnet exec "$scriptroot/../artifacts/bin/RunTests/${configuration}/netcoreapp3.1/RunTests.dll" --tfm netcoreapp3.1 --tfm net5.0 --configuration ${configuration} --dotnet ${_InitializeDotNetCli}/dotnet $runtests_args +fi ExitWithExitCode 0 diff --git a/eng/common/SetupNugetSources.ps1 b/eng/common/SetupNugetSources.ps1 index 6d88a1904ba4f..83218ad7e72ce 100644 --- a/eng/common/SetupNugetSources.ps1 +++ b/eng/common/SetupNugetSources.ps1 @@ -99,8 +99,9 @@ function InsertMaestroPrivateFeedCredentials($Sources, $Creds, $Username, $Passw function EnablePrivatePackageSources($DisabledPackageSources) { $maestroPrivateSources = $DisabledPackageSources.SelectNodes("add[contains(@key,'darc-int')]") ForEach ($DisabledPackageSource in $maestroPrivateSources) { - Write-Host "`tEnsuring private source '$($DisabledPackageSource.key)' is enabled" - $DisabledPackageSource.SetAttribute("value", "false") + Write-Host "`tEnsuring private source '$($DisabledPackageSource.key)' is enabled by deleting it from disabledPackageSource" + # Due to https://github.com/NuGet/Home/issues/10291, we must actually remove the disabled entries + $DisabledPackageSources.RemoveChild($DisabledPackageSource) } } diff --git a/eng/common/SetupNugetSources.sh b/eng/common/SetupNugetSources.sh index 00e8f45b91f24..751863d500628 100644 --- a/eng/common/SetupNugetSources.sh +++ b/eng/common/SetupNugetSources.sh @@ -159,8 +159,8 @@ if [ "$?" == "0" ]; then for DisabledSourceName in ${DisabledDarcIntSources[@]} ; do if [[ $DisabledSourceName == darc-int* ]] then - OldDisableValue="add key=\"$DisabledSourceName\" value=\"true\"" - NewDisableValue="add key=\"$DisabledSourceName\" value=\"false\"" + OldDisableValue="" + NewDisableValue="" sed -i.bak "s|$OldDisableValue|$NewDisableValue|" $ConfigFile echo "Neutralized disablePackageSources entry for '$DisabledSourceName'" fi diff --git a/eng/common/templates/post-build/post-build.yml b/eng/common/templates/post-build/post-build.yml index 2d51c1cdbf631..8ad0f9f66c25f 100644 --- a/eng/common/templates/post-build/post-build.yml +++ b/eng/common/templates/post-build/post-build.yml @@ -367,6 +367,18 @@ stages: shippingFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json' symbolsFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools-symbols/nuget/v3/index.json' +- template: \eng\common\templates\post-build\channels\generic-public-channel.yml + parameters: + artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} + publishInstallersAndChecksums: ${{ parameters.publishInstallersAndChecksums }} + symbolPublishingAdditionalParameters: ${{ parameters.symbolPublishingAdditionalParameters }} + stageName: 'VS16_9_Publishing' + channelName: 'VS 16.9' + channelId: 1473 + transportFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools-transport/nuget/v3/index.json' + shippingFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json' + symbolsFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools-symbols/nuget/v3/index.json' + - template: \eng\common\templates\post-build\channels\generic-public-channel.yml parameters: artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} diff --git a/eng/common/tools.ps1 b/eng/common/tools.ps1 index d7c57081718ea..f50507a06c1b5 100644 --- a/eng/common/tools.ps1 +++ b/eng/common/tools.ps1 @@ -384,11 +384,9 @@ function LocateVisualStudio([object]$vsRequirements = $null){ } } - $rawInfo =& $vsWhereExe $args - $vsInfo = $rawInfo | ConvertFrom-Json + $vsInfo =& $vsWhereExe $args | ConvertFrom-Json if ($lastExitCode -ne 0) { - Write-Host $rawInfo return $null } diff --git a/eng/config/OptProf.json b/eng/config/OptProf.json index cd83784def19c..d2b2cbfd25fbb 100644 --- a/eng/config/OptProf.json +++ b/eng/config/OptProf.json @@ -255,7 +255,7 @@ }, { "filename": "/Microsoft.CodeAnalysis.VisualBasic.dll", - "testCases":[ "VSPE.OptProfTests.vs_asl_vb_scenario", "VSPE.OptProfTests.vs_perf_designtime_ide_searchtest", "VSPE.OptProfTests.DDRIT_RPS_ManagedLangs_Typing", "VSPE.OptProfTests.DDRIT_RPS_ManagedLangs_Debug", "VSPE.OptProfTests.vs_perf_designtime_solution_build_vb_australiangovernment", "VSPE.OptProfTests.vs_perf_designtime_solution_loadclose_vb_australiangovernment" ] + "testCases":[ "VSPE.OptProfTests.vs_asl_vb_scenario", "VSPE.OptProfTests.vs_perf_designtime_ide_searchtest", "VSPE.OptProfTests.DDRIT_RPS_ManagedLangs_Debug", "VSPE.OptProfTests.vs_perf_designtime_solution_build_vb_australiangovernment", "VSPE.OptProfTests.vs_perf_designtime_solution_loadclose_vb_australiangovernment" ] }, { "filename": "/Microsoft.CodeAnalysis.EditorFeatures.Wpf.dll", @@ -400,7 +400,7 @@ }, { "filename": "/Contents/MSBuild/Current/Bin/Roslyn/Microsoft.CodeAnalysis.VisualBasic.dll", - "testCases":[ "VSPE.OptProfTests.vs_perf_designtime_solution_build_vb_australiangovernment", "VSPE.OptProfTests.vs_perf_designtime_ide_searchtest", "VSPE.OptProfTests.DDRIT_RPS_ManagedLangs_Typing", "VSPE.OptProfTests.DDRIT_RPS_ManagedLangs_Debug" ] + "testCases":[ "VSPE.OptProfTests.vs_perf_designtime_solution_build_vb_australiangovernment", "VSPE.OptProfTests.vs_perf_designtime_ide_searchtest", "VSPE.OptProfTests.DDRIT_RPS_ManagedLangs_Debug" ] }, { "filename": "/Contents/MSBuild/Current/Bin/Roslyn/System.Memory.dll", diff --git a/eng/config/PublishData.json b/eng/config/PublishData.json index bdc2f0ab125ed..c323320f13242 100644 --- a/eng/config/PublishData.json +++ b/eng/config/PublishData.json @@ -207,15 +207,15 @@ "nugetKind": [ "Shipping", "NonShipping" ], "version": "3.9.*", "packageFeeds": "default", - "channels": [ "dev16.9p1" ], + "channels": [ "dev16.9p2" ], "vsBranch": "rel/d16.9", "vsMajorVersion": 16 }, "master-vs-deps": { "nugetKind": ["Shipping", "NonShipping"], - "version": "3.8.*", + "version": "3.9.*", "packageFeeds": "default", - "channels": [ "dev16.9", "dev16.9p2" ], + "channels": [ "dev16.9", "dev16.9p3" ], "vsBranch": "main", "vsMajorVersion": 16 }, diff --git a/eng/config/globalconfigs/Common.globalconfig b/eng/config/globalconfigs/Common.globalconfig index 667d755443434..073bdb851d2e3 100644 --- a/eng/config/globalconfigs/Common.globalconfig +++ b/eng/config/globalconfigs/Common.globalconfig @@ -42,6 +42,8 @@ dotnet_diagnostic.RS0024.severity = error dotnet_diagnostic.RS0025.severity = error dotnet_diagnostic.RS0026.severity = error dotnet_diagnostic.RS0027.severity = error +# RS0037: PublicAPI.txt is missing '#nullable enable' +dotnet_diagnostic.RS0037.severity = none # RS0040: Defaultable types should have defaultable fields dotnet_diagnostic.RS0040.severity = none # RS0046: Avoid the 'Opt' suffix in nullable-enabled code (too noisy right now) diff --git a/eng/generate-compiler-code.ps1 b/eng/generate-compiler-code.ps1 index 8bc39ba54e949..377e876201283 100644 --- a/eng/generate-compiler-code.ps1 +++ b/eng/generate-compiler-code.ps1 @@ -11,7 +11,7 @@ $ErrorActionPreference="Stop" function Run-Tool($projectFilePath, $toolArgs) { $toolName = Split-Path -leaf $projectFilePath Write-Host "Running $toolName $toolArgs" - Exec-Console $dotnet "run -p $projectFilePath $toolArgs" + Exec-Console $dotnet "run -p $projectFilePath --framework netcoreapp3.1 $toolArgs" } function Run-LanguageCore($language, $languageSuffix, $languageDir, $syntaxProject, $errorFactsProject, $generatedDir, $generatedTestDir) { @@ -25,7 +25,11 @@ function Run-LanguageCore($language, $languageSuffix, $languageDir, $syntaxProje Create-Directory $generatedDir Create-Directory $generatedTestDir - Run-Tool $syntaxProject "`"$syntaxFilePath`" `"$generatedDir`"" + + # The C# syntax is now generated by a source generator + if ($language -ne "CSharp") { + Run-Tool $syntaxProject "`"$syntaxFilePath`" `"$generatedDir`"" + } Run-Tool $syntaxProject "`"$syntaxFilePath`" `"$generatedDir`" /grammar" Run-Tool $syntaxProject "`"$syntaxFilePath`" `"$syntaxTestFilePath`" /test" Run-Tool $boundTreeGenProject "$language `"$boundFilePath`" `"$boundGeneratedFilePath`"" diff --git a/eng/pipelines/build-unix-job.yml b/eng/pipelines/build-unix-job.yml index 6a26e8017f869..45c6ee2483267 100644 --- a/eng/pipelines/build-unix-job.yml +++ b/eng/pipelines/build-unix-job.yml @@ -34,10 +34,13 @@ jobs: - script: ./eng/build.sh --ci --build --publish --pack --prepareMachine --binaryLog --configuration ${{ parameters.configuration }} displayName: Build + - script: ./eng/prepare-tests.sh + displayName: Prepare Test Payload + - task: PublishPipelineArtifact@1 - displayName: 'Publish Build' + displayName: Publish Test Payload inputs: - targetPath: '$(Build.SourcesDirectory)/artifacts/bin' + targetPath: '$(Build.SourcesDirectory)/artifacts/testPayload' artifactName: ${{ parameters.testArtifactName }} - template: publish-logs.yml diff --git a/eng/pipelines/test-unix-job.yml b/eng/pipelines/test-unix-job.yml index 43d8622b97490..60acbceb9d586 100644 --- a/eng/pipelines/test-unix-job.yml +++ b/eng/pipelines/test-unix-job.yml @@ -36,20 +36,29 @@ jobs: vmImage: ${{ parameters.vmImageName }} timeoutInMinutes: 40 steps: - - script: ./eng/build.sh --ci --restore --prepareMachine --binaryLog --configuration ${{ parameters.configuration }} - displayName: Restore + - checkout: none - task: DownloadPipelineArtifact@2 + displayName: Download Test Payload inputs: artifact: ${{ parameters.testArtifactName }} - path: '$(Build.SourcesDirectory)/artifacts/bin' + path: '$(Build.SourcesDirectory)' + + - task: PowerShell@2 + displayName: Rehydrate Unit Tests Environment + inputs: + filePath: rehydrate.ps1 + pwsh: true # Work around for files not maintaining permissions after pipeline download # https://github.com/microsoft/azure-pipelines-tasks/issues/6364 - - bash: find . -name ilasm | xargs chmod 755 - workingDirectory: '$(Build.SourcesDirectory)/artifacts/bin' + - bash: | + find artifacts/bin -name ilasm | xargs chmod 755 + chmod 755 eng/build.sh + workingDirectory: '$(Build.SourcesDirectory)' + displayName: Fix executable permissions in pipeline artifact - - script: ./eng/build.sh --ci --binaryLog --configuration ${{ parameters.configuration }} ${{ parameters.testArguments }} + - script: ./eng/build.sh --ci --configuration ${{ parameters.configuration }} ${{ parameters.testArguments }} displayName: Test - task: PublishTestResults@2 @@ -64,4 +73,4 @@ jobs: - template: publish-logs.yml parameters: configuration: ${{ parameters.configuration }} - jobName: ${{ parameters.jobName }} \ No newline at end of file + jobName: ${{ parameters.jobName }} diff --git a/eng/pipelines/test-windows-job.yml b/eng/pipelines/test-windows-job.yml index b0461be7ed0f9..8bc92b03397b0 100644 --- a/eng/pipelines/test-windows-job.yml +++ b/eng/pipelines/test-windows-job.yml @@ -30,17 +30,21 @@ jobs: queue: ${{ parameters.queueName }} timeoutInMinutes: 120 steps: + - checkout: none + - task: DownloadPipelineArtifact@2 + displayName: Download Test Payload inputs: artifact: ${{ parameters.testArtifactName }} - path: '$(Build.SourcesDirectory)\artifacts\bin' + path: '$(Build.SourcesDirectory)' - - task: PowerShell@2 + - task: PowerShell@2 displayName: Rehydrate Unit Tests Environment inputs: - filePath: eng/rehydrate-tests.ps1 + filePath: rehydrate.ps1 + pwsh: true - - task: PowerShell@2 + - task: PowerShell@2 displayName: Run Unit Tests inputs: filePath: eng/build.ps1 @@ -58,4 +62,4 @@ jobs: - template: publish-logs.yml parameters: configuration: ${{ parameters.configuration }} - jobName: ${{ parameters.jobName }} \ No newline at end of file + jobName: ${{ parameters.jobName }} diff --git a/eng/prepare-tests.ps1 b/eng/prepare-tests.ps1 index e9bd213b5f1c6..d94b0f7de2293 100644 --- a/eng/prepare-tests.ps1 +++ b/eng/prepare-tests.ps1 @@ -9,7 +9,9 @@ try { Push-Location $RepoRoot $dotnet = Ensure-DotnetSdk - Exec-Console $dotnet "run --project src\Tools\PrepareTests\PrepareTests.csproj $RepoRoot\artifacts\bin $RepoRoot\artifacts\testPayload" + # permissions issues make this a pain to do in PrepareTests itself. + Remove-Item -Recurse -Force "$RepoRoot\artifacts\testPayload" -ErrorAction SilentlyContinue + Exec-Console $dotnet "run --project src\Tools\PrepareTests\PrepareTests.csproj $RepoRoot $RepoRoot\artifacts\testPayload" exit 0 } catch { diff --git a/eng/prepare-tests.sh b/eng/prepare-tests.sh new file mode 100755 index 0000000000000..4d3d32cd0fa21 --- /dev/null +++ b/eng/prepare-tests.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# Copyright (c) .NET Foundation and contributors. All rights reserved. +# Licensed under the MIT license. See LICENSE file in the project root for full license information. + +# Stop script if unbound variable found (use ${var:-} if intentional) +set -u + +# Stop script if subcommand fails +set -e + +source="${BASH_SOURCE[0]}" + +# resolve $source until the file is no longer a symlink +while [[ -h "$source" ]]; do + scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" + source="$(readlink "$source")" + # if $source was a relative symlink, we need to resolve it relative to the path where the + # symlink file was located + [[ $source != /* ]] && source="$scriptroot/$source" +done +scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" + +# Import Arcade functions +. "$scriptroot/common/tools.sh" + +InitializeDotNetCli true + +# permissions issues make this a pain to do in PrepareTests itself. +rm -rf "$repo_root/artifacts/testPayload" + +dotnet run --project src/Tools/PrepareTests/PrepareTests.csproj "$repo_root" "$repo_root/artifacts/testPayload" diff --git a/eng/rehydrate-tests.ps1 b/eng/rehydrate-tests.ps1 deleted file mode 100644 index 33206d752116e..0000000000000 --- a/eng/rehydrate-tests.ps1 +++ /dev/null @@ -1,24 +0,0 @@ -[CmdletBinding(PositionalBinding=$false)] -param () - -Set-StrictMode -version 2.0 -$ErrorActionPreference="Stop" - -try { - . (Join-Path $PSScriptRoot "build-utils.ps1") - Push-Location $RepoRoot - - Push-Location artifacts\bin - & .\rehydrate.cmd - Pop-Location - - Ensure-DotNetSdk - & eng\build.ps1 -restore -} -catch { - Write-Host $_ - exit 1 -} -finally { - Pop-Location -} diff --git a/eng/targets/Imports.targets b/eng/targets/Imports.targets index c3e7b3e81c43c..15b067deb0476 100644 --- a/eng/targets/Imports.targets +++ b/eng/targets/Imports.targets @@ -49,15 +49,15 @@ - - false - true + + false + true @@ -168,34 +168,6 @@ Condition="$(_VersionComparisonResult) < 0"/> - - - - - - - - - - - - - - - + + false + + diff --git a/eng/test-determinism.ps1 b/eng/test-determinism.ps1 index 40f32a0cf53c1..fa5d1001bd27c 100644 --- a/eng/test-determinism.ps1 +++ b/eng/test-determinism.ps1 @@ -1,8 +1,6 @@ [CmdletBinding(PositionalBinding=$false)] param([string]$configuration = "Debug", [string]$msbuildEngine = "vs", - [string]$bootstrapDir = "", - [string]$bootstrapConfiguration = "Debug", [string]$altRootDrive = "q:", [switch]$help) @@ -28,13 +26,13 @@ $script:skipList = @( # Added to work around https://github.com/dotnet/roslyn/issues/48417 "Microsoft.CodeAnalysis.EditorFeatures2.UnitTests.dll" ) - function Run-Build([string]$rootDir, [string]$logFileName) { + # Clean out the previous run Write-Host "Cleaning binaries" $stopWatch = [System.Diagnostics.StopWatch]::StartNew() - Remove-Item -Recurse (Get-BinDir $rootDir) - Remove-Item -Recurse (Get-ObjDir $rootDir) + Remove-Item -Recurse (Get-BinDir $rootDir) -ErrorAction SilentlyContinue + Remove-Item -Recurse (Get-ObjDir $rootDir) -ErrorAction SilentlyContinue $stopWatch.Stop() Write-Host "Cleaning took $($stopWatch.Elapsed)" @@ -48,7 +46,9 @@ function Run-Build([string]$rootDir, [string]$logFileName) { $logFileName = [IO.Path]::ChangeExtension($logFileName, ".binlog") $logFilePath = Join-Path $LogDir $logFileName - Write-Host "Building $solution" + Stop-Processes + + Write-Host "Building $solution using $bootstrapDir" MSBuild $toolsetBuildProj ` /p:Projects=$solution ` /p:Restore=true ` @@ -58,7 +58,13 @@ function Run-Build([string]$rootDir, [string]$logFileName) { /p:DeployExtension=false ` /p:RepoRoot=$rootDir ` /p:TreatWarningsAsErrors=true ` + /p:BootstrapBuildPath=$bootstrapDir ` + /p:RunAnalyzers=false ` + /p:RunAnalyzersDuringBuild=false ` + /p:RestoreUseStaticGraphEvaluation=true ` /bl:$logFilePath + + Stop-Processes } function Get-ObjDir([string]$rootDir) { @@ -76,12 +82,15 @@ function Get-FilesToProcess([string]$rootDir) { foreach ($item in Get-ChildItem -re -in *.dll,*.exe,*.pdb,*.sourcelink.json $objDir) { $filePath = $item.FullName $fileName = Split-Path -leaf $filePath + $relativeDirectory = Split-Path -parent $filePath + $relativeDirectory = $relativeDirectory.Substring($objDir.Length) + $relativeDirectory = $relativeDirectory.TrimStart("\") if ($skipList.Contains($fileName)) { continue; } - $fileId = $filePath.Substring($objDir.Length).Replace("\", ".") + $fileId = $filePath.Substring($objDir.Length).Replace("\", ".").TrimStart(".") $fileHash = (Get-FileHash $filePath -algorithm MD5).Hash $data = @{} @@ -90,6 +99,7 @@ function Get-FilesToProcess([string]$rootDir) { $data.FileId = $fileId $data.FileName = $fileName $data.FilePath = $filePath + $data.RelativeDirectory = $relativeDirectory $keyFilePath = $filePath + ".key" $keyFileName = Split-Path -leaf $keyFilePath @@ -115,7 +125,7 @@ function Record-Binaries([string]$rootDir) { $map = @{ } foreach ($fileData in Get-FilesToProcess $rootDir) { - Write-Host "`t$($fileData.FileName) = $($fileData.Hash)" + Write-Host "`t$($fileData.FileId) = $($fileData.Hash)" $map[$fileData.FileId] = $fileData } $stopWatch.Stop() @@ -168,6 +178,7 @@ function Test-Build([string]$rootDir, $dataMap, [string]$logFileName) { $fileId = $fileData.FileId $fileName = $fileData.FileName $filePath = $fileData.FilePath + $relativeDir = $fileData.RelativeDirectory if (-not $dataMap.Contains($fileId)) { Write-Host "ERROR! Missing entry in map $fileId->$filePath" @@ -177,25 +188,30 @@ function Test-Build([string]$rootDir, $dataMap, [string]$logFileName) { $oldfileData = $datamap[$fileId] if ($fileData.Hash -ne $oldFileData.Hash) { - Write-Host "`tERROR! $fileName contents don't match" + Write-Host "`tERROR! $relativeDir\$fileName contents don't match" $allGood = $false $errorList += $fileName + $errorCurrentDirLeft = Join-Path $errorDirLeft $relativeDir + Create-Directory $errorCurrentDirLeft + $errorCurrentDirRight = Join-Path $errorDirRight $relativeDir + Create-Directory $errorCurrentDirRight + # Save out the original and baseline for investigation - [IO.File]::WriteAllBytes((Join-Path $errorDirLeft $fileName), $oldFileData.Content) - Copy-Item $filePath (Join-Path $errorDirRight $fileName) + [IO.File]::WriteAllBytes((Join-Path $errorCurrentDirLeft $fileName), $oldFileData.Content) + Copy-Item $filePath (Join-Path $errorCurrentDirRight $fileName) # Copy the key files if available too $keyFileName = $oldFileData.KeyFileName if ($keyFileName -ne "") { - [IO.File]::WriteAllBytes((Join-Path $errorDirLeft $keyFileName), $oldFileData.KeyFileContent) - Copy-Item $fileData.KeyFilePath (Join-Path $errorDirRight $keyFileName) + [IO.File]::WriteAllBytes((Join-Path $errorCurrentDirLeft $keyFileName), $oldFileData.KeyFileContent) + Copy-Item $fileData.KeyFilePath (Join-Path $errorCurrentDirRight $keyFileName) } continue } - Write-Host "`tVerified $fileName" + Write-Host "`tVerified $relativeDir\$fileName" } if (-not $allGood) { @@ -219,7 +235,7 @@ function Test-Build([string]$rootDir, $dataMap, [string]$logFileName) { function Run-Test() { # Run the initial build so that we can populate the maps - Run-Build $RepoRoot -logFileName "Initial" + Run-Build $RepoRoot -logFileName "Initial" -useBootstrap $dataMap = Record-Binaries $RepoRoot Test-MapContents $dataMap @@ -252,19 +268,15 @@ try { Create-Directory $errorDirLeft Create-Directory $errorDirRight + $ci = $true $runAnalyzers = $false $binaryLog = $true $officialBuildId = "" - $ci = $true $nodeReuse = $false $properties = @() - if ($bootstrapDir -eq "") { - $bootstrapDir = Make-BootstrapBuild - } elseif (![IO.Path]::IsPathRooted($script:bootstrapDir)) { - Write-Host "The bootstrap build path must be absolute" - exit 1 - } + $script:bootstrapConfiguration = "Release" + $bootstrapDir = Make-BootstrapBuild Run-Test exit 0 diff --git a/global.json b/global.json index 1498de17df5c1..c6d74253e03b6 100644 --- a/global.json +++ b/global.json @@ -1,17 +1,17 @@ { "sdk": { - "version": "5.0.100-rc.2.20479.15", + "version": "5.0.100", "allowPrerelease": true, "rollForward": "major" }, "tools": { - "dotnet": "5.0.100-rc.2.20479.15", + "dotnet": "5.0.100", "vs": { "version": "16.8" }, "xcopy-msbuild": "16.8.0-preview2.1" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "1.0.0-beta.20465.6" + "Microsoft.DotNet.Arcade.Sdk": "1.0.0-beta.20570.10" } } diff --git a/scripts/vscode-build.ps1 b/scripts/vscode-build.ps1 index aaefcad20dd4f..c48e78d6eee01 100644 --- a/scripts/vscode-build.ps1 +++ b/scripts/vscode-build.ps1 @@ -14,7 +14,7 @@ $projectFileInfo = Get-ProjectFile $fileInfo if ($projectFileInfo) { $buildTool = InitializeBuildTool $frameworkArg = if ($framework -ne "") { " -p:TargetFramework=$framework" } else { "" } - $buildArgs = "$($buildTool.Command) -v:m -m -p:UseRoslynAnalyzers=false -p:GenerateFullPaths=true$frameworkArg $($projectFileInfo.FullName)" + $buildArgs = "$($buildTool.Command) -v:m -m -p:RunAnalyzersDuringBuild=false -p:GenerateFullPaths=true$frameworkArg $($projectFileInfo.FullName)" Write-Host "$($buildTool.Path) $buildArgs" Exec-Console $buildTool.Path $buildArgs diff --git a/src/Analyzers/CSharp/Analyzers/SimplifyInterpolation/CSharpSimplifyInterpolationDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/SimplifyInterpolation/CSharpSimplifyInterpolationDiagnosticAnalyzer.cs index ff1220e4629f9..6484ab2763622 100644 --- a/src/Analyzers/CSharp/Analyzers/SimplifyInterpolation/CSharpSimplifyInterpolationDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/SimplifyInterpolation/CSharpSimplifyInterpolationDiagnosticAnalyzer.cs @@ -16,7 +16,7 @@ namespace Microsoft.CodeAnalysis.CSharp.SimplifyInterpolation { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpSimplifyInterpolationDiagnosticAnalyzer : AbstractSimplifyInterpolationDiagnosticAnalyzer< - InterpolationSyntax, ExpressionSyntax> + InterpolationSyntax, ExpressionSyntax, ConditionalExpressionSyntax, ParenthesizedExpressionSyntax> { protected override IVirtualCharService GetVirtualCharService() => CSharpVirtualCharService.Instance; diff --git a/src/Analyzers/CSharp/Analyzers/UseObjectInitializer/CSharpUseObjectInitializerDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseObjectInitializer/CSharpUseObjectInitializerDiagnosticAnalyzer.cs index c48c3be130f76..ad4499cee50b2 100644 --- a/src/Analyzers/CSharp/Analyzers/UseObjectInitializer/CSharpUseObjectInitializerDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/UseObjectInitializer/CSharpUseObjectInitializerDiagnosticAnalyzer.cs @@ -31,5 +31,34 @@ protected override bool AreObjectInitializersSupported(SyntaxNodeAnalysisContext } protected override ISyntaxFacts GetSyntaxFacts() => CSharpSyntaxFacts.Instance; + + protected override bool IsValidContainingStatement(StatementSyntax node) + { + // We don't want to offer this for using declarations because the way they are lifted means all + // initialization is done before entering try block. For example + // + // using var c = new Disposable() { Goo = 2 }; + // + // is lowered to: + // + // var __c = new Disposable(); + // __c.Goo = 2; + // var c = __c; + // try + // { + // } + // finally + // { + // if (c != null) + // { + // ((IDisposable)c).Dispose(); + // } + // } + // + // As can be seen, if initializing throws any kind of exception, the newly created instance will not + // be disposed properly. + return node is not LocalDeclarationStatementSyntax localDecl || + localDecl.UsingKeyword == default; + } } } diff --git a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.cs.xlf b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.cs.xlf index b29a016af3d42..78936d2a8e788 100644 --- a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.cs.xlf +++ b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.cs.xlf @@ -29,7 +29,7 @@ Discard can be removed - Discard can be removed + Proměnná typu discard se dá odebrat. @@ -89,7 +89,7 @@ Remove unnecessary discard - Remove unnecessary discard + Odebrat nepotřebnou proměnnou typu discard @@ -214,7 +214,7 @@ Use 'new(...)' - Use 'new(...)' + Použít new(...) {Locked="new(...)"} This is a C# construct and should not be localized. @@ -279,7 +279,7 @@ 'new' expression can be simplified - 'new' expression can be simplified + Výraz new se dá zjednodušit. diff --git a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.de.xlf b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.de.xlf index 99b65249bbbcb..33c16013df6e0 100644 --- a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.de.xlf +++ b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.de.xlf @@ -29,7 +29,7 @@ Discard can be removed - Discard can be removed + discard-Element kann entfernt werden. @@ -89,7 +89,7 @@ Remove unnecessary discard - Remove unnecessary discard + Nicht benötigtes discard-Element entfernen @@ -214,7 +214,7 @@ Use 'new(...)' - Use 'new(...)' + "new(...)" verwenden {Locked="new(...)"} This is a C# construct and should not be localized. @@ -279,12 +279,12 @@ 'new' expression can be simplified - 'new' expression can be simplified + new-Ausdruck kann vereinfacht werden 'typeof' can be converted to 'nameof' - 'typeof' can be converted to 'nameof' + "typeof" kann in "nameof" konvertiert werden. diff --git a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.es.xlf b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.es.xlf index 0ddb03569cce6..d4e343ce26585 100644 --- a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.es.xlf +++ b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.es.xlf @@ -29,7 +29,7 @@ Discard can be removed - Discard can be removed + El descarte se puede quitar. @@ -89,7 +89,7 @@ Remove unnecessary discard - Remove unnecessary discard + Quitar un descarte innecesario @@ -214,7 +214,7 @@ Use 'new(...)' - Use 'new(...)' + Usar "new(...)" {Locked="new(...)"} This is a C# construct and should not be localized. @@ -279,12 +279,12 @@ 'new' expression can be simplified - 'new' expression can be simplified + La expresión "new" se puede simplificar. 'typeof' can be converted to 'nameof' - 'typeof' can be converted to 'nameof' + "typeof" puede convertirse en "nameof" diff --git a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.fr.xlf b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.fr.xlf index e760f0c7558c1..a9f2abb4c8c2c 100644 --- a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.fr.xlf +++ b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.fr.xlf @@ -29,7 +29,7 @@ Discard can be removed - Discard can be removed + Vous pouvez supprimer le discard @@ -89,7 +89,7 @@ Remove unnecessary discard - Remove unnecessary discard + Supprimer tout discard inutile @@ -214,7 +214,7 @@ Use 'new(...)' - Use 'new(...)' + Utiliser 'new(...)' {Locked="new(...)"} This is a C# construct and should not be localized. @@ -279,12 +279,12 @@ 'new' expression can be simplified - 'new' expression can be simplified + L'expression 'new' peut être simplifiée 'typeof' can be converted to 'nameof' - 'typeof' can be converted to 'nameof' + 'typeof' peut être converti en 'nameof' diff --git a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.it.xlf b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.it.xlf index e84b1e44a16d7..63601c2810fdd 100644 --- a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.it.xlf +++ b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.it.xlf @@ -29,7 +29,7 @@ Discard can be removed - Discard can be removed + È possibile rimuovere discard @@ -89,7 +89,7 @@ Remove unnecessary discard - Remove unnecessary discard + Rimuovi discard non necessario @@ -214,7 +214,7 @@ Use 'new(...)' - Use 'new(...)' + Usa 'new(...)' {Locked="new(...)"} This is a C# construct and should not be localized. @@ -279,12 +279,12 @@ 'new' expression can be simplified - 'new' expression can be simplified + L'espressione 'new' può essere semplificata 'typeof' can be converted to 'nameof' - 'typeof' can be converted to 'nameof' + 'typeof' può essere convertito in 'nameof' diff --git a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.ja.xlf b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.ja.xlf index f7d17d05f7fd3..00516bfbdf3fd 100644 --- a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.ja.xlf +++ b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.ja.xlf @@ -9,7 +9,7 @@ Add braces to '{0}' statement. - {0}' ステートメントに波かっこを追加します。 + '{0}' ステートメントに波かっこを追加します。 @@ -29,7 +29,7 @@ Discard can be removed - Discard can be removed + ディスカードは削除できます @@ -89,7 +89,7 @@ Remove unnecessary discard - Remove unnecessary discard + 不要なディスカードを削除 @@ -214,7 +214,7 @@ Use 'new(...)' - Use 'new(...)' + 'new(...)' を使用する {Locked="new(...)"} This is a C# construct and should not be localized. @@ -264,7 +264,7 @@ {0} can be simplified - {0} を簡略化できます。 + {0} を簡略化できます @@ -279,12 +279,12 @@ 'new' expression can be simplified - 'new' expression can be simplified + 'new' 式を単純化できます 'typeof' can be converted to 'nameof' - 'typeof' can be converted to 'nameof' + 'typeof' を 'nameof' に変換できます diff --git a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.ko.xlf b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.ko.xlf index 842b4bad5020c..a489b70929dc0 100644 --- a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.ko.xlf +++ b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.ko.xlf @@ -9,7 +9,7 @@ Add braces to '{0}' statement. - {0}' 문에 중괄호를 추가합니다. + '{0}' 문에 중괄호를 추가합니다. @@ -29,7 +29,7 @@ Discard can be removed - Discard can be removed + 무시 항목은 제거할 수 있습니다. @@ -89,7 +89,7 @@ Remove unnecessary discard - Remove unnecessary discard + 불필요한 무시 항목 제거 @@ -214,7 +214,7 @@ Use 'new(...)' - Use 'new(...)' + 'new(...)' 사용 {Locked="new(...)"} This is a C# construct and should not be localized. @@ -279,12 +279,12 @@ 'new' expression can be simplified - 'new' expression can be simplified + 'new' 식을 간단하게 줄일 수 있습니다. 'typeof' can be converted to 'nameof' - 'typeof' can be converted to 'nameof' + 'typeof'를 'nameof'로 변환할 수 있습니다. diff --git a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.pl.xlf b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.pl.xlf index 4c362bef5be2a..d874e2405d230 100644 --- a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.pl.xlf +++ b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.pl.xlf @@ -29,7 +29,7 @@ Discard can be removed - Discard can be removed + Odrzucenie można usunąć @@ -89,7 +89,7 @@ Remove unnecessary discard - Remove unnecessary discard + Usuń niepotrzebne odrzucenie @@ -214,7 +214,7 @@ Use 'new(...)' - Use 'new(...)' + Użyj operatora „new(...)” {Locked="new(...)"} This is a C# construct and should not be localized. @@ -279,12 +279,12 @@ 'new' expression can be simplified - 'new' expression can be simplified + Wyrażenie „new” można uprościć 'typeof' can be converted to 'nameof' - 'typeof' can be converted to 'nameof' + Element „typeof” można przekonwertować na element „nameof” diff --git a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.pt-BR.xlf b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.pt-BR.xlf index cf4c9003bb395..90e351a2b31d2 100644 --- a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.pt-BR.xlf +++ b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.pt-BR.xlf @@ -29,7 +29,7 @@ Discard can be removed - Discard can be removed + O discard pode ser removido @@ -89,7 +89,7 @@ Remove unnecessary discard - Remove unnecessary discard + Remover o discard desnecessário @@ -214,7 +214,7 @@ Use 'new(...)' - Use 'new(...)' + Usar 'new(...)' {Locked="new(...)"} This is a C# construct and should not be localized. @@ -279,12 +279,12 @@ 'new' expression can be simplified - 'new' expression can be simplified + A expressão 'new' pode ser simplificada 'typeof' can be converted to 'nameof' - 'typeof' can be converted to 'nameof' + 'typeof' pode ser convertido em 'nameof' diff --git a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.ru.xlf b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.ru.xlf index e3f7d9054d262..76b80f76f0b71 100644 --- a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.ru.xlf +++ b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.ru.xlf @@ -29,7 +29,7 @@ Discard can be removed - Discard can be removed + Пустую переменную можно удалить @@ -89,7 +89,7 @@ Remove unnecessary discard - Remove unnecessary discard + Удалите ненужную пустую переменную. @@ -214,7 +214,7 @@ Use 'new(...)' - Use 'new(...)' + Используйте "new(...)". {Locked="new(...)"} This is a C# construct and should not be localized. @@ -279,12 +279,12 @@ 'new' expression can be simplified - 'new' expression can be simplified + выражение "new" можно упростить 'typeof' can be converted to 'nameof' - 'typeof' can be converted to 'nameof' + "typeof" можно преобразовать в "nameof". diff --git a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.tr.xlf b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.tr.xlf index dae24cc410761..09fd323dbc119 100644 --- a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.tr.xlf +++ b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.tr.xlf @@ -9,7 +9,7 @@ Add braces to '{0}' statement. - {0}' deyimine küme ayracı ekleyin. + '{0}' deyimine küme ayracı ekleyin. @@ -29,7 +29,7 @@ Discard can be removed - Discard can be removed + Atma işlemi kaldırılabilir @@ -89,7 +89,7 @@ Remove unnecessary discard - Remove unnecessary discard + Gereksiz atmayı kaldır @@ -214,7 +214,7 @@ Use 'new(...)' - Use 'new(...)' + 'new(...)' kullanın {Locked="new(...)"} This is a C# construct and should not be localized. @@ -279,12 +279,12 @@ 'new' expression can be simplified - 'new' expression can be simplified + 'new' ifadesi basitleştirilebilir 'typeof' can be converted to 'nameof' - 'typeof' can be converted to 'nameof' + 'typeof' metodu 'nameof' metoduna dönüştürülebilir diff --git a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.zh-Hans.xlf b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.zh-Hans.xlf index 3670da1a17bcc..3823f59dddf22 100644 --- a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.zh-Hans.xlf +++ b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Add braces @@ -29,7 +29,7 @@ Discard can be removed - Discard can be removed + 可删除放弃项 @@ -89,7 +89,7 @@ Remove unnecessary discard - Remove unnecessary discard + 删除不必要的放弃项 @@ -214,7 +214,7 @@ Use 'new(...)' - Use 'new(...)' + 使用 "new(...)" {Locked="new(...)"} This is a C# construct and should not be localized. @@ -279,7 +279,7 @@ 'new' expression can be simplified - 'new' expression can be simplified + 可简化 "new" 表达式 diff --git a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.zh-Hant.xlf b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.zh-Hant.xlf index 4bc17203fe235..6794831460915 100644 --- a/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.zh-Hant.xlf +++ b/src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Add braces @@ -29,7 +29,7 @@ Discard can be removed - Discard can be removed + 可以移除捨棄 @@ -89,7 +89,7 @@ Remove unnecessary discard - Remove unnecessary discard + 移除不必要的捨棄 @@ -214,7 +214,7 @@ Use 'new(...)' - Use 'new(...)' + 使用 'new(...)' {Locked="new(...)"} This is a C# construct and should not be localized. @@ -279,12 +279,12 @@ 'new' expression can be simplified - 'new' expression can be simplified + 'new' 運算式可簡化 'typeof' can be converted to 'nameof' - 'typeof' can be converted to 'nameof' + 'typeof' 可轉換為 'nameof' diff --git a/src/Analyzers/CSharp/CodeFixes/SimplifyInterpolation/CSharpSimplifyInterpolationCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/SimplifyInterpolation/CSharpSimplifyInterpolationCodeFixProvider.cs index 2a379fa748b31..bcf1edb3b4caa 100644 --- a/src/Analyzers/CSharp/CodeFixes/SimplifyInterpolation/CSharpSimplifyInterpolationCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/SimplifyInterpolation/CSharpSimplifyInterpolationCodeFixProvider.cs @@ -16,7 +16,8 @@ namespace Microsoft.CodeAnalysis.CSharp.SimplifyInterpolation [ExportCodeFixProvider(LanguageNames.CSharp), Shared] internal class CSharpSimplifyInterpolationCodeFixProvider : AbstractSimplifyInterpolationCodeFixProvider< InterpolationSyntax, ExpressionSyntax, InterpolationAlignmentClauseSyntax, - InterpolationFormatClauseSyntax, InterpolatedStringExpressionSyntax> + InterpolationFormatClauseSyntax, InterpolatedStringExpressionSyntax, + ConditionalExpressionSyntax, ParenthesizedExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] diff --git a/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.de.xlf b/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.de.xlf index 9567f54e6489d..5b6d38078ab2a 100644 --- a/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.de.xlf +++ b/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.de.xlf @@ -9,7 +9,7 @@ Convert 'typeof' to 'nameof' - Convert 'typeof' to 'nameof' + "typeof" in "nameof" konvertieren diff --git a/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.es.xlf b/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.es.xlf index c286fe9899ed7..308740d584efd 100644 --- a/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.es.xlf +++ b/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.es.xlf @@ -9,7 +9,7 @@ Convert 'typeof' to 'nameof' - Convert 'typeof' to 'nameof' + Convertir "typeof" en "nameof" diff --git a/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.fr.xlf b/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.fr.xlf index 03c7561c41a87..d4bc7d20abecf 100644 --- a/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.fr.xlf +++ b/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.fr.xlf @@ -9,7 +9,7 @@ Convert 'typeof' to 'nameof' - Convert 'typeof' to 'nameof' + Convertir 'typeof' en 'nameof' diff --git a/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.it.xlf b/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.it.xlf index bb537e9fb0ce6..92a725957a081 100644 --- a/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.it.xlf +++ b/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.it.xlf @@ -9,7 +9,7 @@ Convert 'typeof' to 'nameof' - Convert 'typeof' to 'nameof' + Convertire 'typeof' in 'nameof' diff --git a/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.ja.xlf b/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.ja.xlf index 9d4848da89e51..b380152856b62 100644 --- a/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.ja.xlf +++ b/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.ja.xlf @@ -9,7 +9,7 @@ Convert 'typeof' to 'nameof' - Convert 'typeof' to 'nameof' + 'typeof' を 'nameof' に変換します diff --git a/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.ko.xlf b/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.ko.xlf index bd0ddf3a412da..f786de5e596f4 100644 --- a/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.ko.xlf +++ b/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.ko.xlf @@ -9,7 +9,7 @@ Convert 'typeof' to 'nameof' - Convert 'typeof' to 'nameof' + 'typeof'를 'nameof'로 변환 diff --git a/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.pl.xlf b/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.pl.xlf index 96f0e2862db8b..8a0b23bda018c 100644 --- a/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.pl.xlf +++ b/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.pl.xlf @@ -9,7 +9,7 @@ Convert 'typeof' to 'nameof' - Convert 'typeof' to 'nameof' + Konwertuj element „typeof” na element „nameof” diff --git a/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.pt-BR.xlf b/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.pt-BR.xlf index 1316a41f8b2d3..93abea6300049 100644 --- a/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.pt-BR.xlf +++ b/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.pt-BR.xlf @@ -9,7 +9,7 @@ Convert 'typeof' to 'nameof' - Convert 'typeof' to 'nameof' + Converter 'typeof' em 'nameof' diff --git a/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.ru.xlf b/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.ru.xlf index 5ccc684abcf2f..18934a7f07293 100644 --- a/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.ru.xlf +++ b/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.ru.xlf @@ -9,7 +9,7 @@ Convert 'typeof' to 'nameof' - Convert 'typeof' to 'nameof' + Преобразовать "typeof" в "nameof" diff --git a/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.tr.xlf b/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.tr.xlf index bff5d137c5463..f02981981dccf 100644 --- a/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.tr.xlf +++ b/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.tr.xlf @@ -9,7 +9,7 @@ Convert 'typeof' to 'nameof' - Convert 'typeof' to 'nameof' + 'Typeof' metodunu 'nameof' metoduna dönüştürün diff --git a/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.zh-Hans.xlf b/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.zh-Hans.xlf index d5964a99cd09d..ebf63796fe3f4 100644 --- a/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.zh-Hans.xlf +++ b/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Add 'this.' diff --git a/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.zh-Hant.xlf b/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.zh-Hant.xlf index beeaa80aa7f95..af512ffe26975 100644 --- a/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.zh-Hant.xlf +++ b/src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Add 'this.' @@ -9,7 +9,7 @@ Convert 'typeof' to 'nameof' - Convert 'typeof' to 'nameof' + 將 'typeof' 轉換為 'nameof' diff --git a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests.cs index 7ab4771771349..c822e2553e3bc 100644 --- a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable - using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryCast; @@ -8289,5 +8287,111 @@ public void M(UIntPtr x) await VerifyCS.VerifyCodeFixAsync(source, fixedCode); } + + [WorkItem(49140, "https://github.com/dotnet/roslyn/issues/49140")] + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryCast)] + public async Task DoNotRemoveBitwiseNotOfUnsignedExtendedValue1() + { + var source = +@" +class C +{ + public static ulong P(ulong a, uint b) + { + return a & ~(ulong)b; + } +}"; + + var test = new VerifyCS.Test() + { + TestCode = source, + FixedCode = source, + LanguageVersion = LanguageVersion.CSharp9 + }; + + await test.RunAsync(); + } + + [WorkItem(49140, "https://github.com/dotnet/roslyn/issues/49140")] + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryCast)] + public async Task DoNotRemoveBitwiseNotOfUnsignedExtendedValue2() + { + var source = +@" +class C +{ + public static nuint N(nuint a, uint b) + { + return a & ~(nuint)b; + } +}"; + + var test = new VerifyCS.Test() + { + TestCode = source, + FixedCode = source, + LanguageVersion = LanguageVersion.CSharp9 + }; + + await test.RunAsync(); + } + + [WorkItem(49140, "https://github.com/dotnet/roslyn/issues/49140")] + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryCast)] + public async Task DoRemoveBitwiseNotOfSignExtendedValue1() + { + + var test = new VerifyCS.Test() + { + TestCode = @" +class C +{ + public static long P(long a, int b) + { + return a & ~[|(long)|]b; + } +}", + FixedCode = @" +class C +{ + public static long P(long a, int b) + { + return a & ~b; + } +}", + LanguageVersion = LanguageVersion.CSharp9 + }; + + await test.RunAsync(); + } + + [WorkItem(49140, "https://github.com/dotnet/roslyn/issues/49140")] + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryCast)] + public async Task DoRemoveBitwiseNotOfSignExtendedValue2() + { + + var test = new VerifyCS.Test() + { + TestCode = @" +class C +{ + public static nint N(nint a, int b) + { + return a & ~[|(nint)|]b; + } +}", + FixedCode = @" +class C +{ + public static nint N(nint a, int b) + { + return a & ~b; + } +}", + LanguageVersion = LanguageVersion.CSharp9 + }; + + await test.RunAsync(); + } } } diff --git a/src/Analyzers/CSharp/Tests/SimplifyInterpolation/SimplifyInterpolationTests.cs b/src/Analyzers/CSharp/Tests/SimplifyInterpolation/SimplifyInterpolationTests.cs index e245e660c0df6..c57ba2958339c 100644 --- a/src/Analyzers/CSharp/Tests/SimplifyInterpolation/SimplifyInterpolationTests.cs +++ b/src/Analyzers/CSharp/Tests/SimplifyInterpolation/SimplifyInterpolationTests.cs @@ -1000,6 +1000,66 @@ void M(B someValue) { _ = $""prefix {someValue} suffix""; } +}"); + } + + [Fact, WorkItem(49647, "https://github.com/dotnet/roslyn/issues/49647")] + public async Task ConditionalExpressionMustRemainParenthesizedWhenUsingParameterlessToString() + { + await TestInRegularAndScript1Async( +@"class C +{ + void M(bool cond) + { + _ = $""{(cond ? 1 : 2){|Unnecessary:[||].ToString()|}}""; + } +}", +@"class C +{ + void M(bool cond) + { + _ = $""{(cond ? 1 : 2)}""; + } +}"); + } + + [Fact, WorkItem(49647, "https://github.com/dotnet/roslyn/issues/49647")] + public async Task ConditionalExpressionMustRemainParenthesizedWhenUsingParameterizedToString() + { + await TestInRegularAndScript1Async( +@"class C +{ + void M(bool cond) + { + _ = $""{(cond ? 1 : 2){|Unnecessary:[||].ToString(""|}g{|Unnecessary:"")|}}""; + } +}", +@"class C +{ + void M(bool cond) + { + _ = $""{(cond ? 1 : 2):g}""; + } +}"); + } + + [Fact, WorkItem(49647, "https://github.com/dotnet/roslyn/issues/49647")] + public async Task ConditionalExpressionMustRemainParenthesizedWhenUsingPadLeft() + { + await TestInRegularAndScript1Async( +@"class C +{ + void M(bool cond) + { + _ = $""{(cond ? ""1"" : ""2""){|Unnecessary:[||].PadLeft(|}3{|Unnecessary:)|}}""; + } +}", +@"class C +{ + void M(bool cond) + { + _ = $""{(cond ? ""1"" : ""2""),3}""; + } }"); } } diff --git a/src/Analyzers/CSharp/Tests/UseCompoundAssignment/UseCompoundAssignmentTests.cs b/src/Analyzers/CSharp/Tests/UseCompoundAssignment/UseCompoundAssignmentTests.cs index b2a0c5b150024..65769a72b907f 100644 --- a/src/Analyzers/CSharp/Tests/UseCompoundAssignment/UseCompoundAssignmentTests.cs +++ b/src/Analyzers/CSharp/Tests/UseCompoundAssignment/UseCompoundAssignmentTests.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable - using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; @@ -790,6 +788,44 @@ InsertionPoint Up() }"); } + [WorkItem(49294, "https://github.com/dotnet/roslyn/issues/49294")] + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCompoundAssignment)] + public async Task TestNotOnImplicitObjectInitializer() + { + await TestMissingAsync( +@" +struct InsertionPoint +{ + int level; + + InsertionPoint Up() + { + return new() + { + level [||]= level - 1, + }; + } +}"); + } + + [WorkItem(49294, "https://github.com/dotnet/roslyn/issues/49294")] + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCompoundAssignment)] + public async Task TestNotOnRecord() + { + await TestMissingAsync( +@" +record InsertionPoint(int level) +{ + InsertionPoint Up() + { + return this with + { + level [||]= level - 1, + }; + } +}"); + } + [WorkItem(38137, "https://github.com/dotnet/roslyn/issues/38137")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCompoundAssignment)] public async Task TestParenthesizedExpression() diff --git a/src/Analyzers/CSharp/Tests/UseObjectInitializer/UseObjectInitializerTests.cs b/src/Analyzers/CSharp/Tests/UseObjectInitializer/UseObjectInitializerTests.cs index 84b21aa8788cd..de7eafd7c2665 100644 --- a/src/Analyzers/CSharp/Tests/UseObjectInitializer/UseObjectInitializerTests.cs +++ b/src/Analyzers/CSharp/Tests/UseObjectInitializer/UseObjectInitializerTests.cs @@ -687,6 +687,27 @@ public void Main() }; e.Name = string.Empty; } +}"); + } + + [WorkItem(37675, "https://github.com/dotnet/roslyn/issues/37675")] + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)] + public async Task TestDoNotOfferForUsingDeclaration() + { + await TestMissingInRegularAndScriptAsync( +@"class C : IDisposable +{ + int i; + + void M() + { + using var c = [||]new C(); + c.i = 1; + } + + void Dispose() + { + } }"); } } diff --git a/src/Analyzers/Core/Analyzers/SimplifyInterpolation/AbstractSimplifyInterpolationDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/SimplifyInterpolation/AbstractSimplifyInterpolationDiagnosticAnalyzer.cs index 26e8dd1ffc0d5..0f7cbe60530e3 100644 --- a/src/Analyzers/Core/Analyzers/SimplifyInterpolation/AbstractSimplifyInterpolationDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/SimplifyInterpolation/AbstractSimplifyInterpolationDiagnosticAnalyzer.cs @@ -15,9 +15,13 @@ namespace Microsoft.CodeAnalysis.SimplifyInterpolation { internal abstract class AbstractSimplifyInterpolationDiagnosticAnalyzer< TInterpolationSyntax, - TExpressionSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer + TExpressionSyntax, + TConditionalExpressionSyntax, + TParenthesizedExpressionSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TInterpolationSyntax : SyntaxNode where TExpressionSyntax : SyntaxNode + where TConditionalExpressionSyntax : TExpressionSyntax + where TParenthesizedExpressionSyntax : TExpressionSyntax { protected AbstractSimplifyInterpolationDiagnosticAnalyzer() : base(IDEDiagnosticIds.SimplifyInterpolationId, @@ -58,7 +62,7 @@ private void AnalyzeInterpolation(OperationAnalysisContext context) return; } - Helpers.UnwrapInterpolation( + Helpers.UnwrapInterpolation( GetVirtualCharService(), GetSyntaxFacts(), interpolation, out _, out var alignment, out _, out var formatString, out var unnecessaryLocations); diff --git a/src/Analyzers/Core/Analyzers/SimplifyInterpolation/Helpers.cs b/src/Analyzers/Core/Analyzers/SimplifyInterpolation/Helpers.cs index abaa64330c976..7a81b6da5b00b 100644 --- a/src/Analyzers/Core/Analyzers/SimplifyInterpolation/Helpers.cs +++ b/src/Analyzers/Core/Analyzers/SimplifyInterpolation/Helpers.cs @@ -16,12 +16,26 @@ namespace Microsoft.CodeAnalysis.SimplifyInterpolation { internal static class Helpers { - public static void UnwrapInterpolation( + private static SyntaxNode GetPreservedInterpolationExpressionSyntax( + IOperation operation) + where TConditionalExpressionSyntax : SyntaxNode + where TParenthesizedExpressionSyntax : SyntaxNode + { + return operation.Syntax switch + { + TConditionalExpressionSyntax { Parent: TParenthesizedExpressionSyntax parent } => parent, + var syntax => syntax, + }; + } + + public static void UnwrapInterpolation( IVirtualCharService virtualCharService, ISyntaxFacts syntaxFacts, IInterpolationOperation interpolation, out TExpressionSyntax? unwrapped, out TExpressionSyntax? alignment, out bool negate, out string? formatString, out ImmutableArray unnecessaryLocations) - where TInterpolationSyntax : SyntaxNode - where TExpressionSyntax : SyntaxNode + where TInterpolationSyntax : SyntaxNode + where TExpressionSyntax : SyntaxNode + where TConditionalExpressionSyntax : TExpressionSyntax + where TParenthesizedExpressionSyntax : TExpressionSyntax { alignment = null; negate = false; @@ -32,15 +46,17 @@ public static void UnwrapInterpolation( var expression = Unwrap(interpolation.Expression); if (interpolation.Alignment == null) { - UnwrapAlignmentPadding(expression, out expression, out alignment, out negate, unnecessarySpans); + UnwrapAlignmentPadding( + expression, out expression, out alignment, out negate, unnecessarySpans); } if (interpolation.FormatString == null) { - UnwrapFormatString(virtualCharService, syntaxFacts, expression, out expression, out formatString, unnecessarySpans); + UnwrapFormatString( + virtualCharService, syntaxFacts, expression, out expression, out formatString, unnecessarySpans); } - unwrapped = expression.Syntax as TExpressionSyntax; + unwrapped = GetPreservedInterpolationExpressionSyntax(expression) as TExpressionSyntax; unnecessaryLocations = unnecessarySpans.OrderBy(t => t.Start) @@ -65,9 +81,11 @@ private static IOperation Unwrap(IOperation expression) } } - private static void UnwrapFormatString( + private static void UnwrapFormatString( IVirtualCharService virtualCharService, ISyntaxFacts syntaxFacts, IOperation expression, out IOperation unwrapped, out string? formatString, List unnecessarySpans) + where TConditionalExpressionSyntax : SyntaxNode + where TParenthesizedExpressionSyntax : SyntaxNode { if (expression is IInvocationOperation { TargetMethod: { Name: nameof(ToString) } } invocation && HasNonImplicitInstance(invocation) && @@ -82,8 +100,9 @@ private static void UnwrapFormatString( unwrapped = invocation.Instance; formatString = value; + var unwrappedSyntax = GetPreservedInterpolationExpressionSyntax(unwrapped); unnecessarySpans.AddRange(invocation.Syntax.Span - .Subtract(invocation.Instance.Syntax.FullSpan) + .Subtract(unwrappedSyntax.FullSpan) .Subtract(GetSpanWithinLiteralQuotes(virtualCharService, literal.Syntax.GetFirstToken()))); return; } @@ -102,8 +121,9 @@ private static void UnwrapFormatString( unwrapped = invocation.Instance; formatString = ""; + var unwrappedSyntax = GetPreservedInterpolationExpressionSyntax(unwrapped); unnecessarySpans.AddRange(invocation.Syntax.Span - .Subtract(invocation.Instance.Syntax.FullSpan)); + .Subtract(unwrappedSyntax.FullSpan)); return; } } @@ -120,10 +140,12 @@ private static TextSpan GetSpanWithinLiteralQuotes(IVirtualCharService virtualCh : TextSpan.FromBounds(sequence.First().Span.Start, sequence.Last().Span.End); } - private static void UnwrapAlignmentPadding( + private static void UnwrapAlignmentPadding( IOperation expression, out IOperation unwrapped, out TExpressionSyntax? alignment, out bool negate, List unnecessarySpans) where TExpressionSyntax : SyntaxNode + where TConditionalExpressionSyntax : TExpressionSyntax + where TParenthesizedExpressionSyntax : TExpressionSyntax { if (expression is IInvocationOperation invocation && HasNonImplicitInstance(invocation)) @@ -146,8 +168,9 @@ private static void UnwrapAlignmentPadding( alignment = alignmentSyntax as TExpressionSyntax; negate = targetName == nameof(string.PadRight); + var unwrappedSyntax = GetPreservedInterpolationExpressionSyntax(unwrapped); unnecessarySpans.AddRange(invocation.Syntax.Span - .Subtract(invocation.Instance.Syntax.FullSpan) + .Subtract(unwrappedSyntax.FullSpan) .Subtract(alignmentSyntax.FullSpan)); return; } diff --git a/src/Analyzers/Core/Analyzers/UseCompoundAssignment/AbstractUseCompoundAssignmentDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseCompoundAssignment/AbstractUseCompoundAssignmentDiagnosticAnalyzer.cs index 4b01bb89e7a28..3d3d2ab4eab53 100644 --- a/src/Analyzers/Core/Analyzers/UseCompoundAssignment/AbstractUseCompoundAssignmentDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/UseCompoundAssignment/AbstractUseCompoundAssignmentDiagnosticAnalyzer.cs @@ -111,8 +111,10 @@ private void AnalyzeAssignment(SyntaxNodeAnalysisContext context) } // Don't offer if this is `x = x + 1` inside an obj initializer like: - // `new Point { x = x + 1 }` - if (_syntaxFacts.IsObjectInitializerNamedAssignmentIdentifier(assignmentLeft)) + // `new Point { x = x + 1 }` or + // `new () { x = x + 1 }` or + // `p with { x = x + 1 }` + if (_syntaxFacts.IsMemberInitializerNamedAssignmentIdentifier(assignmentLeft)) { return; } diff --git a/src/Analyzers/Core/Analyzers/UseObjectInitializer/AbstractUseObjectInitializerDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseObjectInitializer/AbstractUseObjectInitializerDiagnosticAnalyzer.cs index 20bedda7408d9..9dddaaf5aaf16 100644 --- a/src/Analyzers/Core/Analyzers/UseObjectInitializer/AbstractUseObjectInitializerDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/UseObjectInitializer/AbstractUseObjectInitializerDiagnosticAnalyzer.cs @@ -47,6 +47,8 @@ protected override void InitializeWorker(AnalysisContext context) protected abstract bool AreObjectInitializersSupported(SyntaxNodeAnalysisContext context); + protected abstract bool IsValidContainingStatement(TStatementSyntax node); + private void AnalyzeNode(SyntaxNodeAnalysisContext context) { if (!AreObjectInitializersSupported(context)) @@ -78,6 +80,11 @@ private void AnalyzeNode(SyntaxNodeAnalysisContext context) return; } + if (!IsValidContainingStatement(containingStatement)) + { + return; + } + var nodes = ImmutableArray.Create(containingStatement).AddRange(matches.Value.Select(m => m.Statement)); if (syntaxFacts.ContainsInterleavedDirective(nodes, context.CancellationToken)) { diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.cs.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.cs.xlf index b52f53f7dfd24..f6fb766bd2e3a 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.cs.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.cs.xlf @@ -229,7 +229,7 @@ Remove redundant equality - Remove redundant equality + Odebrat nadbytečnou rovnost @@ -279,7 +279,7 @@ Simplify conditional expression - Simplify conditional expression + Zjednodušit podmíněný výraz @@ -334,7 +334,7 @@ Use '--' operator - Use '--' operator + Použijte operátor --. @@ -344,7 +344,7 @@ Use '++' operator - Use '++' operator + Použijte operátor ++. diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.de.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.de.xlf index 0df208c7b1026..6ad528e4736bc 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.de.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.de.xlf @@ -229,7 +229,7 @@ Remove redundant equality - Remove redundant equality + Redundante Gleichheit entfernen @@ -239,7 +239,7 @@ Remove unnecessary suppression - Remove unnecessary suppression + Unnötige Unterdrückung entfernen @@ -279,7 +279,7 @@ Simplify conditional expression - Simplify conditional expression + Bedingten Ausdruck vereinfachen @@ -334,7 +334,7 @@ Use '--' operator - Use '--' operator + Operator "--" verwenden @@ -344,7 +344,7 @@ Use '++' operator - Use '++' operator + Operator "++" verwenden diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.es.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.es.xlf index 3607be029a0a6..cc01604c9bc32 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.es.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.es.xlf @@ -229,7 +229,7 @@ Remove redundant equality - Remove redundant equality + Quitar la igualdad redundante @@ -239,7 +239,7 @@ Remove unnecessary suppression - Remove unnecessary suppression + Quitar supresión innecesaria @@ -279,7 +279,7 @@ Simplify conditional expression - Simplify conditional expression + Simplificar la expresión condicional @@ -334,7 +334,7 @@ Use '--' operator - Use '--' operator + Usar el operador "--" @@ -344,7 +344,7 @@ Use '++' operator - Use '++' operator + Usar el operador "++" diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.fr.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.fr.xlf index b61a98d45dceb..42ba4c46b493a 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.fr.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.fr.xlf @@ -229,7 +229,7 @@ Remove redundant equality - Remove redundant equality + Supprimer l'égalité redondante @@ -239,7 +239,7 @@ Remove unnecessary suppression - Remove unnecessary suppression + Retirer la suppression inutile @@ -279,7 +279,7 @@ Simplify conditional expression - Simplify conditional expression + Simplifier l’expression conditionnelle @@ -334,7 +334,7 @@ Use '--' operator - Use '--' operator + Utiliser l'opérateur '--' @@ -344,7 +344,7 @@ Use '++' operator - Use '++' operator + Utiliser l'opérateur '++' diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.it.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.it.xlf index 8af798df2be17..469918fd1f917 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.it.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.it.xlf @@ -229,7 +229,7 @@ Remove redundant equality - Remove redundant equality + Rimuovi l'uguaglianza ridondante @@ -239,7 +239,7 @@ Remove unnecessary suppression - Remove unnecessary suppression + Rimuovere l'eliminazione non necessaria @@ -279,7 +279,7 @@ Simplify conditional expression - Simplify conditional expression + Semplifica l'espressione condizionale @@ -334,7 +334,7 @@ Use '--' operator - Use '--' operator + Usa l'operatore '--' @@ -344,7 +344,7 @@ Use '++' operator - Use '++' operator + Usa l'operatore '++' diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.ja.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.ja.xlf index 5ccb1539a1bb1..5bc4015737e53 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.ja.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.ja.xlf @@ -229,7 +229,7 @@ Remove redundant equality - Remove redundant equality + 冗長な等値を削除 @@ -239,7 +239,7 @@ Remove unnecessary suppression - Remove unnecessary suppression + 不要な抑制を削除します @@ -279,7 +279,7 @@ Simplify conditional expression - Simplify conditional expression + 条件式を簡略化する @@ -334,7 +334,7 @@ Use '--' operator - Use '--' operator + '--' 演算子を使用する @@ -344,7 +344,7 @@ Use '++' operator - Use '++' operator + '++' 演算子を使用する diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.ko.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.ko.xlf index 32c61d6ea2043..a1d00a47b5e80 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.ko.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.ko.xlf @@ -229,7 +229,7 @@ Remove redundant equality - Remove redundant equality + 중복 같음 제거 @@ -239,7 +239,7 @@ Remove unnecessary suppression - Remove unnecessary suppression + 불필요한 비표시 오류(Suppression) 제거 @@ -279,7 +279,7 @@ Simplify conditional expression - Simplify conditional expression + 조건식 단순화 @@ -334,7 +334,7 @@ Use '--' operator - Use '--' operator + '--' 연산자 사용 @@ -344,7 +344,7 @@ Use '++' operator - Use '++' operator + '++' 연산자 사용 diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.pl.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.pl.xlf index 766a4b42e47f8..25ec537b574e7 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.pl.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.pl.xlf @@ -229,7 +229,7 @@ Remove redundant equality - Remove redundant equality + Usuń nadmiarową równość @@ -239,7 +239,7 @@ Remove unnecessary suppression - Remove unnecessary suppression + Usuń niepotrzebne pomijanie @@ -279,7 +279,7 @@ Simplify conditional expression - Simplify conditional expression + Uprość wyrażenie warunkowe @@ -334,7 +334,7 @@ Use '--' operator - Use '--' operator + Użyj operatora „--” @@ -344,7 +344,7 @@ Use '++' operator - Use '++' operator + Użyj operatora „++” diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.pt-BR.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.pt-BR.xlf index 46b7e25016e97..7c7732413b918 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.pt-BR.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.pt-BR.xlf @@ -229,7 +229,7 @@ Remove redundant equality - Remove redundant equality + Remover a igualdade redundante @@ -239,7 +239,7 @@ Remove unnecessary suppression - Remove unnecessary suppression + Remover a supressão desnecessária @@ -279,7 +279,7 @@ Simplify conditional expression - Simplify conditional expression + Simplificar a expressão condicional @@ -334,7 +334,7 @@ Use '--' operator - Use '--' operator + Usar o operador '--' @@ -344,7 +344,7 @@ Use '++' operator - Use '++' operator + Usar o operador '++' diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.ru.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.ru.xlf index e76b6badc3d5d..401aaf53a3152 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.ru.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.ru.xlf @@ -229,7 +229,7 @@ Remove redundant equality - Remove redundant equality + Удалите лишнее равенство. @@ -239,7 +239,7 @@ Remove unnecessary suppression - Remove unnecessary suppression + Удалить ненужное подавление @@ -279,7 +279,7 @@ Simplify conditional expression - Simplify conditional expression + Упростить условное выражение @@ -334,7 +334,7 @@ Use '--' operator - Use '--' operator + Используйте оператор "--" @@ -344,7 +344,7 @@ Use '++' operator - Use '++' operator + Используйте оператор "++" diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.tr.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.tr.xlf index d0f40625428b7..8fd72a3746f7e 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.tr.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.tr.xlf @@ -219,7 +219,7 @@ Private property '{0}' can be converted to a method as its get accessor is never invoked. - {0}' özel özelliği, bu özelliğin get erişimcisi hiçbir zaman çağrılmadığı için bir yönteme dönüştürülebilir. + '{0}' özel özelliği, bu özelliğin get erişimcisi hiçbir zaman çağrılmadığı için bir yönteme dönüştürülebilir. @@ -229,7 +229,7 @@ Remove redundant equality - Remove redundant equality + Gereksiz eşitliği kaldır @@ -239,7 +239,7 @@ Remove unnecessary suppression - Remove unnecessary suppression + Gereksiz gizlemeyi kaldırın @@ -279,7 +279,7 @@ Simplify conditional expression - Simplify conditional expression + Koşullu ifadeyi basitleştir @@ -334,7 +334,7 @@ Use '--' operator - Use '--' operator + '--' operatörünü kullanın @@ -344,7 +344,7 @@ Use '++' operator - Use '++' operator + '++' operatörünü kullanın diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.zh-Hans.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.zh-Hans.xlf index 29182e074260a..e89e3e765d9c2 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.zh-Hans.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + A source file contains a header that does not match the required text @@ -159,7 +159,7 @@ Null check can be simplified - 可以简化 Null 检查。 + 可以简化 Null 检查 @@ -229,7 +229,7 @@ Remove redundant equality - Remove redundant equality + 删除冗余等同性 @@ -279,7 +279,7 @@ Simplify conditional expression - Simplify conditional expression + 简化条件表达式 @@ -334,7 +334,7 @@ Use '--' operator - Use '--' operator + 使用 "--" 运算符 @@ -344,7 +344,7 @@ Use '++' operator - Use '++' operator + 使用 "++" 运算符 diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.zh-Hant.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.zh-Hant.xlf index 199d74d422ec5..a5f3aae71a2c5 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.zh-Hant.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + A source file contains a header that does not match the required text @@ -229,7 +229,7 @@ Remove redundant equality - Remove redundant equality + 移除多餘的等號 @@ -239,7 +239,7 @@ Remove unnecessary suppression - Remove unnecessary suppression + 移除非必要的隱藏項目 @@ -279,7 +279,7 @@ Simplify conditional expression - Simplify conditional expression + 簡化條件運算式 @@ -334,7 +334,7 @@ Use '--' operator - Use '--' operator + 使用 '--' 運算子 @@ -344,7 +344,7 @@ Use '++' operator - Use '++' operator + 使用 '+ +' 運算子 diff --git a/src/Analyzers/Core/CodeFixes/SimplifyInterpolation/AbstractSimplifyInterpolationCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/SimplifyInterpolation/AbstractSimplifyInterpolationCodeFixProvider.cs index b68f34685bbbb..1c214116cd044 100644 --- a/src/Analyzers/Core/CodeFixes/SimplifyInterpolation/AbstractSimplifyInterpolationCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/SimplifyInterpolation/AbstractSimplifyInterpolationCodeFixProvider.cs @@ -23,12 +23,16 @@ internal abstract class AbstractSimplifyInterpolationCodeFixProvider< TExpressionSyntax, TInterpolationAlignmentClause, TInterpolationFormatClause, - TInterpolatedStringExpressionSyntax> : SyntaxEditorBasedCodeFixProvider + TInterpolatedStringExpressionSyntax, + TConditionalExpressionSyntax, + TParenthesizedExpressionSyntax> : SyntaxEditorBasedCodeFixProvider where TInterpolationSyntax : SyntaxNode where TExpressionSyntax : SyntaxNode where TInterpolationAlignmentClause : SyntaxNode where TInterpolationFormatClause : SyntaxNode where TInterpolatedStringExpressionSyntax : TExpressionSyntax + where TConditionalExpressionSyntax : TExpressionSyntax + where TParenthesizedExpressionSyntax : TExpressionSyntax { public override ImmutableArray FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.SimplifyInterpolationId); @@ -62,7 +66,7 @@ protected override async Task FixAllAsync( if (interpolation?.Syntax is TInterpolationSyntax interpolationSyntax && interpolationSyntax.Parent is TInterpolatedStringExpressionSyntax interpolatedString) { - Helpers.UnwrapInterpolation( + Helpers.UnwrapInterpolation( document.GetRequiredLanguageService(), document.GetRequiredLanguageService(), interpolation, out var unwrapped, out var alignment, out var negate, out var formatString, out _); diff --git a/src/Analyzers/Core/CodeFixes/xlf/CodeFixesResources.zh-Hans.xlf b/src/Analyzers/Core/CodeFixes/xlf/CodeFixesResources.zh-Hans.xlf index 0c5b0a89ae27a..383b01917a9ec 100644 --- a/src/Analyzers/Core/CodeFixes/xlf/CodeFixesResources.zh-Hans.xlf +++ b/src/Analyzers/Core/CodeFixes/xlf/CodeFixesResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Add both diff --git a/src/Analyzers/Core/CodeFixes/xlf/CodeFixesResources.zh-Hant.xlf b/src/Analyzers/Core/CodeFixes/xlf/CodeFixesResources.zh-Hant.xlf index ef664262e66bc..fa0ce5da94d41 100644 --- a/src/Analyzers/Core/CodeFixes/xlf/CodeFixesResources.zh-Hant.xlf +++ b/src/Analyzers/Core/CodeFixes/xlf/CodeFixesResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Add both diff --git a/src/Analyzers/VisualBasic/Analyzers/SimplifyInterpolation/VisualBasicSimplifyInterpolationDiagnosticAnalyzer.vb b/src/Analyzers/VisualBasic/Analyzers/SimplifyInterpolation/VisualBasicSimplifyInterpolationDiagnosticAnalyzer.vb index d9db8dc8cb266..b88ee1f3db3ae 100644 --- a/src/Analyzers/VisualBasic/Analyzers/SimplifyInterpolation/VisualBasicSimplifyInterpolationDiagnosticAnalyzer.vb +++ b/src/Analyzers/VisualBasic/Analyzers/SimplifyInterpolation/VisualBasicSimplifyInterpolationDiagnosticAnalyzer.vb @@ -13,7 +13,11 @@ Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.SimplifyInterpolation Friend Class VisualBasicSimplifyInterpolationDiagnosticAnalyzer - Inherits AbstractSimplifyInterpolationDiagnosticAnalyzer(Of InterpolationSyntax, ExpressionSyntax) + Inherits AbstractSimplifyInterpolationDiagnosticAnalyzer(Of + InterpolationSyntax, + ExpressionSyntax, + TernaryConditionalExpressionSyntax, + ParenthesizedExpressionSyntax) Protected Overrides Function GetVirtualCharService() As IVirtualCharService Return VisualBasicVirtualCharService.Instance diff --git a/src/Analyzers/VisualBasic/Analyzers/UseObjectInitializer/VisualBasicUseObjectInitializerDiagnosticAnalyzer.vb b/src/Analyzers/VisualBasic/Analyzers/UseObjectInitializer/VisualBasicUseObjectInitializerDiagnosticAnalyzer.vb index fe344a99e53a4..5f5dad08c996d 100644 --- a/src/Analyzers/VisualBasic/Analyzers/UseObjectInitializer/VisualBasicUseObjectInitializerDiagnosticAnalyzer.vb +++ b/src/Analyzers/VisualBasic/Analyzers/UseObjectInitializer/VisualBasicUseObjectInitializerDiagnosticAnalyzer.vb @@ -34,5 +34,9 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.UseObjectInitializer Protected Overrides Function GetSyntaxFacts() As ISyntaxFacts Return VisualBasicSyntaxFacts.Instance End Function + + Protected Overrides Function IsValidContainingStatement(node As StatementSyntax) As Boolean + Return True + End Function End Class End Namespace diff --git a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.cs.xlf b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.cs.xlf index 51f91614dbc35..7aed16da9d690 100644 --- a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.cs.xlf +++ b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.cs.xlf @@ -29,7 +29,7 @@ Use 'IsNot' expression - Use 'IsNot' expression + Použít výraz IsNot {locked: IsNot}This is a Visual Basic keyword and should not be localized or have its casing changed diff --git a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.de.xlf b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.de.xlf index 72423c50e92df..63d87b6def34e 100644 --- a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.de.xlf +++ b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.de.xlf @@ -4,7 +4,7 @@ 'GetType' can be converted to 'NameOf' - 'GetType' can be converted to 'NameOf' + "GetType" kann in "NameOf" konvertiert werden. @@ -19,7 +19,7 @@ 'ByVal' keyword is unnecessary and can be removed. - 'ByVal' keyword is unnecessary and can be removed. + Das ByVal-Schlüsselwort ist unnötig und kann entfernt werden. {locked: ByVal}This is a Visual Basic keyword and should not be localized or have its casing changed @@ -29,7 +29,7 @@ Use 'IsNot' expression - Use 'IsNot' expression + Ausdruck "IsNot" verwenden {locked: IsNot}This is a Visual Basic keyword and should not be localized or have its casing changed diff --git a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.es.xlf b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.es.xlf index feb7e5f67ddbb..57e1fe2784cc8 100644 --- a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.es.xlf +++ b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.es.xlf @@ -4,7 +4,7 @@ 'GetType' can be converted to 'NameOf' - 'GetType' can be converted to 'NameOf' + "GetType" puede convertirse en "NameOf" @@ -19,7 +19,7 @@ 'ByVal' keyword is unnecessary and can be removed. - 'ByVal' keyword is unnecessary and can be removed. + La palabra clave "ByVal" no es necesaria y se puede quitar. {locked: ByVal}This is a Visual Basic keyword and should not be localized or have its casing changed @@ -29,7 +29,7 @@ Use 'IsNot' expression - Use 'IsNot' expression + Usar la expresión "IsNot" {locked: IsNot}This is a Visual Basic keyword and should not be localized or have its casing changed diff --git a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.fr.xlf b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.fr.xlf index 03c96c0d21b3b..b35686fb49a03 100644 --- a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.fr.xlf +++ b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.fr.xlf @@ -4,7 +4,7 @@ 'GetType' can be converted to 'NameOf' - 'GetType' can be converted to 'NameOf' + 'GetType' peut être converti en 'NameOf' @@ -19,7 +19,7 @@ 'ByVal' keyword is unnecessary and can be removed. - 'ByVal' keyword is unnecessary and can be removed. + Le mot clé 'ByVal' est inutile et peut être supprimé. {locked: ByVal}This is a Visual Basic keyword and should not be localized or have its casing changed @@ -29,7 +29,7 @@ Use 'IsNot' expression - Use 'IsNot' expression + Utiliser l'expression 'IsNot' {locked: IsNot}This is a Visual Basic keyword and should not be localized or have its casing changed diff --git a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.it.xlf b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.it.xlf index faf223c24e4a3..0139c32109f91 100644 --- a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.it.xlf +++ b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.it.xlf @@ -4,7 +4,7 @@ 'GetType' can be converted to 'NameOf' - 'GetType' can be converted to 'NameOf' + 'GetType' può essere convertito in 'NameOf' @@ -19,7 +19,7 @@ 'ByVal' keyword is unnecessary and can be removed. - 'ByVal' keyword is unnecessary and can be removed. + La parola chiave 'ByVal' non è necessaria e può essere rimossa. {locked: ByVal}This is a Visual Basic keyword and should not be localized or have its casing changed @@ -29,7 +29,7 @@ Use 'IsNot' expression - Use 'IsNot' expression + Usa l'espressione 'IsNot' {locked: IsNot}This is a Visual Basic keyword and should not be localized or have its casing changed diff --git a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.ja.xlf b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.ja.xlf index 936968aea0bf4..c0e2f334e81b2 100644 --- a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.ja.xlf +++ b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.ja.xlf @@ -4,7 +4,7 @@ 'GetType' can be converted to 'NameOf' - 'GetType' can be converted to 'NameOf' + 'GetType' を 'NameOf' に変換できます @@ -19,7 +19,7 @@ 'ByVal' keyword is unnecessary and can be removed. - 'ByVal' keyword is unnecessary and can be removed. + 'ByVal' キーワードは必要ありません。削除することができます。 {locked: ByVal}This is a Visual Basic keyword and should not be localized or have its casing changed @@ -29,7 +29,7 @@ Use 'IsNot' expression - Use 'IsNot' expression + 'IsNot' 式を使用する {locked: IsNot}This is a Visual Basic keyword and should not be localized or have its casing changed diff --git a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.ko.xlf b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.ko.xlf index d41fe4bdd9886..8bd041a14cf53 100644 --- a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.ko.xlf +++ b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.ko.xlf @@ -4,7 +4,7 @@ 'GetType' can be converted to 'NameOf' - 'GetType' can be converted to 'NameOf' + 'GetType'을 'NameOf'로 변환할 수 없습니다. @@ -19,7 +19,7 @@ 'ByVal' keyword is unnecessary and can be removed. - 'ByVal' keyword is unnecessary and can be removed. + 'ByVal' 키워드는 불필요하며 제거할 수 있습니다. {locked: ByVal}This is a Visual Basic keyword and should not be localized or have its casing changed @@ -29,7 +29,7 @@ Use 'IsNot' expression - Use 'IsNot' expression + 'IsNot' 식 사용 {locked: IsNot}This is a Visual Basic keyword and should not be localized or have its casing changed diff --git a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.pl.xlf b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.pl.xlf index 4e66c11497cc7..81be8dd4c48b8 100644 --- a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.pl.xlf +++ b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.pl.xlf @@ -4,7 +4,7 @@ 'GetType' can be converted to 'NameOf' - 'GetType' can be converted to 'NameOf' + Element „GetType” można przekonwertować na element „NameOf” @@ -19,7 +19,7 @@ 'ByVal' keyword is unnecessary and can be removed. - 'ByVal' keyword is unnecessary and can be removed. + Słowo kluczowe „ByVal” jest niepotrzebne i można je usunąć. {locked: ByVal}This is a Visual Basic keyword and should not be localized or have its casing changed @@ -29,7 +29,7 @@ Use 'IsNot' expression - Use 'IsNot' expression + Użyj wyrażenia „IsNot” {locked: IsNot}This is a Visual Basic keyword and should not be localized or have its casing changed diff --git a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.pt-BR.xlf b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.pt-BR.xlf index c988addaa7311..f17e36330f71f 100644 --- a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.pt-BR.xlf +++ b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.pt-BR.xlf @@ -4,7 +4,7 @@ 'GetType' can be converted to 'NameOf' - 'GetType' can be converted to 'NameOf' + 'GetType' pode ser convertido em 'NameOf' @@ -19,7 +19,7 @@ 'ByVal' keyword is unnecessary and can be removed. - 'ByVal' keyword is unnecessary and can be removed. + A palavra-chave 'ByVal' é desnecessária e pode ser removida. {locked: ByVal}This is a Visual Basic keyword and should not be localized or have its casing changed @@ -29,7 +29,7 @@ Use 'IsNot' expression - Use 'IsNot' expression + Usar a expressão 'IsNot' {locked: IsNot}This is a Visual Basic keyword and should not be localized or have its casing changed diff --git a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.ru.xlf b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.ru.xlf index f87f106cbe3d7..fb3b6dcade26f 100644 --- a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.ru.xlf +++ b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.ru.xlf @@ -4,7 +4,7 @@ 'GetType' can be converted to 'NameOf' - 'GetType' can be converted to 'NameOf' + "GetType" можно преобразовать в "NameOf". @@ -19,7 +19,7 @@ 'ByVal' keyword is unnecessary and can be removed. - 'ByVal' keyword is unnecessary and can be removed. + Ключевое слово "ByVal" является необязательным и может быть удалено. {locked: ByVal}This is a Visual Basic keyword and should not be localized or have its casing changed @@ -29,7 +29,7 @@ Use 'IsNot' expression - Use 'IsNot' expression + Использовать выражение IsNot {locked: IsNot}This is a Visual Basic keyword and should not be localized or have its casing changed diff --git a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.tr.xlf b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.tr.xlf index 48f847b5f0a06..7473a7934ba20 100644 --- a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.tr.xlf +++ b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.tr.xlf @@ -4,7 +4,7 @@ 'GetType' can be converted to 'NameOf' - 'GetType' can be converted to 'NameOf' + 'GetType' metodu, 'NameOf' metoduna dönüştürülebilir @@ -19,7 +19,7 @@ 'ByVal' keyword is unnecessary and can be removed. - 'ByVal' keyword is unnecessary and can be removed. + 'ByVal' anahtar sözcüğü gereksizdir ve kaldırılabilir. {locked: ByVal}This is a Visual Basic keyword and should not be localized or have its casing changed @@ -29,7 +29,7 @@ Use 'IsNot' expression - Use 'IsNot' expression + 'IsNot' ifadesini kullanın {locked: IsNot}This is a Visual Basic keyword and should not be localized or have its casing changed diff --git a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.zh-Hans.xlf b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.zh-Hans.xlf index eaefa292397a2..ef3f1ecbba88b 100644 --- a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.zh-Hans.xlf +++ b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + 'GetType' can be converted to 'NameOf' @@ -29,7 +29,7 @@ Use 'IsNot' expression - Use 'IsNot' expression + 使用 "IsNot" 表达式 {locked: IsNot}This is a Visual Basic keyword and should not be localized or have its casing changed diff --git a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.zh-Hant.xlf b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.zh-Hant.xlf index 97d79958c5d19..9f35b6156f40d 100644 --- a/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.zh-Hant.xlf +++ b/src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.zh-Hant.xlf @@ -1,10 +1,10 @@  - + 'GetType' can be converted to 'NameOf' - 'GetType' can be converted to 'NameOf' + 'GetType' 可轉換為 'NameOf' @@ -19,7 +19,7 @@ 'ByVal' keyword is unnecessary and can be removed. - 'ByVal' keyword is unnecessary and can be removed. + 'ByVal' 關鍵字非必要,可以移除。 {locked: ByVal}This is a Visual Basic keyword and should not be localized or have its casing changed @@ -29,7 +29,7 @@ Use 'IsNot' expression - Use 'IsNot' expression + 使用 'IsNot' 運算式 {locked: IsNot}This is a Visual Basic keyword and should not be localized or have its casing changed diff --git a/src/Analyzers/VisualBasic/CodeFixes/SimplifyInterpolation/VisualBasicSimplifyInterpolationCodeFixProvider.vb b/src/Analyzers/VisualBasic/CodeFixes/SimplifyInterpolation/VisualBasicSimplifyInterpolationCodeFixProvider.vb index 7fec35d7ca1e9..ebbdd5712afe9 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/SimplifyInterpolation/VisualBasicSimplifyInterpolationCodeFixProvider.vb +++ b/src/Analyzers/VisualBasic/CodeFixes/SimplifyInterpolation/VisualBasicSimplifyInterpolationCodeFixProvider.vb @@ -13,7 +13,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.SimplifyInterpolation Friend Class VisualBasicSimplifyInterpolationCodeFixProvider Inherits AbstractSimplifyInterpolationCodeFixProvider(Of InterpolationSyntax, ExpressionSyntax, InterpolationAlignmentClauseSyntax, - InterpolationFormatClauseSyntax, InterpolatedStringExpressionSyntax) + InterpolationFormatClauseSyntax, InterpolatedStringExpressionSyntax, + TernaryConditionalExpressionSyntax, ParenthesizedExpressionSyntax) diff --git a/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.de.xlf b/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.de.xlf index 705d6f0da22b6..b5860ad1418f1 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.de.xlf +++ b/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.de.xlf @@ -9,7 +9,7 @@ Convert 'GetType' to 'NameOf' - Convert 'GetType' to 'NameOf' + "GetType" in "NameOf" konvertieren diff --git a/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.es.xlf b/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.es.xlf index 6df1179924ea6..1173f00588dea 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.es.xlf +++ b/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.es.xlf @@ -9,7 +9,7 @@ Convert 'GetType' to 'NameOf' - Convert 'GetType' to 'NameOf' + Convertir "GetType" en "NameOf" diff --git a/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.fr.xlf b/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.fr.xlf index ca23e041c1d96..0331570831ce5 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.fr.xlf +++ b/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.fr.xlf @@ -9,7 +9,7 @@ Convert 'GetType' to 'NameOf' - Convert 'GetType' to 'NameOf' + Convertir 'GetType' en 'NameOf' diff --git a/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.it.xlf b/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.it.xlf index d1e8f3ad15d90..0821f2420fde3 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.it.xlf +++ b/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.it.xlf @@ -9,7 +9,7 @@ Convert 'GetType' to 'NameOf' - Convert 'GetType' to 'NameOf' + Convertire 'GetType' in 'NameOf' diff --git a/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.ja.xlf b/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.ja.xlf index 043786610fe85..99c4d80c9f4fb 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.ja.xlf +++ b/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.ja.xlf @@ -9,7 +9,7 @@ Convert 'GetType' to 'NameOf' - Convert 'GetType' to 'NameOf' + 'GetType' を 'NameOf' に変換します diff --git a/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.ko.xlf b/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.ko.xlf index 0d8a3ad9286eb..c75af0f32aa15 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.ko.xlf +++ b/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.ko.xlf @@ -9,7 +9,7 @@ Convert 'GetType' to 'NameOf' - Convert 'GetType' to 'NameOf' + 'GetType'을 'NameOf'로 변환 diff --git a/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.pl.xlf b/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.pl.xlf index 609ec7b5e2d8d..5e69cb9f7e4de 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.pl.xlf +++ b/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.pl.xlf @@ -9,7 +9,7 @@ Convert 'GetType' to 'NameOf' - Convert 'GetType' to 'NameOf' + Konwertuj element „GetType” na element „NameOf” diff --git a/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.pt-BR.xlf b/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.pt-BR.xlf index deece595f6553..e1c9a969ee748 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.pt-BR.xlf +++ b/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.pt-BR.xlf @@ -9,7 +9,7 @@ Convert 'GetType' to 'NameOf' - Convert 'GetType' to 'NameOf' + Converter 'GetType' em 'NameOf' diff --git a/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.ru.xlf b/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.ru.xlf index 5068b811610cf..c506aff4a1480 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.ru.xlf +++ b/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.ru.xlf @@ -4,12 +4,12 @@ Add 'Me.' - Добавьте "'Me". + Добавьте "Me". Convert 'GetType' to 'NameOf' - Convert 'GetType' to 'NameOf' + Преобразовать "GetType" в "NameOf" diff --git a/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.tr.xlf b/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.tr.xlf index 5c01bf6de2b5b..21ba41a702369 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.tr.xlf +++ b/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.tr.xlf @@ -9,7 +9,7 @@ Convert 'GetType' to 'NameOf' - Convert 'GetType' to 'NameOf' + 'GetType' metodunu 'NameOf' metoduna dönüştürün diff --git a/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.zh-Hans.xlf b/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.zh-Hans.xlf index baec379a402f7..cd3d6d9832046 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.zh-Hans.xlf +++ b/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Add 'Me.' diff --git a/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.zh-Hant.xlf b/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.zh-Hant.xlf index 69ba167a685e7..f957123b3479d 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.zh-Hant.xlf +++ b/src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Add 'Me.' @@ -9,7 +9,7 @@ Convert 'GetType' to 'NameOf' - Convert 'GetType' to 'NameOf' + 將 'GetType' 轉換為 'NameOf' diff --git a/src/CodeStyle/CSharp/Analyzers/xlf/CSharpCodeStyleResources.zh-Hans.xlf b/src/CodeStyle/CSharp/Analyzers/xlf/CSharpCodeStyleResources.zh-Hans.xlf index 1a9702dd40ad3..aaf0f4a2e371f 100644 --- a/src/CodeStyle/CSharp/Analyzers/xlf/CSharpCodeStyleResources.zh-Hans.xlf +++ b/src/CodeStyle/CSharp/Analyzers/xlf/CSharpCodeStyleResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Indentation preferences diff --git a/src/CodeStyle/CSharp/Analyzers/xlf/CSharpCodeStyleResources.zh-Hant.xlf b/src/CodeStyle/CSharp/Analyzers/xlf/CSharpCodeStyleResources.zh-Hant.xlf index 0135365fa24e6..a057736ccbba5 100644 --- a/src/CodeStyle/CSharp/Analyzers/xlf/CSharpCodeStyleResources.zh-Hant.xlf +++ b/src/CodeStyle/CSharp/Analyzers/xlf/CSharpCodeStyleResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Indentation preferences diff --git a/src/CodeStyle/CSharp/CodeFixes/xlf/CSharpCodeStyleFixesResources.zh-Hans.xlf b/src/CodeStyle/CSharp/CodeFixes/xlf/CSharpCodeStyleFixesResources.zh-Hans.xlf index be6877b951bb0..97b64549dd6e4 100644 --- a/src/CodeStyle/CSharp/CodeFixes/xlf/CSharpCodeStyleFixesResources.zh-Hans.xlf +++ b/src/CodeStyle/CSharp/CodeFixes/xlf/CSharpCodeStyleFixesResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Remove this value when another is added. diff --git a/src/CodeStyle/CSharp/CodeFixes/xlf/CSharpCodeStyleFixesResources.zh-Hant.xlf b/src/CodeStyle/CSharp/CodeFixes/xlf/CSharpCodeStyleFixesResources.zh-Hant.xlf index 8daad74a19618..e24860e761093 100644 --- a/src/CodeStyle/CSharp/CodeFixes/xlf/CSharpCodeStyleFixesResources.zh-Hant.xlf +++ b/src/CodeStyle/CSharp/CodeFixes/xlf/CSharpCodeStyleFixesResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Remove this value when another is added. diff --git a/src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.ja.xlf b/src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.ja.xlf index 3e5cc2ae67715..0b2d0dba0f88a 100644 --- a/src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.ja.xlf +++ b/src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.ja.xlf @@ -24,7 +24,7 @@ Deserialization reader for '{0}' read incorrect number of values. - {0}' の逆シリアル化のリーダーが、正しくない数の値を読み取りました。 + '{0}' の逆シリアル化のリーダーが、正しくない数の値を読み取りました。 diff --git a/src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.ko.xlf b/src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.ko.xlf index e8a94c83918dc..e52f4f1214482 100644 --- a/src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.ko.xlf +++ b/src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.ko.xlf @@ -19,12 +19,12 @@ Cannot serialize type '{0}'. - {0}' 형식을 직렬화할 수 없습니다. + '{0}' 형식을 직렬화할 수 없습니다. Deserialization reader for '{0}' read incorrect number of values. - {0}'에 대한 역직렬화 판독기가 잘못된 숫자 값을 읽습니다. + '{0}'에 대한 역직렬화 판독기가 잘못된 숫자 값을 읽습니다. diff --git a/src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.tr.xlf b/src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.tr.xlf index 957cd9aca8dd0..885ee6bc34af9 100644 --- a/src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.tr.xlf +++ b/src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.tr.xlf @@ -19,12 +19,12 @@ Cannot serialize type '{0}'. - {0}' türü seri hale getirilemiyor. + '{0}' türü seri hale getirilemiyor. Deserialization reader for '{0}' read incorrect number of values. - {0}' türünün seri durumdan çıkarma okuyucusu, yanlış sayıda değer okudu. + '{0}' türünün seri durumdan çıkarma okuyucusu, yanlış sayıda değer okudu. @@ -69,7 +69,7 @@ The type '{0}' is not understood by the serialization binder. - {0}' türü, serileştirme bağlayıcısı tarafından anlaşılamıyor. + '{0}' türü, serileştirme bağlayıcısı tarafından anlaşılamıyor. diff --git a/src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.zh-Hans.xlf b/src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.zh-Hans.xlf index 4ebf61b0e734d..3b19fe18a4303 100644 --- a/src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.zh-Hans.xlf +++ b/src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + A language name cannot be specified for this option. diff --git a/src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.zh-Hant.xlf b/src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.zh-Hant.xlf index 314e425ff1bfb..121f1af72e4dd 100644 --- a/src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.zh-Hant.xlf +++ b/src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + A language name cannot be specified for this option. @@ -24,7 +24,7 @@ Deserialization reader for '{0}' read incorrect number of values. - {0}' 的還原序列化讀取器所讀取的值數目不正確。 + '{0}' 的還原序列化讀取器所讀取的值數目不正確。 diff --git a/src/CodeStyle/Core/CodeFixes/xlf/CodeStyleFixesResources.zh-Hans.xlf b/src/CodeStyle/Core/CodeFixes/xlf/CodeStyleFixesResources.zh-Hans.xlf index 1a6295ceca776..3f8ef3ceb7cef 100644 --- a/src/CodeStyle/Core/CodeFixes/xlf/CodeStyleFixesResources.zh-Hans.xlf +++ b/src/CodeStyle/Core/CodeFixes/xlf/CodeStyleFixesResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Remove this value when another is added. diff --git a/src/CodeStyle/Core/CodeFixes/xlf/CodeStyleFixesResources.zh-Hant.xlf b/src/CodeStyle/Core/CodeFixes/xlf/CodeStyleFixesResources.zh-Hant.xlf index 47e57451acb6b..f9b289510af34 100644 --- a/src/CodeStyle/Core/CodeFixes/xlf/CodeStyleFixesResources.zh-Hant.xlf +++ b/src/CodeStyle/Core/CodeFixes/xlf/CodeStyleFixesResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Remove this value when another is added. diff --git a/src/CodeStyle/VisualBasic/Analyzers/xlf/VBCodeStyleResources.zh-Hans.xlf b/src/CodeStyle/VisualBasic/Analyzers/xlf/VBCodeStyleResources.zh-Hans.xlf index 37d7c99d03180..b2a7b5aa1506d 100644 --- a/src/CodeStyle/VisualBasic/Analyzers/xlf/VBCodeStyleResources.zh-Hans.xlf +++ b/src/CodeStyle/VisualBasic/Analyzers/xlf/VBCodeStyleResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Remove this value when another is added. diff --git a/src/CodeStyle/VisualBasic/Analyzers/xlf/VBCodeStyleResources.zh-Hant.xlf b/src/CodeStyle/VisualBasic/Analyzers/xlf/VBCodeStyleResources.zh-Hant.xlf index 2f99525762e7a..128897fcd74fa 100644 --- a/src/CodeStyle/VisualBasic/Analyzers/xlf/VBCodeStyleResources.zh-Hant.xlf +++ b/src/CodeStyle/VisualBasic/Analyzers/xlf/VBCodeStyleResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Remove this value when another is added. diff --git a/src/CodeStyle/VisualBasic/CodeFixes/xlf/VBCodeStyleFixesResources.zh-Hans.xlf b/src/CodeStyle/VisualBasic/CodeFixes/xlf/VBCodeStyleFixesResources.zh-Hans.xlf index 37da7ae8e7ea4..6c44c29b32f70 100644 --- a/src/CodeStyle/VisualBasic/CodeFixes/xlf/VBCodeStyleFixesResources.zh-Hans.xlf +++ b/src/CodeStyle/VisualBasic/CodeFixes/xlf/VBCodeStyleFixesResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Remove this value when another is added. diff --git a/src/CodeStyle/VisualBasic/CodeFixes/xlf/VBCodeStyleFixesResources.zh-Hant.xlf b/src/CodeStyle/VisualBasic/CodeFixes/xlf/VBCodeStyleFixesResources.zh-Hant.xlf index ecb8712ecf42d..ede487b803def 100644 --- a/src/CodeStyle/VisualBasic/CodeFixes/xlf/VBCodeStyleFixesResources.zh-Hant.xlf +++ b/src/CodeStyle/VisualBasic/CodeFixes/xlf/VBCodeStyleFixesResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Remove this value when another is added. diff --git a/src/Compilers/CSharp/Portable/Binder/Binder.ValueChecks.cs b/src/Compilers/CSharp/Portable/Binder/Binder.ValueChecks.cs index 251c849c2878a..3b39a6a2d4e4c 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder.ValueChecks.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder.ValueChecks.cs @@ -169,6 +169,61 @@ private static bool RequiresRefOrOut(BindValueKind kind) return (kind & BindValueKind.RefOrOut) == BindValueKind.RefOrOut; } +#nullable enable + + private BoundIndexerAccess BindIndexerDefaultArguments(BoundIndexerAccess indexerAccess, BindValueKind valueKind, DiagnosticBag diagnostics) + { + var useSetAccessor = valueKind == BindValueKind.Assignable && !indexerAccess.Indexer.ReturnsByRef; + var accessorForDefaultArguments = useSetAccessor + ? indexerAccess.Indexer.GetOwnOrInheritedSetMethod() + : indexerAccess.Indexer.GetOwnOrInheritedGetMethod(); + if (accessorForDefaultArguments is not null) + { + var argumentsBuilder = ArrayBuilder.GetInstance(accessorForDefaultArguments.ParameterCount); + argumentsBuilder.AddRange(indexerAccess.Arguments); + + ArrayBuilder? refKindsBuilderOpt; + if (!indexerAccess.ArgumentRefKindsOpt.IsDefaultOrEmpty) + { + refKindsBuilderOpt = ArrayBuilder.GetInstance(accessorForDefaultArguments.ParameterCount); + refKindsBuilderOpt.AddRange(indexerAccess.ArgumentRefKindsOpt); + } + else + { + refKindsBuilderOpt = null; + } + var argsToParams = indexerAccess.ArgsToParamsOpt; + + // It is possible for the indexer 'value' parameter from metadata to have a default value, but the compiler will not use it. + // However, we may still use any default values from the preceding parameters. + var parameters = accessorForDefaultArguments.Parameters; + if (useSetAccessor) + { + parameters = parameters.RemoveAt(parameters.Length - 1); + } + Debug.Assert(parameters.Length == indexerAccess.Indexer.Parameters.Length); + BindDefaultArguments(indexerAccess.Syntax, parameters, argumentsBuilder, refKindsBuilderOpt, ref argsToParams, out var defaultArguments, indexerAccess.Expanded, enableCallerInfo: true, diagnostics); + + indexerAccess = indexerAccess.Update( + indexerAccess.ReceiverOpt, + indexerAccess.Indexer, + argumentsBuilder.ToImmutableAndFree(), + indexerAccess.ArgumentNamesOpt, + refKindsBuilderOpt?.ToImmutableOrNull() ?? default, + indexerAccess.Expanded, + argsToParams, + defaultArguments, + indexerAccess.BinderOpt, + indexerAccess.Type); + + refKindsBuilderOpt?.Free(); + } + + return indexerAccess; + } + +#nullable disable + /// /// Check the expression is of the required lvalue and rvalue specified by valueKind. /// The method returns the original expression if the expression is of the required @@ -182,6 +237,10 @@ private BoundExpression CheckValue(BoundExpression expr, BindValueKind valueKind { case BoundKind.PropertyGroup: expr = BindIndexedPropertyAccess((BoundPropertyGroup)expr, mustHaveAllOptionalParameters: false, diagnostics: diagnostics); + if (expr is BoundIndexerAccess indexerAccess) + { + expr = BindIndexerDefaultArguments(indexerAccess, valueKind, diagnostics); + } break; case BoundKind.Local: @@ -198,15 +257,7 @@ private BoundExpression CheckValue(BoundExpression expr, BindValueKind valueKind return expr; case BoundKind.IndexerAccess: - { - // Assigning to a non ref return indexer needs to set 'useSetterForDefaultArgumentGeneration' to true. - // This is for IOperation purpose. - var indexerAccess = (BoundIndexerAccess)expr; - if (valueKind == BindValueKind.Assignable && !indexerAccess.Indexer.ReturnsByRef) - { - expr = indexerAccess.Update(useSetterForDefaultArgumentGeneration: true); - } - } + expr = BindIndexerDefaultArguments((BoundIndexerAccess)expr, valueKind, diagnostics); break; case BoundKind.UnconvertedObjectCreationExpression: diff --git a/src/Compilers/CSharp/Portable/Binder/Binder.cs b/src/Compilers/CSharp/Portable/Binder/Binder.cs index 630406496854e..ecebb6640f181 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder.cs @@ -251,10 +251,6 @@ internal bool AreNullableAnnotationsEnabled(SyntaxTree syntaxTree, int position) internal bool AreNullableAnnotationsEnabled(SyntaxToken token) { RoslynDebug.Assert(token.SyntaxTree is object); - if ((Flags & BinderFlags.IgnoreNullableContext) != 0) - { - return false; - } return AreNullableAnnotationsEnabled(token.SyntaxTree, token.SpanStart); } diff --git a/src/Compilers/CSharp/Portable/Binder/BinderFlags.cs b/src/Compilers/CSharp/Portable/Binder/BinderFlags.cs index 225f3af98d981..a786f219dbe6d 100644 --- a/src/Compilers/CSharp/Portable/Binder/BinderFlags.cs +++ b/src/Compilers/CSharp/Portable/Binder/BinderFlags.cs @@ -113,9 +113,10 @@ internal enum BinderFlags : uint InEEMethodBinder = 1 << 30, /// - /// Assume '#nullable disable' context. + /// Skip binding type arguments (we use instead). + /// For example, currently used when type constraints are bound in some scenarios. /// - IgnoreNullableContext = 1u << 31, + SuppressTypeArgumentBinding = 1u << 31, // Groups diff --git a/src/Compilers/CSharp/Portable/Binder/Binder_Constraints.cs b/src/Compilers/CSharp/Portable/Binder/Binder_Constraints.cs index 0b5148f1419c3..da38ec1659837 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder_Constraints.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder_Constraints.cs @@ -25,9 +25,8 @@ internal ImmutableArray BindTypeParameterConstrai ImmutableArray typeParameters, TypeParameterListSyntax typeParameterList, SyntaxList clauses, - bool canIgnoreNullableContext, - ref IReadOnlyDictionary isValueTypeOverride, DiagnosticBag diagnostics, + bool performOnlyCycleSafeValidation, bool isForOverride = false) { Debug.Assert(this.Flags.Includes(BinderFlags.GenericConstraintsClause)); @@ -66,8 +65,7 @@ internal ImmutableArray BindTypeParameterConstrai Debug.Assert(ordinal >= 0); Debug.Assert(ordinal < n); - (TypeParameterConstraintClause constraintClause, ArrayBuilder? typeConstraintNodes) = - this.BindTypeParameterConstraints(typeParameterList.Parameters[ordinal], clause, isForOverride, canIgnoreNullableContext: canIgnoreNullableContext, diagnostics); + (TypeParameterConstraintClause constraintClause, ArrayBuilder? typeConstraintNodes) = this.BindTypeParameterConstraints(typeParameterList.Parameters[ordinal], clause, isForOverride, diagnostics); if (results[ordinal] == null) { results[ordinal] = constraintClause; @@ -101,9 +99,7 @@ internal ImmutableArray BindTypeParameterConstrai } } - TypeParameterConstraintClause.AdjustConstraintTypes(containingSymbol, typeParameters, results, ref isValueTypeOverride); - - RemoveInvalidConstraints(typeParameters, results!, syntaxNodes, diagnostics); + RemoveInvalidConstraints(typeParameters, results!, syntaxNodes, performOnlyCycleSafeValidation, diagnostics); foreach (var typeConstraintsSyntaxes in syntaxNodes) { @@ -118,8 +114,7 @@ internal ImmutableArray BindTypeParameterConstrai /// /// Bind and return a single type parameter constraint clause along with syntax nodes corresponding to type constraints. /// - private (TypeParameterConstraintClause, ArrayBuilder?) BindTypeParameterConstraints( - TypeParameterSyntax typeParameterSyntax, TypeParameterConstraintClauseSyntax constraintClauseSyntax, bool isForOverride, bool canIgnoreNullableContext, DiagnosticBag diagnostics) + private (TypeParameterConstraintClause, ArrayBuilder?) BindTypeParameterConstraints(TypeParameterSyntax typeParameterSyntax, TypeParameterConstraintClauseSyntax constraintClauseSyntax, bool isForOverride, DiagnosticBag diagnostics) { var constraints = TypeParameterConstraintKind.None; ArrayBuilder? constraintTypes = null; @@ -309,7 +304,7 @@ internal ImmutableArray BindTypeParameterConstrai Debug.Assert(!isForOverride || (constraints & (TypeParameterConstraintKind.ReferenceType | TypeParameterConstraintKind.ValueType)) != (TypeParameterConstraintKind.ReferenceType | TypeParameterConstraintKind.ValueType)); - return (TypeParameterConstraintClause.Create(constraints, constraintTypes?.ToImmutableAndFree() ?? ImmutableArray.Empty, canIgnoreNullableContext), syntaxBuilder); + return (TypeParameterConstraintClause.Create(constraints, constraintTypes?.ToImmutableAndFree() ?? ImmutableArray.Empty), syntaxBuilder); static void reportOverrideWithConstraints(ref bool reportedOverrideWithConstraints, TypeParameterConstraintSyntax syntax, DiagnosticBag diagnostics) { @@ -350,6 +345,7 @@ private static void RemoveInvalidConstraints( ImmutableArray typeParameters, ArrayBuilder constraintClauses, ArrayBuilder?> syntaxNodes, + bool performOnlyCycleSafeValidation, DiagnosticBag diagnostics) { Debug.Assert(typeParameters.Length > 0); @@ -357,7 +353,7 @@ private static void RemoveInvalidConstraints( int n = typeParameters.Length; for (int i = 0; i < n; i++) { - constraintClauses[i] = RemoveInvalidConstraints(typeParameters[i], constraintClauses[i], syntaxNodes[i], diagnostics); + constraintClauses[i] = RemoveInvalidConstraints(typeParameters[i], constraintClauses[i], syntaxNodes[i], performOnlyCycleSafeValidation, diagnostics); } } @@ -365,6 +361,7 @@ private static TypeParameterConstraintClause RemoveInvalidConstraints( TypeParameterSymbol typeParameter, TypeParameterConstraintClause constraintClause, ArrayBuilder? syntaxNodesOpt, + bool performOnlyCycleSafeValidation, DiagnosticBag diagnostics) { if (syntaxNodesOpt != null) @@ -383,16 +380,20 @@ private static TypeParameterConstraintClause RemoveInvalidConstraints( // since, in general, it may be difficult to support all invalid types. // In the future, we may want to include some invalid types // though so the public binding API has the most information. - if (IsValidConstraint(typeParameter.Name, syntax, constraintType, constraintClause.Constraints, constraintTypeBuilder, diagnostics)) + if (IsValidConstraint(typeParameter, syntax, constraintType, constraintClause.Constraints, constraintTypeBuilder, performOnlyCycleSafeValidation, diagnostics)) { - CheckConstraintTypeVisibility(containingSymbol, syntax.Location, constraintType, diagnostics); + if (!performOnlyCycleSafeValidation) + { + CheckConstraintTypeVisibility(containingSymbol, syntax.Location, constraintType, diagnostics); + } + constraintTypeBuilder.Add(constraintType); } } if (constraintTypeBuilder.Count < n) { - return TypeParameterConstraintClause.Create(constraintClause.Constraints, constraintTypeBuilder.ToImmutableAndFree(), constraintClause.IgnoresNullableContext); + return TypeParameterConstraintClause.Create(constraintClause.Constraints, constraintTypeBuilder.ToImmutableAndFree()); } constraintTypeBuilder.Free(); @@ -421,26 +422,28 @@ private static void CheckConstraintTypeVisibility( /// returns false and generates a diagnostic. /// private static bool IsValidConstraint( - string typeParameterName, + TypeParameterSymbol typeParameter, TypeConstraintSyntax syntax, TypeWithAnnotations type, TypeParameterConstraintKind constraints, ArrayBuilder constraintTypes, + bool performOnlyCycleSafeValidation, DiagnosticBag diagnostics) { - if (!isValidConstraintType(syntax, type, diagnostics)) + if (!isValidConstraintType(typeParameter, syntax, type, performOnlyCycleSafeValidation, diagnostics)) { return false; } - if (constraintTypes.Contains(c => type.Equals(c, TypeCompareKind.AllIgnoreOptions))) + if (!performOnlyCycleSafeValidation && constraintTypes.Contains(c => type.Equals(c, TypeCompareKind.AllIgnoreOptions))) { // "Duplicate constraint '{0}' for type parameter '{1}'" - Error(diagnostics, ErrorCode.ERR_DuplicateBound, syntax, type.Type.SetUnknownNullabilityForReferenceTypes(), typeParameterName); + Error(diagnostics, ErrorCode.ERR_DuplicateBound, syntax, type.Type.SetUnknownNullabilityForReferenceTypes(), typeParameter.Name); return false; } - if (type.TypeKind == TypeKind.Class) + if (!type.DefaultType.IsTypeParameter() && // Doing an explicit check for type parameter on unresolved type to avoid cycles while calculating TypeKind. An unresolved type parameter cannot resolve to a class. + type.TypeKind == TypeKind.Class) { // If there is already a struct or class constraint (class constraint could be // 'class' or explicit type), report an error and drop this class. If we don't @@ -489,8 +492,14 @@ private static bool IsValidConstraint( // Returns true if the type is a valid constraint type. // Otherwise returns false and generates a diagnostic. - static bool isValidConstraintType(TypeConstraintSyntax syntax, TypeWithAnnotations typeWithAnnotations, DiagnosticBag diagnostics) + static bool isValidConstraintType(TypeParameterSymbol typeParameter, TypeConstraintSyntax syntax, TypeWithAnnotations typeWithAnnotations, bool performOnlyCycleSafeValidation, DiagnosticBag diagnostics) { + if (typeWithAnnotations.NullableAnnotation == NullableAnnotation.Annotated && performOnlyCycleSafeValidation && + typeWithAnnotations.DefaultType is TypeParameterSymbol typeParameterInConstraint && typeParameterInConstraint.ContainingSymbol == (object)typeParameter.ContainingSymbol) + { + return true; + } + TypeSymbol type = typeWithAnnotations.Type; switch (type.SpecialType) diff --git a/src/Compilers/CSharp/Portable/Binder/Binder_Expressions.cs b/src/Compilers/CSharp/Portable/Binder/Binder_Expressions.cs index 5cd2a0ee953bf..c9110c9bdfe86 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder_Expressions.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder_Expressions.cs @@ -1933,13 +1933,7 @@ private BoundExpression SynthesizeReceiver(SyntaxNode node, Symbol member, Diagn internal Symbol ContainingMember() { - // We skip intervening lambdas and local functions to find the actual member. - var containingMember = this.ContainingMemberOrLambda; - while (containingMember.Kind != SymbolKind.NamedType && (object)containingMember.ContainingSymbol != null && containingMember.ContainingSymbol.Kind != SymbolKind.NamedType) - { - containingMember = containingMember.ContainingSymbol; - } - return containingMember; + return this.ContainingMemberOrLambda.ContainingNonLambdaMember(); } private BoundExpression TryBindInteractiveReceiver(SyntaxNode syntax, NamedTypeSymbol memberDeclaringType) @@ -3959,23 +3953,27 @@ private BoundExpression BindConstructorInitializerCore( CSharpSyntaxNode nonNullSyntax; Location errorLocation; + bool enableCallerInfo; switch (initializerArgumentListOpt?.Parent) { case ConstructorInitializerSyntax initializerSyntax: nonNullSyntax = initializerSyntax; errorLocation = initializerSyntax.ThisOrBaseKeyword.GetLocation(); + enableCallerInfo = true; break; case PrimaryConstructorBaseTypeSyntax baseWithArguments: nonNullSyntax = baseWithArguments; errorLocation = initializerArgumentListOpt.GetLocation(); + enableCallerInfo = true; break; default: // Note: use syntax node of constructor with initializer, not constructor invoked by initializer (i.e. methodResolutionResult). nonNullSyntax = constructor.GetNonNullSyntaxNode(); errorLocation = constructor.Locations[0]; + enableCallerInfo = false; break; } @@ -4037,9 +4035,12 @@ private BoundExpression BindConstructorInitializerCore( ReportDiagnosticsIfObsolete(diagnostics, resultMember, nonNullSyntax, hasBaseReceiver: isBaseConstructorInitializer); + var expanded = memberResolutionResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; + var argsToParamsOpt = memberResolutionResult.Result.ArgsToParamsOpt; + BindDefaultArguments(nonNullSyntax, resultMember.Parameters, analyzedArguments.Arguments, analyzedArguments.RefKinds, ref argsToParamsOpt, out var defaultArguments, expanded, enableCallerInfo, diagnostics); + var arguments = analyzedArguments.Arguments.ToImmutable(); var refKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); - var argsToParamsOpt = memberResolutionResult.Result.ArgsToParamsOpt; if (!hasErrors) { hasErrors = !CheckInvocationArgMixing( @@ -4061,9 +4062,10 @@ private BoundExpression BindConstructorInitializerCore( analyzedArguments.GetNames(), refKinds, isDelegateCall: false, - expanded: memberResolutionResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm, + expanded, invokedAsExtensionMethod: false, argsToParamsOpt: argsToParamsOpt, + defaultArguments: defaultArguments, resultKind: LookupResultKind.Viable, binderOpt: this, type: constructorReturnType, @@ -4653,6 +4655,7 @@ private BoundExpression BindObjectInitializerMember( ImmutableArray argumentNamesOpt = default(ImmutableArray); ImmutableArray argsToParamsOpt = default(ImmutableArray); ImmutableArray argumentRefKindsOpt = default(ImmutableArray); + BitVector defaultArguments = default(BitVector); bool expanded = false; switch (boundMemberKind) @@ -4683,12 +4686,14 @@ private BoundExpression BindObjectInitializerMember( case BoundKind.IndexerAccess: { - var indexer = (BoundIndexerAccess)boundMember; + var indexer = BindIndexerDefaultArguments((BoundIndexerAccess)boundMember, valueKind, diagnostics); + boundMember = indexer; hasErrors |= isRhsNestedInitializer && !CheckNestedObjectInitializerPropertySymbol(indexer.Indexer, namedAssignment.Left, diagnostics, hasErrors, ref resultKind); arguments = indexer.Arguments; argumentNamesOpt = indexer.ArgumentNamesOpt; argsToParamsOpt = indexer.ArgsToParamsOpt; argumentRefKindsOpt = indexer.ArgumentRefKindsOpt; + defaultArguments = indexer.DefaultArguments; expanded = indexer.Expanded; break; @@ -4732,6 +4737,7 @@ private BoundExpression BindObjectInitializerMember( argumentRefKindsOpt, expanded, argsToParamsOpt, + defaultArguments, resultKind, implicitReceiver.Type, binder: this, @@ -5081,6 +5087,7 @@ private BoundExpression BindCollectionInitializerElementAddMethod( boundCall.ReceiverOpt, boundCall.Expanded, boundCall.ArgsToParamsOpt, + boundCall.DefaultArguments, boundCall.InvokedAsExtensionMethod, boundCall.ResultKind, binderOpt: boundCall.BinderOpt, @@ -5254,9 +5261,12 @@ protected BoundExpression BindClassCreationExpression( FoldParameterlessValueTypeConstructor(type) : null; + var expanded = memberResolutionResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; + var argToParams = memberResolutionResult.Result.ArgsToParamsOpt; + BindDefaultArguments(node, method.Parameters, analyzedArguments.Arguments, analyzedArguments.RefKinds, ref argToParams, out var defaultArguments, expanded, enableCallerInfo: true, diagnostics); + var arguments = analyzedArguments.Arguments.ToImmutable(); var refKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); - var argToParams = memberResolutionResult.Result.ArgsToParamsOpt; if (!hasError) { @@ -5279,8 +5289,9 @@ protected BoundExpression BindClassCreationExpression( arguments, analyzedArguments.GetNames(), refKinds, - memberResolutionResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm, + expanded, argToParams, + defaultArguments, constantValueOpt, boundInitializerOpt, wasTargetTyped, @@ -5442,7 +5453,7 @@ private BoundExpression BindComImportCoClassCreationExpression(SyntaxNode node, case BoundKind.ObjectCreationExpression: var creation = (BoundObjectCreationExpression)classCreation; return creation.Update(creation.Constructor, creation.ConstructorsGroup, creation.Arguments, creation.ArgumentNamesOpt, - creation.ArgumentRefKindsOpt, creation.Expanded, creation.ArgsToParamsOpt, creation.ConstantValueOpt, + creation.ArgumentRefKindsOpt, creation.Expanded, creation.ArgsToParamsOpt, creation.DefaultArguments, creation.ConstantValueOpt, creation.InitializerExpressionOpt, creation.BinderOpt, interfaceType); case BoundKind.BadExpression: @@ -7786,6 +7797,8 @@ private BoundExpression BindIndexerOrIndexedPropertyAccess( diagnostics); } + // Note that we do not bind default arguments here, because at this point we do not know whether + // the indexer is being used in a 'get', or 'set', or 'get+set' (compound assignment) context. propertyAccess = new BoundIndexerAccess( syntax, receiver, @@ -7795,8 +7808,8 @@ private BoundExpression BindIndexerOrIndexedPropertyAccess( argumentRefKinds, isExpanded, argsToParams, + defaultArguments: default, this, - false, property.Type, gotError); } diff --git a/src/Compilers/CSharp/Portable/Binder/Binder_Invocation.cs b/src/Compilers/CSharp/Portable/Binder/Binder_Invocation.cs index 3f95819d358a6..2744d68e9dbe4 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder_Invocation.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder_Invocation.cs @@ -1006,6 +1006,8 @@ private BoundCall BindInvocationExpressionContinued( var expanded = methodResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; var argsToParams = methodResult.Result.ArgsToParamsOpt; + BindDefaultArguments(node, method.Parameters, analyzedArguments.Arguments, analyzedArguments.RefKinds, ref argsToParams, out var defaultArguments, expanded, enableCallerInfo: true, diagnostics); + // It is possible that overload resolution succeeded, but we have chosen an // instance method and we're in a static method. A careful reading of the // overload resolution spec shows that the "final validation" stage allows an @@ -1140,9 +1142,278 @@ private BoundCall BindInvocationExpressionContinued( return new BoundCall(node, receiver, method, args, argNames, argRefKinds, isDelegateCall: isDelegateCall, expanded: expanded, invokedAsExtensionMethod: invokedAsExtensionMethod, - argsToParamsOpt: argsToParams, resultKind: LookupResultKind.Viable, binderOpt: this, type: returnType, hasErrors: gotError); + argsToParamsOpt: argsToParams, defaultArguments, resultKind: LookupResultKind.Viable, binderOpt: this, type: returnType, hasErrors: gotError); + } + +#nullable enable + + private static SourceLocation GetCallerLocation(SyntaxNode syntax) + { + var token = syntax switch + { + InvocationExpressionSyntax invocation => invocation.ArgumentList.OpenParenToken, + ObjectCreationExpressionSyntax objectCreation => objectCreation.NewKeyword, + ConstructorInitializerSyntax constructorInitializer => constructorInitializer.ArgumentList.OpenParenToken, + PrimaryConstructorBaseTypeSyntax primaryConstructorBaseType => primaryConstructorBaseType.ArgumentList.OpenParenToken, + ElementAccessExpressionSyntax elementAccess => elementAccess.ArgumentList.OpenBracketToken, + _ => syntax.GetFirstToken() + }; + + return new SourceLocation(token); } + internal BoundExpression BindDefaultArgument(SyntaxNode syntax, ParameterSymbol parameter, Symbol containingMember, bool enableCallerInfo, DiagnosticBag diagnostics) + { + Debug.Assert(parameter.IsOptional); + + TypeSymbol parameterType = parameter.Type; + if (Flags.Includes(BinderFlags.ParameterDefaultValue)) + { + // This is only expected to occur in recursive error scenarios, for example: `object F(object param = F()) { }` + // We return a non-error expression here to ensure ERR_DefaultValueMustBeConstant (or another appropriate diagnostics) is produced by the caller. + return new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; + } + + var defaultConstantValue = parameter.ExplicitDefaultConstantValue switch + { + // Bad default values are implicitly replaced with default(T) at call sites. + { IsBad: true } => ConstantValue.Null, + var constantValue => constantValue + }; + Debug.Assert((object?)defaultConstantValue != ConstantValue.Unset); + + var callerSourceLocation = enableCallerInfo ? GetCallerLocation(syntax) : null; + BoundExpression defaultValue; + if (callerSourceLocation is object && parameter.IsCallerLineNumber) + { + int line = callerSourceLocation.SourceTree.GetDisplayLineNumber(callerSourceLocation.SourceSpan); + defaultValue = new BoundLiteral(syntax, ConstantValue.Create(line), Compilation.GetSpecialType(SpecialType.System_Int32)) { WasCompilerGenerated = true }; + } + else if (callerSourceLocation is object && parameter.IsCallerFilePath) + { + string path = callerSourceLocation.SourceTree.GetDisplayPath(callerSourceLocation.SourceSpan, Compilation.Options.SourceReferenceResolver); + defaultValue = new BoundLiteral(syntax, ConstantValue.Create(path), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true }; + } + else if (callerSourceLocation is object && parameter.IsCallerMemberName) + { + var memberName = containingMember.GetMemberCallerName(); + defaultValue = new BoundLiteral(syntax, ConstantValue.Create(memberName), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true }; + } + else if (defaultConstantValue == ConstantValue.NotAvailable) + { + // There is no constant value given for the parameter in source/metadata. + if (parameterType.IsDynamic() || parameterType.SpecialType == SpecialType.System_Object) + { + // We have something like M([Optional] object x). We have special handling for such situations. + defaultValue = GetDefaultParameterSpecialNoConversion(syntax, parameter, diagnostics); + } + else + { + // The argument to M([Optional] int x) becomes default(int) + defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; + } + } + else if (defaultConstantValue.IsNull) + { + defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; + } + else + { + TypeSymbol constantType = Compilation.GetSpecialType(defaultConstantValue.SpecialType); + defaultValue = new BoundLiteral(syntax, defaultConstantValue, constantType) { WasCompilerGenerated = true }; + } + + HashSet? useSiteDiagnostics = null; + Conversion conversion = Conversions.ClassifyConversionFromExpression(defaultValue, parameterType, ref useSiteDiagnostics); + diagnostics.Add(syntax, useSiteDiagnostics); + + if (!conversion.IsValid && defaultConstantValue is { SpecialType: SpecialType.System_Decimal or SpecialType.System_DateTime }) + { + // Usually, if a default constant value fails to convert to the parameter type, we want an error at the call site. + // For legacy reasons, decimal and DateTime constants are special. If such a constant fails to convert to the parameter type + // then we want to silently replace it with default(ParameterType). + defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; + } + else + { + if (!conversion.IsValid) + { + GenerateImplicitConversionError(diagnostics, syntax, conversion, defaultValue, parameterType); + } + defaultValue = CreateConversion(defaultValue, conversion, parameterType, diagnostics); + } + + return defaultValue; + } + + private BoundExpression GetDefaultParameterSpecialNoConversion(SyntaxNode syntax, ParameterSymbol parameter, DiagnosticBag diagnostics) + { + var parameterType = parameter.Type; + Debug.Assert(parameterType.IsDynamic() || parameterType.SpecialType == SpecialType.System_Object); + + // We have a call to a method M([Optional] object x) which omits the argument. The value we generate + // for the argument depends on the presence or absence of other attributes. The rules are: + // + // * If the parameter is marked as [MarshalAs(Interface)], [MarshalAs(IUnknown)] or [MarshalAs(IDispatch)] + // then the argument is null. + // * Otherwise, if the parameter is marked as [IUnknownConstant] then the argument is + // new UnknownWrapper(null) + // * Otherwise, if the parameter is marked as [IDispatchConstant] then the argument is + // new DispatchWrapper(null) + // * Otherwise, the argument is Type.Missing. + + BoundExpression? defaultValue = null; + if (parameter.IsMarshalAsObject) + { + // default(object) + defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; + } + else if (parameter.IsIUnknownConstant) + { + if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Runtime_InteropServices_UnknownWrapper__ctor, diagnostics, syntax: syntax) is MethodSymbol methodSymbol) + { + // new UnknownWrapper(default(object)) + var unknownArgument = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; + defaultValue = new BoundObjectCreationExpression(syntax, methodSymbol, null, unknownArgument) { WasCompilerGenerated = true }; + } + } + else if (parameter.IsIDispatchConstant) + { + if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Runtime_InteropServices_DispatchWrapper__ctor, diagnostics, syntax: syntax) is MethodSymbol methodSymbol) + { + // new DispatchWrapper(default(object)) + var dispatchArgument = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; + defaultValue = new BoundObjectCreationExpression(syntax, methodSymbol, null, dispatchArgument) { WasCompilerGenerated = true }; + } + } + else + { + if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Type__Missing, diagnostics, syntax: syntax) is FieldSymbol fieldSymbol) + { + // Type.Missing + defaultValue = new BoundFieldAccess(syntax, null, fieldSymbol, ConstantValue.NotAvailable) { WasCompilerGenerated = true }; + } + } + + return defaultValue ?? BadExpression(syntax).MakeCompilerGenerated(); + } + + internal static ParameterSymbol? GetCorrespondingParameter( + int argumentOrdinal, + ImmutableArray parameters, + ImmutableArray argsToParamsOpt, + bool expanded) + { + int n = parameters.Length; + ParameterSymbol? parameter; + + if (argsToParamsOpt.IsDefault) + { + if (argumentOrdinal < n) + { + parameter = parameters[argumentOrdinal]; + } + else if (expanded) + { + parameter = parameters[n - 1]; + } + else + { + parameter = null; + } + } + else + { + Debug.Assert(argumentOrdinal < argsToParamsOpt.Length); + int parameterOrdinal = argsToParamsOpt[argumentOrdinal]; + + if (parameterOrdinal < n) + { + parameter = parameters[parameterOrdinal]; + } + else + { + parameter = null; + } + } + + return parameter; + } + + internal void BindDefaultArguments( + SyntaxNode node, + ImmutableArray parameters, + ArrayBuilder argumentsBuilder, + ArrayBuilder? argumentRefKindsBuilder, + ref ImmutableArray argsToParamsOpt, + out BitVector defaultArguments, + bool expanded, + bool enableCallerInfo, + DiagnosticBag diagnostics) + { + + var visitedParameters = BitVector.Create(parameters.Length); + for (var i = 0; i < argumentsBuilder.Count; i++) + { + var parameter = GetCorrespondingParameter(i, parameters, argsToParamsOpt, expanded); + if (parameter is not null) + { + visitedParameters[parameter.Ordinal] = true; + } + } + + // only proceed with binding default arguments if we know there is some optional parameter that has not been matched by an explicit argument + if (!parameters.Any(static (param, visitedParameters) => !visitedParameters[param.Ordinal] && param.IsOptional, visitedParameters)) + { + defaultArguments = default; + return; + } + + // In a scenario like `string Prop { get; } = M();`, the containing symbol could be the synthesized field. + // We want to use the associated user-declared symbol instead where possible. + var containingMember = ContainingMember() switch + { + FieldSymbol { AssociatedSymbol: { } symbol } => symbol, + var c => c + }; + + defaultArguments = BitVector.Create(parameters.Length); + ArrayBuilder? argsToParamsBuilder = null; + if (!argsToParamsOpt.IsDefault) + { + argsToParamsBuilder = ArrayBuilder.GetInstance(argsToParamsOpt.Length); + argsToParamsBuilder.AddRange(argsToParamsOpt); + } + + // Go over missing parameters, inserting default values for optional parameters + for (int i = 0; i < parameters.Length; i++) + { + var parameter = parameters[i]; + if (!visitedParameters[parameter.Ordinal] && parameter.IsOptional) + { + defaultArguments[argumentsBuilder.Count] = true; + argumentsBuilder.Add(BindDefaultArgument(node, parameter, containingMember, enableCallerInfo, diagnostics)); + + if (argumentRefKindsBuilder is { Count: > 0 }) + { + argumentRefKindsBuilder.Add(RefKind.None); + } + + argsToParamsBuilder?.Add(parameter.Ordinal); + } + } + Debug.Assert(argumentRefKindsBuilder is null || argumentRefKindsBuilder.Count == 0 || argumentRefKindsBuilder.Count == argumentsBuilder.Count); + Debug.Assert(argsToParamsBuilder is null || argsToParamsBuilder.Count == argumentsBuilder.Count); + + if (argsToParamsBuilder is object) + { + argsToParamsOpt = argsToParamsBuilder.ToImmutableOrNull(); + argsToParamsBuilder.Free(); + } + } + +#nullable disable + /// /// Returns false if an implicit 'this' copy will occur due to an instance member invocation in a readonly member. /// diff --git a/src/Compilers/CSharp/Portable/Binder/Binder_Query.cs b/src/Compilers/CSharp/Portable/Binder/Binder_Query.cs index 97410f7e2197e..f7fd9190daa7b 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder_Query.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder_Query.cs @@ -229,10 +229,13 @@ private static BoundCall ReverseLastTwoParameterOrder(BoundCall result) argsToParams.AddRange(Enumerable.Range(0, n)); argsToParams[n - 1] = n - 2; argsToParams[n - 2] = n - 1; + var defaultArguments = result.DefaultArguments.Clone(); + (defaultArguments[n - 1], defaultArguments[n - 2]) = (defaultArguments[n - 2], defaultArguments[n - 1]); + return result.Update( - result.ReceiverOpt, result.Method, arguments.ToImmutableAndFree(), default(ImmutableArray), - default(ImmutableArray), result.IsDelegateCall, result.Expanded, result.InvokedAsExtensionMethod, - argsToParams.ToImmutableAndFree(), result.ResultKind, result.OriginalMethodsOpt, result.BinderOpt, result.Type); + result.ReceiverOpt, result.Method, arguments.ToImmutableAndFree(), argumentNamesOpt: default, + argumentRefKindsOpt: default, result.IsDelegateCall, result.Expanded, result.InvokedAsExtensionMethod, + argsToParams.ToImmutableAndFree(), defaultArguments, result.ResultKind, result.OriginalMethodsOpt, result.BinderOpt, result.Type); } private void ReduceQuery(QueryTranslationState state, DiagnosticBag diagnostics) diff --git a/src/Compilers/CSharp/Portable/Binder/Binder_Statements.cs b/src/Compilers/CSharp/Portable/Binder/Binder_Statements.cs index 70e56c5a322d8..279641294175e 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder_Statements.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder_Statements.cs @@ -1628,7 +1628,7 @@ private static bool AccessingAutoPropertyFromConstructor(BoundExpression receive var propertyIsStatic = propertySymbol.IsStatic; return (object)sourceProperty != null && - sourceProperty.IsAutoProperty && + sourceProperty.IsAutoPropertyWithGetAccessor && TypeSymbol.Equals(sourceProperty.ContainingType, fromMember.ContainingType, TypeCompareKind.ConsiderEverything2) && IsConstructorOrField(fromMember, isStatic: propertyIsStatic) && (propertyIsStatic || receiver.Kind == BoundKind.ThisReference); diff --git a/src/Compilers/CSharp/Portable/Binder/Binder_Symbols.cs b/src/Compilers/CSharp/Portable/Binder/Binder_Symbols.cs index 8aad0493e3519..a79f20b35559e 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder_Symbols.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder_Symbols.cs @@ -1154,6 +1154,10 @@ private TypeWithAnnotations BindGenericSimpleNamespaceOrTypeOrAliasSymbol( resultType = unconstructedType.AsUnboundGenericType(); } } + else if ((Flags & BinderFlags.SuppressTypeArgumentBinding) != 0) + { + resultType = unconstructedType.Construct(PlaceholderTypeArgumentSymbol.CreateTypeArguments(unconstructedType.TypeParameters)); + } else { // It's not an unbound type expression, so we must have type arguments, and we have a diff --git a/src/Compilers/CSharp/Portable/Binder/Semantics/AccessCheck.cs b/src/Compilers/CSharp/Portable/Binder/Semantics/AccessCheck.cs index c31f09c7060a0..fb933b116b560 100644 --- a/src/Compilers/CSharp/Portable/Binder/Semantics/AccessCheck.cs +++ b/src/Compilers/CSharp/Portable/Binder/Semantics/AccessCheck.cs @@ -236,7 +236,7 @@ private static bool IsNamedTypeAccessible(NamedTypeSymbol type, Symbol within, r { // type parameters are always accessible, so don't check those (so common it's // worth optimizing this). - if (typeArg.DefaultType.TypeKind != TypeKind.TypeParameter && !IsSymbolAccessibleCore(typeArg.Type, within, null, out unused, compilation, ref useSiteDiagnostics, basesBeingResolved)) + if (typeArg.Type.Kind != SymbolKind.TypeParameter && !IsSymbolAccessibleCore(typeArg.Type, within, null, out unused, compilation, ref useSiteDiagnostics, basesBeingResolved)) { return false; } diff --git a/src/Compilers/CSharp/Portable/BoundTree/BoundExpression.cs b/src/Compilers/CSharp/Portable/BoundTree/BoundExpression.cs index 5f4ad2943bab8..ce44319a2270d 100644 --- a/src/Compilers/CSharp/Portable/BoundTree/BoundExpression.cs +++ b/src/Compilers/CSharp/Portable/BoundTree/BoundExpression.cs @@ -232,9 +232,6 @@ public override Symbol? ExpressionSymbol get { return this.Indexer; } } - public BoundIndexerAccess Update(bool useSetterForDefaultArgumentGeneration) => - Update(ReceiverOpt, Indexer, Arguments, ArgumentNamesOpt, ArgumentRefKindsOpt, Expanded, ArgsToParamsOpt, BinderOpt, useSetterForDefaultArgumentGeneration, OriginalIndexersOpt, Type); - public override LookupResultKind ResultKind { get @@ -438,6 +435,7 @@ internal BoundObjectCreationExpression UpdateArgumentsAndInitializer( argumentRefKindsOpt: newRefKinds, expanded: false, argsToParamsOpt: default(ImmutableArray), + defaultArguments: default(BitVector), constantValueOpt: ConstantValueOpt, initializerExpressionOpt: newInitializerExpression, binderOpt: BinderOpt, diff --git a/src/Compilers/CSharp/Portable/BoundTree/BoundNodes.xml b/src/Compilers/CSharp/Portable/BoundTree/BoundNodes.xml index 04edbe9e8ab89..a1e15a5c78a00 100644 --- a/src/Compilers/CSharp/Portable/BoundTree/BoundNodes.xml +++ b/src/Compilers/CSharp/Portable/BoundTree/BoundNodes.xml @@ -1585,6 +1585,7 @@ + @@ -1771,6 +1774,7 @@ + @@ -1928,11 +1932,11 @@ + - diff --git a/src/Compilers/CSharp/Portable/BoundTree/BoundObjectCreationExpression.cs b/src/Compilers/CSharp/Portable/BoundTree/BoundObjectCreationExpression.cs index bc809adf43272..f06fd9d2a7acd 100644 --- a/src/Compilers/CSharp/Portable/BoundTree/BoundObjectCreationExpression.cs +++ b/src/Compilers/CSharp/Portable/BoundTree/BoundObjectCreationExpression.cs @@ -10,22 +10,22 @@ namespace Microsoft.CodeAnalysis.CSharp internal partial class BoundObjectCreationExpression { public BoundObjectCreationExpression(SyntaxNode syntax, MethodSymbol constructor, ImmutableArray arguments, ImmutableArray argumentNamesOpt, - ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, ConstantValue? constantValueOpt, + ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, ConstantValue? constantValueOpt, BoundObjectInitializerExpressionBase? initializerExpressionOpt, Binder? binderOpt, TypeSymbol type, bool hasErrors = false) - : this(syntax, constructor, ImmutableArray.Empty, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, constantValueOpt, initializerExpressionOpt, wasTargetTyped: false, binderOpt, type, hasErrors) + : this(syntax, constructor, ImmutableArray.Empty, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, constantValueOpt, initializerExpressionOpt, wasTargetTyped: false, binderOpt, type, hasErrors) { } public BoundObjectCreationExpression Update(MethodSymbol constructor, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, - ImmutableArray argsToParamsOpt, ConstantValue? constantValueOpt, BoundObjectInitializerExpressionBase? initializerExpressionOpt, Binder? binderOpt, TypeSymbol type) + ImmutableArray argsToParamsOpt, BitVector defaultArguments, ConstantValue? constantValueOpt, BoundObjectInitializerExpressionBase? initializerExpressionOpt, Binder? binderOpt, TypeSymbol type) { - return this.Update(constructor, ImmutableArray.Empty, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, constantValueOpt, initializerExpressionOpt, this.WasTargetTyped, binderOpt, type); + return this.Update(constructor, ImmutableArray.Empty, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, constantValueOpt, initializerExpressionOpt, this.WasTargetTyped, binderOpt, type); } public BoundObjectCreationExpression Update(MethodSymbol constructor, ImmutableArray constructorsGroup, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, - ConstantValue? constantValueOpt, BoundObjectInitializerExpressionBase? initializerExpressionOpt, Binder? binderOpt, TypeSymbol type) + BitVector defaultArguments, ConstantValue? constantValueOpt, BoundObjectInitializerExpressionBase? initializerExpressionOpt, Binder? binderOpt, TypeSymbol type) { - return this.Update(constructor, constructorsGroup, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, constantValueOpt, initializerExpressionOpt, this.WasTargetTyped, binderOpt, type); + return this.Update(constructor, constructorsGroup, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, constantValueOpt, initializerExpressionOpt, this.WasTargetTyped, binderOpt, type); } } } diff --git a/src/Compilers/CSharp/Portable/BoundTree/Constructors.cs b/src/Compilers/CSharp/Portable/BoundTree/Constructors.cs index 246eef1ca3305..a1de8f7c2431e 100644 --- a/src/Compilers/CSharp/Portable/BoundTree/Constructors.cs +++ b/src/Compilers/CSharp/Portable/BoundTree/Constructors.cs @@ -92,11 +92,12 @@ public BoundCall( bool expanded, bool invokedAsExtensionMethod, ImmutableArray argsToParamsOpt, + BitVector defaultArguments, LookupResultKind resultKind, Binder? binderOpt, TypeSymbol type, bool hasErrors = false) : - this(syntax, receiverOpt, method, arguments, argumentNamesOpt, argumentRefKindsOpt, isDelegateCall, expanded, invokedAsExtensionMethod, argsToParamsOpt, resultKind, originalMethodsOpt: default, binderOpt, type, hasErrors) + this(syntax, receiverOpt, method, arguments, argumentNamesOpt, argumentRefKindsOpt, isDelegateCall, expanded, invokedAsExtensionMethod, argsToParamsOpt, defaultArguments, resultKind, originalMethodsOpt: default, binderOpt, type, hasErrors) { } @@ -109,10 +110,11 @@ public BoundCall Update(BoundExpression? receiverOpt, bool expanded, bool invokedAsExtensionMethod, ImmutableArray argsToParamsOpt, + BitVector defaultArguments, LookupResultKind resultKind, Binder? binderOpt, TypeSymbol type) - => Update(receiverOpt, method, arguments, argumentNamesOpt, argumentRefKindsOpt, isDelegateCall, expanded, invokedAsExtensionMethod, argsToParamsOpt, resultKind, this.OriginalMethodsOpt, binderOpt, type); + => Update(receiverOpt, method, arguments, argumentNamesOpt, argumentRefKindsOpt, isDelegateCall, expanded, invokedAsExtensionMethod, argsToParamsOpt, defaultArguments, resultKind, this.OriginalMethodsOpt, binderOpt, type); public static BoundCall ErrorCall( SyntaxNode node, @@ -143,6 +145,7 @@ public static BoundCall ErrorCall( expanded: false, invokedAsExtensionMethod: invokedAsExtensionMethod, argsToParamsOpt: default(ImmutableArray), + defaultArguments: default(BitVector), resultKind: resultKind, originalMethodsOpt: originalMethods, binderOpt: binder, @@ -152,12 +155,12 @@ public static BoundCall ErrorCall( public BoundCall Update(ImmutableArray arguments) { - return this.Update(ReceiverOpt, Method, arguments, ArgumentNamesOpt, ArgumentRefKindsOpt, IsDelegateCall, Expanded, InvokedAsExtensionMethod, ArgsToParamsOpt, ResultKind, OriginalMethodsOpt, BinderOpt, Type); + return this.Update(ReceiverOpt, Method, arguments, ArgumentNamesOpt, ArgumentRefKindsOpt, IsDelegateCall, Expanded, InvokedAsExtensionMethod, ArgsToParamsOpt, DefaultArguments, ResultKind, OriginalMethodsOpt, BinderOpt, Type); } public BoundCall Update(BoundExpression? receiverOpt, MethodSymbol method, ImmutableArray arguments) { - return this.Update(receiverOpt, method, arguments, ArgumentNamesOpt, ArgumentRefKindsOpt, IsDelegateCall, Expanded, InvokedAsExtensionMethod, ArgsToParamsOpt, ResultKind, OriginalMethodsOpt, BinderOpt, Type); + return this.Update(receiverOpt, method, arguments, ArgumentNamesOpt, ArgumentRefKindsOpt, IsDelegateCall, Expanded, InvokedAsExtensionMethod, ArgsToParamsOpt, DefaultArguments, ResultKind, OriginalMethodsOpt, BinderOpt, Type); } public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol method) @@ -187,6 +190,7 @@ public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression? receiver expanded: false, invokedAsExtensionMethod: false, argsToParamsOpt: default(ImmutableArray), + defaultArguments: default(BitVector), resultKind: LookupResultKind.Viable, originalMethodsOpt: default, binderOpt: null, @@ -200,11 +204,11 @@ public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression? receiver internal sealed partial class BoundObjectCreationExpression { public BoundObjectCreationExpression(SyntaxNode syntax, MethodSymbol constructor, Binder? binderOpt, params BoundExpression[] arguments) - : this(syntax, constructor, ImmutableArray.Create(arguments), default(ImmutableArray), default(ImmutableArray), false, default(ImmutableArray), null, null, binderOpt, constructor.ContainingType) + : this(syntax, constructor, ImmutableArray.Create(arguments), default(ImmutableArray), default(ImmutableArray), false, default(ImmutableArray), default(BitVector), null, null, binderOpt, constructor.ContainingType) { } public BoundObjectCreationExpression(SyntaxNode syntax, MethodSymbol constructor, Binder? binderOpt, ImmutableArray arguments) - : this(syntax, constructor, arguments, default(ImmutableArray), default(ImmutableArray), false, default(ImmutableArray), null, null, binderOpt, constructor.ContainingType) + : this(syntax, constructor, arguments, default(ImmutableArray), default(ImmutableArray), false, default(ImmutableArray), default(BitVector), null, null, binderOpt, constructor.ContainingType) { } } @@ -229,8 +233,8 @@ public static BoundIndexerAccess ErrorAccess( refKinds, expanded: false, argsToParamsOpt: default(ImmutableArray), + defaultArguments: default(BitVector), binderOpt: null, - useSetterForDefaultArgumentGeneration: false, originalIndexers, type: indexer.Type, hasErrors: true); @@ -244,11 +248,11 @@ public BoundIndexerAccess( ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, + BitVector defaultArguments, Binder? binderOpt, - bool useSetterForDefaultArgumentGeneration, TypeSymbol type, bool hasErrors = false) : - this(syntax, receiverOpt, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, binderOpt, useSetterForDefaultArgumentGeneration, originalIndexersOpt: default, type, hasErrors) + this(syntax, receiverOpt, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, binderOpt, originalIndexersOpt: default, type, hasErrors) { } public BoundIndexerAccess Update(BoundExpression? receiverOpt, @@ -258,10 +262,10 @@ public BoundIndexerAccess Update(BoundExpression? receiverOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, + BitVector defaultArguments, Binder? binderOpt, - bool useSetterForDefaultArgumentGeneration, TypeSymbol type) - => Update(receiverOpt, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, binderOpt, useSetterForDefaultArgumentGeneration, this.OriginalIndexersOpt, type); + => Update(receiverOpt, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, binderOpt, this.OriginalIndexersOpt, type); } internal sealed partial class BoundConversion diff --git a/src/Compilers/CSharp/Portable/CodeGen/Optimizer.cs b/src/Compilers/CSharp/Portable/CodeGen/Optimizer.cs index bdab7d15a87a4..0d7e68a92ef55 100644 --- a/src/Compilers/CSharp/Portable/CodeGen/Optimizer.cs +++ b/src/Compilers/CSharp/Portable/CodeGen/Optimizer.cs @@ -1221,7 +1221,7 @@ public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpre Debug.Assert(node.InitializerExpressionOpt == null); return node.Update(constructor, rewrittenArguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, - node.Expanded, node.ArgsToParamsOpt, node.ConstantValue, null, node.BinderOpt, node.Type); + node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.ConstantValue, null, node.BinderOpt, node.Type); } public override BoundNode VisitArrayAccess(BoundArrayAccess node) @@ -2029,7 +2029,7 @@ public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpre ImmutableArray arguments = this.VisitList(node.Arguments); Debug.Assert(node.InitializerExpressionOpt == null); TypeSymbol type = this.VisitType(node.Type); - return node.Update(node.Constructor, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.ConstantValueOpt, null, node.BinderOpt, type); + return node.Update(node.Constructor, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.ConstantValueOpt, null, node.BinderOpt, type); } public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) diff --git a/src/Compilers/CSharp/Portable/Compilation/CSharpDiagnosticFilter.cs b/src/Compilers/CSharp/Portable/Compilation/CSharpDiagnosticFilter.cs index 5772783d97a2a..1303fc56c371d 100644 --- a/src/Compilers/CSharp/Portable/Compilation/CSharpDiagnosticFilter.cs +++ b/src/Compilers/CSharp/Portable/Compilation/CSharpDiagnosticFilter.cs @@ -178,23 +178,36 @@ internal static ReportDiagnostic GetDiagnosticReport( ReportDiagnostic report; bool isSpecified = false; + bool specifiedWarnAsErrorMinus = false; if (specificDiagnosticOptions.TryGetValue(id, out report)) { // 2. Command line options (/nowarn, /warnaserror) isSpecified = true; + + // 'ReportDiagnostic.Default' is added to SpecificDiagnosticOptions for "/warnaserror-:DiagnosticId", + if (report == ReportDiagnostic.Default) + { + specifiedWarnAsErrorMinus = true; + } } - else if (syntaxTreeOptions != null) + + // Apply syntax tree options, if applicable. + if (syntaxTreeOptions != null && + (!isSpecified || specifiedWarnAsErrorMinus)) { // 3. Editor config options (syntax tree level) // 4. Global analyzer config options (compilation level) - if (tree != null && syntaxTreeOptions.TryGetDiagnosticValue(tree, id, cancellationToken, out report) || - syntaxTreeOptions.TryGetGlobalDiagnosticValue(id, cancellationToken, out report)) + // Do not apply config options if it is bumping a warning to an error and "/warnaserror-:DiagnosticId" was specified on the command line. + if ((tree != null && syntaxTreeOptions.TryGetDiagnosticValue(tree, id, cancellationToken, out var reportFromSyntaxTreeOptions) || + syntaxTreeOptions.TryGetGlobalDiagnosticValue(id, cancellationToken, out reportFromSyntaxTreeOptions)) && + !(specifiedWarnAsErrorMinus && severity == DiagnosticSeverity.Warning && reportFromSyntaxTreeOptions == ReportDiagnostic.Error)) { isSpecified = true; + report = reportFromSyntaxTreeOptions; // '/warnaserror' should promote warnings configured in analyzer config to error. - if (report == ReportDiagnostic.Warn && generalDiagnosticOption == ReportDiagnostic.Error) + if (!specifiedWarnAsErrorMinus && report == ReportDiagnostic.Warn && generalDiagnosticOption == ReportDiagnostic.Error) { report = ReportDiagnostic.Error; } diff --git a/src/Compilers/CSharp/Portable/Compiler/MethodBodySynthesizer.cs b/src/Compilers/CSharp/Portable/Compiler/MethodBodySynthesizer.cs index f404a8ba47524..1756022efce0a 100644 --- a/src/Compilers/CSharp/Portable/Compiler/MethodBodySynthesizer.cs +++ b/src/Compilers/CSharp/Portable/Compiler/MethodBodySynthesizer.cs @@ -51,6 +51,7 @@ internal static ImmutableArray ConstructScriptConstructorBody( expanded: false, invokedAsExtensionMethod: false, argsToParamsOpt: ImmutableArray.Empty, + defaultArguments: BitVector.Empty, resultKind: LookupResultKind.Viable, binderOpt: null, type: objectType) diff --git a/src/Compilers/CSharp/Portable/Compiler/MethodCompiler.cs b/src/Compilers/CSharp/Portable/Compiler/MethodCompiler.cs index d1566cf8956af..54b80e57fadce 100644 --- a/src/Compilers/CSharp/Portable/Compiler/MethodCompiler.cs +++ b/src/Compilers/CSharp/Portable/Compiler/MethodCompiler.cs @@ -1754,7 +1754,7 @@ syntaxNode is ConstructorDeclarationSyntax constructorSyntax && else { var property = sourceMethod.AssociatedSymbol as SourcePropertySymbolBase; - if ((object)property != null && property.IsAutoProperty) + if ((object)property != null && property.IsAutoPropertyWithGetAccessor) { return MethodBodySynthesizer.ConstructAutoPropertyAccessorBody(sourceMethod); } @@ -2018,6 +2018,7 @@ internal static BoundCall GenerateBaseParameterlessConstructorInitializer(Method expanded: false, invokedAsExtensionMethod: false, argsToParamsOpt: ImmutableArray.Empty, + defaultArguments: BitVector.Empty, resultKind: resultKind, binderOpt: null, type: baseConstructor.ReturnType, @@ -2065,6 +2066,7 @@ private static BoundCall GenerateBaseCopyConstructorInitializer(SynthesizedRecor expanded: false, invokedAsExtensionMethod: false, argsToParamsOpt: default, + defaultArguments: default, resultKind: LookupResultKind.Viable, binderOpt: null, type: baseConstructor.ReturnType, diff --git a/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.DebugVerifier.cs b/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.DebugVerifier.cs index 74265fff9c9ef..804fc9d97fb1f 100644 --- a/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.DebugVerifier.cs +++ b/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.DebugVerifier.cs @@ -115,6 +115,7 @@ private void VerifyExpression(BoundExpression expression, bool overrideSkippedEx { Visit(node.IterationVariableType); Visit(node.AwaitOpt); + Visit(node.EnumeratorInfoOpt?.DisposeAwaitableInfo); Visit(node.Expression); // https://github.com/dotnet/roslyn/issues/35010: handle the deconstruction //this.Visit(node.DeconstructionOpt); diff --git a/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs b/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs index 181180e2a22e7..ffa2eeb78e857 100644 --- a/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs +++ b/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs @@ -218,17 +218,6 @@ public VisitArgumentResult(VisitResult visitResult, Optional stateFo /// private VisitResult _currentConditionalReceiverVisitResult; - /// - /// Gets the synthesized default argument expression for the given syntax node and parameter. - /// Upon re-analysis, the bound nodes that get visited must have the same identity as the previous analysis pass - /// so that the analysis does not believe that new variables were found each time and repeat indefinitely. - /// - /// Each call which implicitly passes a default value needs its own synthesized BoundExpression - /// because the location of the call can affect the default parameter value. - /// Therefore the dictionary key must be (SyntaxNode, ParameterSymbol) instead of just ParameterSymbol. - /// - private PooledDictionary<(SyntaxNode, ParameterSymbol), BoundExpression>? _defaultValuesOpt; - /// /// The result type represents the state of the last visited expression. /// @@ -360,7 +349,6 @@ protected override void Free() _methodGroupReceiverMapOpt?.Free(); _variableTypes.Free(); _placeholderLocalsOpt?.Free(); - _defaultValuesOpt?.Free(); base.Free(); } @@ -1234,9 +1222,22 @@ private static BoundNode Rewrite(ImmutableDictionaryAnalyzes a node in a "one-off" context, such as for attributes or parameter default values. internal static void AnalyzeIfNeeded( Binder binder, - BoundAttribute attribute, + BoundNode node, DiagnosticBag diagnostics) { var compilation = binder.Compilation; @@ -1254,7 +1255,7 @@ internal static void AnalyzeIfNeeded( Analyze( compilation, symbol: null, - attribute, + node, binder, binder.Conversions, diagnostics, @@ -2329,27 +2330,26 @@ private void EnterParameter(ParameterSymbol parameter, TypeWithAnnotations param valueSlot: -1, isDefaultValue: parameter.ExplicitDefaultConstantValue?.IsNull == true); } + } + } - if (parameter.IsOptional) - { - // When a parameter has a default value, we initialize its flow state by simulating an assignment of the default value to the parameter. - var syntax = parameter.GetNonNullSyntaxNode(); - var rightSyntax = syntax is ParameterSyntax { Default: { Value: { } value } } ? value : syntax; - var right = GetDefaultParameterValue(rightSyntax, parameter); + public override BoundNode? VisitParameterEqualsValue(BoundParameterEqualsValue equalsValue) + { + var parameter = equalsValue.Parameter; + var parameterAnnotations = GetParameterAnnotations(parameter); + var parameterLValueType = ApplyLValueAnnotations(parameter.TypeWithAnnotations, parameterAnnotations); - var parameterAnnotations = GetParameterAnnotations(parameter); - var parameterLValueType = ApplyLValueAnnotations(parameterType, parameterAnnotations); + var resultType = VisitOptionalImplicitConversion( + equalsValue.Value, + parameterLValueType, + useLegacyWarnings: false, + trackMembers: false, + assignmentKind: AssignmentKind.Assignment); - var previous = _disableNullabilityAnalysis; - _disableNullabilityAnalysis = true; - VisitOptionalImplicitConversion(right, parameterLValueType, useLegacyWarnings: true, trackMembers: true, assignmentKind: AssignmentKind.Assignment); - _disableNullabilityAnalysis = previous; + // If the LHS has annotations, we perform an additional check for nullable value types + CheckDisallowedNullAssignment(resultType, parameterAnnotations, equalsValue.Value.Syntax.Location); - // If the LHS has annotations, we perform an additional check for nullable value types - CheckDisallowedNullAssignment(ResultType, parameterAnnotations, right.Syntax.Location); - TrackNullableStateForAssignment(right, parameterType, slot, ResultType, MakeSlot(right)); - } - } + return null; } private static TypeWithState GetParameterState(TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations) @@ -2739,7 +2739,6 @@ private void VisitLocalFunctionUse(LocalFunctionSymbol symbol) public override BoundNode? VisitForEachStatement(BoundForEachStatement node) { DeclareLocals(node.IterationVariables); - Visit(node.AwaitOpt); return base.VisitForEachStatement(node); } @@ -2962,7 +2961,7 @@ protected override void VisitStatement(BoundStatement statement) { Debug.Assert(!IsConditionalState); var arguments = node.Arguments; - var argumentResults = VisitArguments(node, arguments, node.ArgumentRefKindsOpt, node.Constructor, node.ArgsToParamsOpt, node.Expanded, invokedAsExtensionMethod: false).results; + var argumentResults = VisitArguments(node, arguments, node.ArgumentRefKindsOpt, node.Constructor, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, invokedAsExtensionMethod: false).results; VisitObjectOrDynamicObjectCreation(node, arguments, argumentResults, node.InitializerExpressionOpt); return null; } @@ -3130,7 +3129,7 @@ private void VisitObjectElementInitializer(int containingSlot, BoundAssignmentOp var symbol = objectInitializer.MemberSymbol; if (!objectInitializer.Arguments.IsDefaultOrEmpty) { - VisitArguments(objectInitializer, objectInitializer.Arguments, objectInitializer.ArgumentRefKindsOpt, (PropertySymbol?)symbol, objectInitializer.ArgsToParamsOpt, objectInitializer.Expanded); + VisitArguments(objectInitializer, objectInitializer.Arguments, objectInitializer.ArgumentRefKindsOpt, (PropertySymbol?)symbol, objectInitializer.ArgsToParamsOpt, objectInitializer.DefaultArguments, objectInitializer.Expanded); } if (symbol is object) @@ -3155,7 +3154,7 @@ private void VisitObjectElementInitializer(int containingSlot, BoundAssignmentOp private new void VisitCollectionElementInitializer(BoundCollectionElementInitializer node) { // Note: we analyze even omitted calls - (var reinferredMethod, _, _) = VisitArguments(node, node.Arguments, refKindsOpt: default, node.AddMethod, node.ArgsToParamsOpt, node.Expanded, node.InvokedAsExtensionMethod); + (var reinferredMethod, _, _) = VisitArguments(node, node.Arguments, refKindsOpt: default, node.AddMethod, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, node.InvokedAsExtensionMethod); Debug.Assert(reinferredMethod is object); if (node.ImplicitReceiverOpt != null) { @@ -4493,7 +4492,7 @@ private void ReinferMethodAndVisitArguments(BoundCall node, TypeWithState receiv ImmutableArray results; bool returnNotNull; - (method, results, returnNotNull) = VisitArguments(node, node.Arguments, refKindsOpt, method!.Parameters, node.ArgsToParamsOpt, + (method, results, returnNotNull) = VisitArguments(node, node.Arguments, refKindsOpt, method!.Parameters, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, node.InvokedAsExtensionMethod, method); ApplyMemberPostConditions(node.ReceiverOpt, method); @@ -4910,10 +4909,11 @@ protected override void VisitArguments(ImmutableArray arguments ImmutableArray refKindsOpt, MethodSymbol? method, ImmutableArray argsToParamsOpt, + BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod) { - return VisitArguments(node, arguments, refKindsOpt, method is null ? default : method.Parameters, argsToParamsOpt, expanded, invokedAsExtensionMethod, method); + return VisitArguments(node, arguments, refKindsOpt, method is null ? default : method.Parameters, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod, method); } private ImmutableArray VisitArguments( @@ -4922,9 +4922,10 @@ private ImmutableArray VisitArguments( ImmutableArray refKindsOpt, PropertySymbol? property, ImmutableArray argsToParamsOpt, + BitVector defaultArguments, bool expanded) { - return VisitArguments(node, arguments, refKindsOpt, property is null ? default : property.Parameters, argsToParamsOpt, expanded, invokedAsExtensionMethod: false).results; + return VisitArguments(node, arguments, refKindsOpt, property is null ? default : property.Parameters, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod: false).results; } /// @@ -4936,6 +4937,7 @@ private ImmutableArray VisitArguments( ImmutableArray refKindsOpt, ImmutableArray parametersOpt, ImmutableArray argsToParamsOpt, + BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod, MethodSymbol? method = null) @@ -4946,8 +4948,7 @@ private ImmutableArray VisitArguments( (ImmutableArray argumentsNoConversions, ImmutableArray conversions) = RemoveArgumentConversions(arguments, refKindsOpt); // Visit the arguments and collect results - ImmutableArray results; - (results, argumentsNoConversions, argsToParamsOpt, refKindsOpt) = VisitArgumentsEvaluate(node.Syntax, argumentsNoConversions, refKindsOpt, parametersOpt, argsToParamsOpt, expanded); + ImmutableArray results = VisitArgumentsEvaluate(node.Syntax, argumentsNoConversions, refKindsOpt, parametersOpt, argsToParamsOpt, defaultArguments, expanded); // Re-infer method type parameters if (method?.IsGenericMethod == true) @@ -5170,86 +5171,39 @@ void markMembersAsNotNull(int receiverSlot, TypeSymbol type, string memberName, } } - private (ImmutableArray results, ImmutableArray arguments, ImmutableArray allArgsToParamsOpt, ImmutableArray allRefKindsOpt) VisitArgumentsEvaluate( + private ImmutableArray VisitArgumentsEvaluate( SyntaxNode syntax, ImmutableArray arguments, ImmutableArray refKindsOpt, ImmutableArray parametersOpt, ImmutableArray argsToParamsOpt, + BitVector defaultArguments, bool expanded) { Debug.Assert(!IsConditionalState); int n = arguments.Length; if (n == 0 && parametersOpt.IsDefaultOrEmpty) { - return (ImmutableArray.Empty, arguments, argsToParamsOpt, refKindsOpt); + return ImmutableArray.Empty; } var visitedParameters = PooledHashSet.GetInstance(); var resultsBuilder = ArrayBuilder.GetInstance(n); + var previousDisableDiagnostics = _disableDiagnostics; for (int i = 0; i < n; i++) { var (parameter, _, parameterAnnotations, _) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); + // we disable nullable warnings on default arguments + _disableDiagnostics = defaultArguments[i] || previousDisableDiagnostics; resultsBuilder.Add(VisitArgumentEvaluate(arguments[i], GetRefKind(refKindsOpt, i), parameterAnnotations)); visitedParameters.Add(parameter); } - - if (!parametersOpt.IsDefaultOrEmpty && parametersOpt.Length != visitedParameters.Count) - { - var argumentsBuilder = initBuilder(arguments)!; - var argsToParamsBuilder = initBuilder(argsToParamsOpt); - var argRefKindsBuilder = initBuilder(refKindsOpt); - - var previousDisableNullabilityAnalysis = _disableNullabilityAnalysis; - // Synthesized default arguments will not be found in the DebugVerifier's traversal of the bound tree. - // Therefore we need to ensure they don't get added to _analyzedNullabilityMapOpt. - _disableNullabilityAnalysis = true; - for (int i = 0; i < parametersOpt.Length; i++) - { - var parameter = parametersOpt[i]; - // Fill in unspecified optional arguments - // Note that the order of visiting the optional arguments doesn't matter because they are constants. - if (parameter.IsOptional && !visitedParameters.Contains(parameter)) - { - var annotations = GetParameterAnnotations(parameter); - - BoundExpression argument = GetDefaultParameterValue(syntax, parameter); - resultsBuilder.Add(VisitArgumentEvaluate(argument, RefKind.None, annotations)); - argumentsBuilder.Add(argument); - argsToParamsBuilder?.Add(i); - argRefKindsBuilder?.Add(RefKind.None); - } - } - _disableNullabilityAnalysis = previousDisableNullabilityAnalysis; - - arguments = argumentsBuilder.ToImmutableAndFree(); - argsToParamsOpt = argsToParamsBuilder?.ToImmutableAndFree() ?? default; - refKindsOpt = argRefKindsBuilder?.ToImmutableAndFree() ?? default; - } + _disableDiagnostics = previousDisableDiagnostics; SetInvalidResult(); visitedParameters.Free(); - return (resultsBuilder.ToImmutableAndFree(), arguments, argsToParamsOpt, refKindsOpt); - - ArrayBuilder? initBuilder(ImmutableArray arrayOpt) - { - if (arrayOpt.IsDefault) { return null; } - var builder = ArrayBuilder.GetInstance(parametersOpt.Length); - builder.AddRange(arrayOpt); - return builder; - } - } - - private BoundExpression GetDefaultParameterValue(SyntaxNode syntax, ParameterSymbol parameter) - { - _defaultValuesOpt ??= PooledDictionary<(SyntaxNode, ParameterSymbol), BoundExpression>.GetInstance(); - if (!_defaultValuesOpt.TryGetValue((syntax, parameter), out var argument)) - { - _defaultValuesOpt[(syntax, parameter)] = argument = LocalRewriter.GetDefaultParameterValue(syntax, parameter, enableCallerInfo: ThreeState.True, localRewriter: null, _binder, Diagnostics); - } - - return argument; + return resultsBuilder.ToImmutableAndFree(); } private VisitArgumentResult VisitArgumentEvaluate(BoundExpression argument, RefKind refKind, FlowAnalysisAnnotations annotations) @@ -5328,6 +5282,17 @@ private void VisitArgumentConversionAndInboundAssignmentsAndPreConditions( case RefKind.In: { // Note: for lambda arguments, they will be converted in the context/state we saved for that argument + if (conversion is { Kind: ConversionKind.ImplicitUserDefined }) + { + var argumentResultType = resultType.Type; + conversion = GenerateConversion(_conversions, argumentNoConversion, argumentResultType, parameterType.Type, fromExplicitCast: false, extensionMethodThisArgument: false); + if (!conversion.Exists && !argumentNoConversion.IsSuppressed) + { + Debug.Assert(argumentResultType is not null); + ReportNullabilityMismatchInArgument(argumentNoConversion.Syntax, argumentResultType, parameter, parameterType.Type, forOutput: false); + } + } + var stateAfterConversion = VisitConversion( conversionOpt: conversionOpt, conversionOperand: argumentNoConversion, @@ -5727,48 +5692,16 @@ private VariableState GetVariableState(Optional localState) private (ParameterSymbol? Parameter, TypeWithAnnotations Type, FlowAnalysisAnnotations Annotations, bool isExpandedParamsArgument) GetCorrespondingParameter( int argumentOrdinal, - ImmutableArray parameters, + ImmutableArray parametersOpt, ImmutableArray argsToParamsOpt, bool expanded) { - if (parameters.IsDefault) + if (parametersOpt.IsDefault) { return default; } - int n = parameters.Length; - ParameterSymbol? parameter; - - if (argsToParamsOpt.IsDefault) - { - if (argumentOrdinal < n) - { - parameter = parameters[argumentOrdinal]; - } - else if (expanded) - { - parameter = parameters[n - 1]; - } - else - { - parameter = null; - } - } - else - { - int parameterOrdinal = argsToParamsOpt[argumentOrdinal]; - - if (parameterOrdinal < n) - { - parameter = parameters[parameterOrdinal]; - } - else - { - parameter = null; - expanded = false; - } - } - + var parameter = Binder.GetCorrespondingParameter(argumentOrdinal, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { Debug.Assert(!expanded); @@ -5776,7 +5709,7 @@ private VariableState GetVariableState(Optional localState) } var type = parameter.TypeWithAnnotations; - if (expanded && parameter.Ordinal == n - 1 && type.IsSZArray()) + if (expanded && parameter.Ordinal == parametersOpt.Length - 1 && type.IsSZArray()) { type = ((ArrayTypeSymbol)type.Type).ElementTypeWithAnnotations; return (parameter, type, FlowAnalysisAnnotations.None, isExpandedParamsArgument: true); @@ -6392,17 +6325,6 @@ private void TrackNullableStateOfNullableValue(int containingSlot, TypeSymbol co } } - private void TrackNullableStateOfNullableValue(BoundExpression node, BoundExpression operand, TypeSymbol convertedType, TypeWithAnnotations underlyingType) - { - int valueSlot = MakeSlot(operand); - if (valueSlot > 0) - { - int containingSlot = GetOrCreatePlaceholderSlot(node); - Debug.Assert(containingSlot > 0); - TrackNullableStateOfNullableValue(containingSlot, convertedType, operand, underlyingType.ToTypeWithState(), valueSlot); - } - } - private void TrackNullableStateOfTupleConversion( BoundConversion? conversionOpt, BoundExpression convertedNode, @@ -8127,7 +8049,7 @@ private ImmutableArray GetDeconstructionRightParts(BoundExpress if (node.Operator.Kind.IsUserDefined() && (object)node.Operator.Method != null && node.Operator.Method.ParameterCount == 2) { MethodSymbol method = node.Operator.Method; - VisitArguments(node, ImmutableArray.Create(node.Left, right), method.ParameterRefKinds, method.Parameters, argsToParamsOpt: default, + VisitArguments(node, ImmutableArray.Create(node.Left, right), method.ParameterRefKinds, method.Parameters, argsToParamsOpt: default, defaultArguments: default, expanded: true, invokedAsExtensionMethod: false, method); } @@ -8304,7 +8226,7 @@ private void SplitIfBooleanConstant(BoundExpression node) indexer = (PropertySymbol)AsMemberOfType(receiverType, indexer); } - VisitArguments(node, node.Arguments, node.ArgumentRefKindsOpt, indexer, node.ArgsToParamsOpt, node.Expanded); + VisitArguments(node, node.Arguments, node.ArgumentRefKindsOpt, indexer, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded); var resultType = ApplyUnconditionalAnnotations(indexer.TypeWithAnnotations.ToTypeWithState(), GetRValueAnnotations(indexer)); SetResult(node, resultType, indexer.TypeWithAnnotations); @@ -8472,6 +8394,7 @@ protected override void VisitForEachExpression(BoundForEachStatement node) refKindsOpt: default, parameters, argsToParamsOpt: default, + defaultArguments: default, expanded: false, invokedAsExtensionMethod: true, enumeratorMethod); @@ -8571,6 +8494,41 @@ protected override void VisitForEachExpression(BoundForEachStatement node) currentPropertyGetterTypeWithState = ApplyUnconditionalAnnotations( currentPropertyGetter.ReturnTypeWithAnnotations.ToTypeWithState(), currentPropertyGetter.ReturnTypeFlowAnalysisAnnotations); + + // Analyze `await MoveNextAsync()` + if (node.AwaitOpt is { AwaitableInstancePlaceholder: BoundAwaitableValuePlaceholder moveNextPlaceholder } awaitMoveNextInfo) + { + var moveNextAsyncMethod = (MethodSymbol)AsMemberOfType(reinferredGetEnumeratorMethod.ReturnType, node.EnumeratorInfoOpt.MoveNextMethod); + + EnsureAwaitablePlaceholdersInitialized(); + var result = new VisitResult(GetReturnTypeWithState(moveNextAsyncMethod), moveNextAsyncMethod.ReturnTypeWithAnnotations); + _awaitablePlaceholdersOpt.Add(moveNextPlaceholder, (moveNextPlaceholder, result)); + Visit(awaitMoveNextInfo); + _awaitablePlaceholdersOpt.Remove(moveNextPlaceholder); + } + + // Analyze `await DisposeAsync()` + if (node.EnumeratorInfoOpt is { NeedsDisposal: true, DisposeAwaitableInfo: BoundAwaitableInfo awaitDisposalInfo }) + { + var disposalPlaceholder = awaitDisposalInfo.AwaitableInstancePlaceholder; + bool addedPlaceholder = false; + if (node.EnumeratorInfoOpt.DisposeMethod is not null) // no statically known Dispose method if doing a runtime check + { + Debug.Assert(disposalPlaceholder is not null); + var disposeAsyncMethod = (MethodSymbol)AsMemberOfType(reinferredGetEnumeratorMethod.ReturnType, node.EnumeratorInfoOpt.DisposeMethod); + EnsureAwaitablePlaceholdersInitialized(); + var result = new VisitResult(GetReturnTypeWithState(disposeAsyncMethod), disposeAsyncMethod.ReturnTypeWithAnnotations); + _awaitablePlaceholdersOpt.Add(disposalPlaceholder, (disposalPlaceholder, result)); + addedPlaceholder = true; + } + + Visit(awaitDisposalInfo); + + if (addedPlaceholder) + { + _awaitablePlaceholdersOpt!.Remove(disposalPlaceholder!); + } + } } SetResultType(expression: null, currentPropertyGetterTypeWithState); @@ -8921,7 +8879,7 @@ private TypeWithState InferResultNullabilityOfBinaryLogicalOperator(BoundExpress var placeholder = awaitableInfo.AwaitableInstancePlaceholder; Debug.Assert(placeholder is object); - _awaitablePlaceholdersOpt ??= PooledDictionary.GetInstance(); + EnsureAwaitablePlaceholdersInitialized(); _awaitablePlaceholdersOpt.Add(placeholder, (node.Expression, _visitResult)); Visit(awaitableInfo); _awaitablePlaceholdersOpt.Remove(placeholder); @@ -9065,7 +9023,7 @@ private TypeWithState InferResultNullabilityOfBinaryLogicalOperator(BoundExpress public override BoundNode? VisitArgListOperator(BoundArgListOperator node) { - VisitArgumentsEvaluate(node.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, expanded: false); + VisitArgumentsEvaluate(node.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); Debug.Assert(node.Type is null); SetNotNullResult(node); return null; @@ -9150,7 +9108,7 @@ private TypeWithState InferResultNullabilityOfBinaryLogicalOperator(BoundExpress CheckPossibleNullReceiver(receiverOpt, receiverType, checkNullableValueType: false); } - VisitArgumentsEvaluate(node.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, expanded: false); + VisitArgumentsEvaluate(node.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); Debug.Assert(node.Type.IsDynamic()); Debug.Assert(node.Type.IsReferenceType); var result = TypeWithAnnotations.Create(node.Type, NullableAnnotation.Oblivious); @@ -9189,7 +9147,7 @@ private TypeWithState InferResultNullabilityOfBinaryLogicalOperator(BoundExpress { Debug.Assert(!IsConditionalState); var arguments = node.Arguments; - var (argumentResults, _, _, _) = VisitArgumentsEvaluate(node.Syntax, arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, expanded: false); + var argumentResults = VisitArgumentsEvaluate(node.Syntax, arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); VisitObjectOrDynamicObjectCreation(node, arguments, argumentResults, node.InitializerExpressionOpt); return null; } @@ -9270,7 +9228,7 @@ private void SetUnknownResultNullability(BoundExpression expression) // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiver); - VisitArgumentsEvaluate(node.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, expanded: false); + VisitArgumentsEvaluate(node.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); Debug.Assert(node.Type.IsDynamic()); var result = TypeWithAnnotations.Create(node.Type, NullableAnnotation.Oblivious); SetLvalueResultType(node, result); @@ -9483,7 +9441,7 @@ protected override void VisitCatchBlock(BoundCatchBlock node, ref LocalState fin public override BoundNode? VisitAttribute(BoundAttribute node) { - VisitArguments(node, node.ConstructorArguments, ImmutableArray.Empty, node.Constructor, argsToParamsOpt: node.ConstructorArgumentsToParamsOpt, expanded: node.ConstructorExpanded, invokedAsExtensionMethod: false); + VisitArguments(node, node.ConstructorArguments, ImmutableArray.Empty, node.Constructor, argsToParamsOpt: node.ConstructorArgumentsToParamsOpt, defaultArguments: default, expanded: node.ConstructorExpanded, invokedAsExtensionMethod: false); foreach (var assignment in node.NamedArguments) { Visit(assignment); @@ -9512,6 +9470,12 @@ protected override void VisitCatchBlock(BoundCatchBlock node, ref LocalState fin return null; } + [MemberNotNull(nameof(_awaitablePlaceholdersOpt))] + private void EnsureAwaitablePlaceholdersInitialized() + { + _awaitablePlaceholdersOpt ??= PooledDictionary.GetInstance(); + } + public override BoundNode? VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node) { if (_awaitablePlaceholdersOpt != null && _awaitablePlaceholdersOpt.TryGetValue(node, out var value)) @@ -9543,6 +9507,7 @@ protected override void VisitCatchBlock(BoundCatchBlock node, ref LocalState fin node.ArgumentRefKindsOpt, node.FunctionPointer.Signature, argsToParamsOpt: default, + defaultArguments: default, expanded: false, invokedAsExtensionMethod: false); diff --git a/src/Compilers/CSharp/Portable/Generated/BoundNodes.xml.Generated.cs b/src/Compilers/CSharp/Portable/Generated/BoundNodes.xml.Generated.cs index f5c29da8ce4d8..ef64a23120a14 100644 --- a/src/Compilers/CSharp/Portable/Generated/BoundNodes.xml.Generated.cs +++ b/src/Compilers/CSharp/Portable/Generated/BoundNodes.xml.Generated.cs @@ -5641,7 +5641,7 @@ public BoundPropertyGroup Update(ImmutableArray properties, Boun internal sealed partial class BoundCall : BoundExpression { - public BoundCall(SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol method, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool isDelegateCall, bool expanded, bool invokedAsExtensionMethod, ImmutableArray argsToParamsOpt, LookupResultKind resultKind, ImmutableArray originalMethodsOpt, Binder? binderOpt, TypeSymbol type, bool hasErrors = false) + public BoundCall(SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol method, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool isDelegateCall, bool expanded, bool invokedAsExtensionMethod, ImmutableArray argsToParamsOpt, BitVector defaultArguments, LookupResultKind resultKind, ImmutableArray originalMethodsOpt, Binder? binderOpt, TypeSymbol type, bool hasErrors = false) : base(BoundKind.Call, syntax, type, hasErrors || receiverOpt.HasErrors() || arguments.HasErrors()) { @@ -5658,6 +5658,7 @@ public BoundCall(SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol m this.Expanded = expanded; this.InvokedAsExtensionMethod = invokedAsExtensionMethod; this.ArgsToParamsOpt = argsToParamsOpt; + this.DefaultArguments = defaultArguments; this._ResultKind = resultKind; this.OriginalMethodsOpt = originalMethodsOpt; this.BinderOpt = binderOpt; @@ -5684,6 +5685,8 @@ public BoundCall(SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol m public ImmutableArray ArgsToParamsOpt { get; } + public BitVector DefaultArguments { get; } + private readonly LookupResultKind _ResultKind; public override LookupResultKind ResultKind { get { return _ResultKind; } } @@ -5693,11 +5696,11 @@ public BoundCall(SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol m [DebuggerStepThrough] public override BoundNode? Accept(BoundTreeVisitor visitor) => visitor.VisitCall(this); - public BoundCall Update(BoundExpression? receiverOpt, MethodSymbol method, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool isDelegateCall, bool expanded, bool invokedAsExtensionMethod, ImmutableArray argsToParamsOpt, LookupResultKind resultKind, ImmutableArray originalMethodsOpt, Binder? binderOpt, TypeSymbol type) + public BoundCall Update(BoundExpression? receiverOpt, MethodSymbol method, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool isDelegateCall, bool expanded, bool invokedAsExtensionMethod, ImmutableArray argsToParamsOpt, BitVector defaultArguments, LookupResultKind resultKind, ImmutableArray originalMethodsOpt, Binder? binderOpt, TypeSymbol type) { - if (receiverOpt != this.ReceiverOpt || !Symbols.SymbolEqualityComparer.ConsiderEverything.Equals(method, this.Method) || arguments != this.Arguments || argumentNamesOpt != this.ArgumentNamesOpt || argumentRefKindsOpt != this.ArgumentRefKindsOpt || isDelegateCall != this.IsDelegateCall || expanded != this.Expanded || invokedAsExtensionMethod != this.InvokedAsExtensionMethod || argsToParamsOpt != this.ArgsToParamsOpt || resultKind != this.ResultKind || originalMethodsOpt != this.OriginalMethodsOpt || binderOpt != this.BinderOpt || !TypeSymbol.Equals(type, this.Type, TypeCompareKind.ConsiderEverything)) + if (receiverOpt != this.ReceiverOpt || !Symbols.SymbolEqualityComparer.ConsiderEverything.Equals(method, this.Method) || arguments != this.Arguments || argumentNamesOpt != this.ArgumentNamesOpt || argumentRefKindsOpt != this.ArgumentRefKindsOpt || isDelegateCall != this.IsDelegateCall || expanded != this.Expanded || invokedAsExtensionMethod != this.InvokedAsExtensionMethod || argsToParamsOpt != this.ArgsToParamsOpt || defaultArguments != this.DefaultArguments || resultKind != this.ResultKind || originalMethodsOpt != this.OriginalMethodsOpt || binderOpt != this.BinderOpt || !TypeSymbol.Equals(type, this.Type, TypeCompareKind.ConsiderEverything)) { - var result = new BoundCall(this.Syntax, receiverOpt, method, arguments, argumentNamesOpt, argumentRefKindsOpt, isDelegateCall, expanded, invokedAsExtensionMethod, argsToParamsOpt, resultKind, originalMethodsOpt, binderOpt, type, this.HasErrors); + var result = new BoundCall(this.Syntax, receiverOpt, method, arguments, argumentNamesOpt, argumentRefKindsOpt, isDelegateCall, expanded, invokedAsExtensionMethod, argsToParamsOpt, defaultArguments, resultKind, originalMethodsOpt, binderOpt, type, this.HasErrors); result.CopyAttributes(this); return result; } @@ -5841,7 +5844,7 @@ public BoundUnconvertedObjectCreationExpression Update(ImmutableArray constructorsGroup, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, ConstantValue? constantValueOpt, BoundObjectInitializerExpressionBase? initializerExpressionOpt, bool wasTargetTyped, Binder? binderOpt, TypeSymbol type, bool hasErrors = false) + public BoundObjectCreationExpression(SyntaxNode syntax, MethodSymbol constructor, ImmutableArray constructorsGroup, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, ConstantValue? constantValueOpt, BoundObjectInitializerExpressionBase? initializerExpressionOpt, bool wasTargetTyped, Binder? binderOpt, TypeSymbol type, bool hasErrors = false) : base(BoundKind.ObjectCreationExpression, syntax, type, hasErrors || arguments.HasErrors() || initializerExpressionOpt.HasErrors()) { @@ -5857,6 +5860,7 @@ public BoundObjectCreationExpression(SyntaxNode syntax, MethodSymbol constructor this.ArgumentRefKindsOpt = argumentRefKindsOpt; this.Expanded = expanded; this.ArgsToParamsOpt = argsToParamsOpt; + this.DefaultArguments = defaultArguments; this.ConstantValueOpt = constantValueOpt; this.InitializerExpressionOpt = initializerExpressionOpt; this.WasTargetTyped = wasTargetTyped; @@ -5880,6 +5884,8 @@ public BoundObjectCreationExpression(SyntaxNode syntax, MethodSymbol constructor public ImmutableArray ArgsToParamsOpt { get; } + public BitVector DefaultArguments { get; } + public ConstantValue? ConstantValueOpt { get; } public BoundObjectInitializerExpressionBase? InitializerExpressionOpt { get; } @@ -5890,11 +5896,11 @@ public BoundObjectCreationExpression(SyntaxNode syntax, MethodSymbol constructor [DebuggerStepThrough] public override BoundNode? Accept(BoundTreeVisitor visitor) => visitor.VisitObjectCreationExpression(this); - public BoundObjectCreationExpression Update(MethodSymbol constructor, ImmutableArray constructorsGroup, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, ConstantValue? constantValueOpt, BoundObjectInitializerExpressionBase? initializerExpressionOpt, bool wasTargetTyped, Binder? binderOpt, TypeSymbol type) + public BoundObjectCreationExpression Update(MethodSymbol constructor, ImmutableArray constructorsGroup, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, ConstantValue? constantValueOpt, BoundObjectInitializerExpressionBase? initializerExpressionOpt, bool wasTargetTyped, Binder? binderOpt, TypeSymbol type) { - if (!Symbols.SymbolEqualityComparer.ConsiderEverything.Equals(constructor, this.Constructor) || constructorsGroup != this.ConstructorsGroup || arguments != this.Arguments || argumentNamesOpt != this.ArgumentNamesOpt || argumentRefKindsOpt != this.ArgumentRefKindsOpt || expanded != this.Expanded || argsToParamsOpt != this.ArgsToParamsOpt || constantValueOpt != this.ConstantValueOpt || initializerExpressionOpt != this.InitializerExpressionOpt || wasTargetTyped != this.WasTargetTyped || binderOpt != this.BinderOpt || !TypeSymbol.Equals(type, this.Type, TypeCompareKind.ConsiderEverything)) + if (!Symbols.SymbolEqualityComparer.ConsiderEverything.Equals(constructor, this.Constructor) || constructorsGroup != this.ConstructorsGroup || arguments != this.Arguments || argumentNamesOpt != this.ArgumentNamesOpt || argumentRefKindsOpt != this.ArgumentRefKindsOpt || expanded != this.Expanded || argsToParamsOpt != this.ArgsToParamsOpt || defaultArguments != this.DefaultArguments || constantValueOpt != this.ConstantValueOpt || initializerExpressionOpt != this.InitializerExpressionOpt || wasTargetTyped != this.WasTargetTyped || binderOpt != this.BinderOpt || !TypeSymbol.Equals(type, this.Type, TypeCompareKind.ConsiderEverything)) { - var result = new BoundObjectCreationExpression(this.Syntax, constructor, constructorsGroup, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, constantValueOpt, initializerExpressionOpt, wasTargetTyped, binderOpt, type, this.HasErrors); + var result = new BoundObjectCreationExpression(this.Syntax, constructor, constructorsGroup, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, constantValueOpt, initializerExpressionOpt, wasTargetTyped, binderOpt, type, this.HasErrors); result.CopyAttributes(this); return result; } @@ -6113,7 +6119,7 @@ public BoundObjectInitializerExpression Update(BoundObjectOrCollectionValuePlace internal sealed partial class BoundObjectInitializerMember : BoundExpression { - public BoundObjectInitializerMember(SyntaxNode syntax, Symbol? memberSymbol, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, LookupResultKind resultKind, TypeSymbol receiverType, Binder binder, TypeSymbol type, bool hasErrors = false) + public BoundObjectInitializerMember(SyntaxNode syntax, Symbol? memberSymbol, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, LookupResultKind resultKind, TypeSymbol receiverType, Binder binder, TypeSymbol type, bool hasErrors = false) : base(BoundKind.ObjectInitializerMember, syntax, type, hasErrors || arguments.HasErrors()) { @@ -6128,6 +6134,7 @@ public BoundObjectInitializerMember(SyntaxNode syntax, Symbol? memberSymbol, Imm this.ArgumentRefKindsOpt = argumentRefKindsOpt; this.Expanded = expanded; this.ArgsToParamsOpt = argsToParamsOpt; + this.DefaultArguments = defaultArguments; this._ResultKind = resultKind; this.ReceiverType = receiverType; this.Binder = binder; @@ -6148,6 +6155,8 @@ public BoundObjectInitializerMember(SyntaxNode syntax, Symbol? memberSymbol, Imm public ImmutableArray ArgsToParamsOpt { get; } + public BitVector DefaultArguments { get; } + private readonly LookupResultKind _ResultKind; public override LookupResultKind ResultKind { get { return _ResultKind; } } @@ -6157,11 +6166,11 @@ public BoundObjectInitializerMember(SyntaxNode syntax, Symbol? memberSymbol, Imm [DebuggerStepThrough] public override BoundNode? Accept(BoundTreeVisitor visitor) => visitor.VisitObjectInitializerMember(this); - public BoundObjectInitializerMember Update(Symbol? memberSymbol, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, LookupResultKind resultKind, TypeSymbol receiverType, Binder binder, TypeSymbol type) + public BoundObjectInitializerMember Update(Symbol? memberSymbol, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, LookupResultKind resultKind, TypeSymbol receiverType, Binder binder, TypeSymbol type) { - if (!Symbols.SymbolEqualityComparer.ConsiderEverything.Equals(memberSymbol, this.MemberSymbol) || arguments != this.Arguments || argumentNamesOpt != this.ArgumentNamesOpt || argumentRefKindsOpt != this.ArgumentRefKindsOpt || expanded != this.Expanded || argsToParamsOpt != this.ArgsToParamsOpt || resultKind != this.ResultKind || !TypeSymbol.Equals(receiverType, this.ReceiverType, TypeCompareKind.ConsiderEverything) || binder != this.Binder || !TypeSymbol.Equals(type, this.Type, TypeCompareKind.ConsiderEverything)) + if (!Symbols.SymbolEqualityComparer.ConsiderEverything.Equals(memberSymbol, this.MemberSymbol) || arguments != this.Arguments || argumentNamesOpt != this.ArgumentNamesOpt || argumentRefKindsOpt != this.ArgumentRefKindsOpt || expanded != this.Expanded || argsToParamsOpt != this.ArgsToParamsOpt || defaultArguments != this.DefaultArguments || resultKind != this.ResultKind || !TypeSymbol.Equals(receiverType, this.ReceiverType, TypeCompareKind.ConsiderEverything) || binder != this.Binder || !TypeSymbol.Equals(type, this.Type, TypeCompareKind.ConsiderEverything)) { - var result = new BoundObjectInitializerMember(this.Syntax, memberSymbol, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, resultKind, receiverType, binder, type, this.HasErrors); + var result = new BoundObjectInitializerMember(this.Syntax, memberSymbol, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, resultKind, receiverType, binder, type, this.HasErrors); result.CopyAttributes(this); return result; } @@ -6245,7 +6254,7 @@ public BoundCollectionInitializerExpression Update(BoundObjectOrCollectionValueP internal sealed partial class BoundCollectionElementInitializer : BoundExpression { - public BoundCollectionElementInitializer(SyntaxNode syntax, MethodSymbol addMethod, ImmutableArray arguments, BoundExpression? implicitReceiverOpt, bool expanded, ImmutableArray argsToParamsOpt, bool invokedAsExtensionMethod, LookupResultKind resultKind, Binder? binderOpt, TypeSymbol type, bool hasErrors = false) + public BoundCollectionElementInitializer(SyntaxNode syntax, MethodSymbol addMethod, ImmutableArray arguments, BoundExpression? implicitReceiverOpt, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, bool invokedAsExtensionMethod, LookupResultKind resultKind, Binder? binderOpt, TypeSymbol type, bool hasErrors = false) : base(BoundKind.CollectionElementInitializer, syntax, type, hasErrors || arguments.HasErrors() || implicitReceiverOpt.HasErrors()) { @@ -6258,6 +6267,7 @@ public BoundCollectionElementInitializer(SyntaxNode syntax, MethodSymbol addMeth this.ImplicitReceiverOpt = implicitReceiverOpt; this.Expanded = expanded; this.ArgsToParamsOpt = argsToParamsOpt; + this.DefaultArguments = defaultArguments; this.InvokedAsExtensionMethod = invokedAsExtensionMethod; this._ResultKind = resultKind; this.BinderOpt = binderOpt; @@ -6276,6 +6286,8 @@ public BoundCollectionElementInitializer(SyntaxNode syntax, MethodSymbol addMeth public ImmutableArray ArgsToParamsOpt { get; } + public BitVector DefaultArguments { get; } + public bool InvokedAsExtensionMethod { get; } private readonly LookupResultKind _ResultKind; @@ -6285,11 +6297,11 @@ public BoundCollectionElementInitializer(SyntaxNode syntax, MethodSymbol addMeth [DebuggerStepThrough] public override BoundNode? Accept(BoundTreeVisitor visitor) => visitor.VisitCollectionElementInitializer(this); - public BoundCollectionElementInitializer Update(MethodSymbol addMethod, ImmutableArray arguments, BoundExpression? implicitReceiverOpt, bool expanded, ImmutableArray argsToParamsOpt, bool invokedAsExtensionMethod, LookupResultKind resultKind, Binder? binderOpt, TypeSymbol type) + public BoundCollectionElementInitializer Update(MethodSymbol addMethod, ImmutableArray arguments, BoundExpression? implicitReceiverOpt, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, bool invokedAsExtensionMethod, LookupResultKind resultKind, Binder? binderOpt, TypeSymbol type) { - if (!Symbols.SymbolEqualityComparer.ConsiderEverything.Equals(addMethod, this.AddMethod) || arguments != this.Arguments || implicitReceiverOpt != this.ImplicitReceiverOpt || expanded != this.Expanded || argsToParamsOpt != this.ArgsToParamsOpt || invokedAsExtensionMethod != this.InvokedAsExtensionMethod || resultKind != this.ResultKind || binderOpt != this.BinderOpt || !TypeSymbol.Equals(type, this.Type, TypeCompareKind.ConsiderEverything)) + if (!Symbols.SymbolEqualityComparer.ConsiderEverything.Equals(addMethod, this.AddMethod) || arguments != this.Arguments || implicitReceiverOpt != this.ImplicitReceiverOpt || expanded != this.Expanded || argsToParamsOpt != this.ArgsToParamsOpt || defaultArguments != this.DefaultArguments || invokedAsExtensionMethod != this.InvokedAsExtensionMethod || resultKind != this.ResultKind || binderOpt != this.BinderOpt || !TypeSymbol.Equals(type, this.Type, TypeCompareKind.ConsiderEverything)) { - var result = new BoundCollectionElementInitializer(this.Syntax, addMethod, arguments, implicitReceiverOpt, expanded, argsToParamsOpt, invokedAsExtensionMethod, resultKind, binderOpt, type, this.HasErrors); + var result = new BoundCollectionElementInitializer(this.Syntax, addMethod, arguments, implicitReceiverOpt, expanded, argsToParamsOpt, defaultArguments, invokedAsExtensionMethod, resultKind, binderOpt, type, this.HasErrors); result.CopyAttributes(this); return result; } @@ -6822,7 +6834,7 @@ public BoundEventAccess Update(BoundExpression? receiverOpt, EventSymbol eventSy internal sealed partial class BoundIndexerAccess : BoundExpression { - public BoundIndexerAccess(SyntaxNode syntax, BoundExpression? receiverOpt, PropertySymbol indexer, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, Binder? binderOpt, bool useSetterForDefaultArgumentGeneration, ImmutableArray originalIndexersOpt, TypeSymbol type, bool hasErrors = false) + public BoundIndexerAccess(SyntaxNode syntax, BoundExpression? receiverOpt, PropertySymbol indexer, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, Binder? binderOpt, ImmutableArray originalIndexersOpt, TypeSymbol type, bool hasErrors = false) : base(BoundKind.IndexerAccess, syntax, type, hasErrors || receiverOpt.HasErrors() || arguments.HasErrors()) { @@ -6837,8 +6849,8 @@ public BoundIndexerAccess(SyntaxNode syntax, BoundExpression? receiverOpt, Prope this.ArgumentRefKindsOpt = argumentRefKindsOpt; this.Expanded = expanded; this.ArgsToParamsOpt = argsToParamsOpt; + this.DefaultArguments = defaultArguments; this.BinderOpt = binderOpt; - this.UseSetterForDefaultArgumentGeneration = useSetterForDefaultArgumentGeneration; this.OriginalIndexersOpt = originalIndexersOpt; } @@ -6859,19 +6871,19 @@ public BoundIndexerAccess(SyntaxNode syntax, BoundExpression? receiverOpt, Prope public ImmutableArray ArgsToParamsOpt { get; } - public Binder? BinderOpt { get; } + public BitVector DefaultArguments { get; } - public bool UseSetterForDefaultArgumentGeneration { get; } + public Binder? BinderOpt { get; } public ImmutableArray OriginalIndexersOpt { get; } [DebuggerStepThrough] public override BoundNode? Accept(BoundTreeVisitor visitor) => visitor.VisitIndexerAccess(this); - public BoundIndexerAccess Update(BoundExpression? receiverOpt, PropertySymbol indexer, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, Binder? binderOpt, bool useSetterForDefaultArgumentGeneration, ImmutableArray originalIndexersOpt, TypeSymbol type) + public BoundIndexerAccess Update(BoundExpression? receiverOpt, PropertySymbol indexer, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, Binder? binderOpt, ImmutableArray originalIndexersOpt, TypeSymbol type) { - if (receiverOpt != this.ReceiverOpt || !Symbols.SymbolEqualityComparer.ConsiderEverything.Equals(indexer, this.Indexer) || arguments != this.Arguments || argumentNamesOpt != this.ArgumentNamesOpt || argumentRefKindsOpt != this.ArgumentRefKindsOpt || expanded != this.Expanded || argsToParamsOpt != this.ArgsToParamsOpt || binderOpt != this.BinderOpt || useSetterForDefaultArgumentGeneration != this.UseSetterForDefaultArgumentGeneration || originalIndexersOpt != this.OriginalIndexersOpt || !TypeSymbol.Equals(type, this.Type, TypeCompareKind.ConsiderEverything)) + if (receiverOpt != this.ReceiverOpt || !Symbols.SymbolEqualityComparer.ConsiderEverything.Equals(indexer, this.Indexer) || arguments != this.Arguments || argumentNamesOpt != this.ArgumentNamesOpt || argumentRefKindsOpt != this.ArgumentRefKindsOpt || expanded != this.Expanded || argsToParamsOpt != this.ArgsToParamsOpt || defaultArguments != this.DefaultArguments || binderOpt != this.BinderOpt || originalIndexersOpt != this.OriginalIndexersOpt || !TypeSymbol.Equals(type, this.Type, TypeCompareKind.ConsiderEverything)) { - var result = new BoundIndexerAccess(this.Syntax, receiverOpt, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, binderOpt, useSetterForDefaultArgumentGeneration, originalIndexersOpt, type, this.HasErrors); + var result = new BoundIndexerAccess(this.Syntax, receiverOpt, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, binderOpt, originalIndexersOpt, type, this.HasErrors); result.CopyAttributes(this); return result; } @@ -10507,7 +10519,7 @@ internal abstract partial class BoundTreeRewriter : BoundTreeVisitor BoundExpression? receiverOpt = (BoundExpression?)this.Visit(node.ReceiverOpt); ImmutableArray arguments = this.VisitList(node.Arguments); TypeSymbol? type = this.VisitType(node.Type); - return node.Update(receiverOpt, node.Method, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.IsDelegateCall, node.Expanded, node.InvokedAsExtensionMethod, node.ArgsToParamsOpt, node.ResultKind, node.OriginalMethodsOpt, node.BinderOpt, type); + return node.Update(receiverOpt, node.Method, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.IsDelegateCall, node.Expanded, node.InvokedAsExtensionMethod, node.ArgsToParamsOpt, node.DefaultArguments, node.ResultKind, node.OriginalMethodsOpt, node.BinderOpt, type); } public override BoundNode? VisitEventAssignmentOperator(BoundEventAssignmentOperator node) { @@ -10534,7 +10546,7 @@ internal abstract partial class BoundTreeRewriter : BoundTreeVisitor ImmutableArray arguments = this.VisitList(node.Arguments); BoundObjectInitializerExpressionBase? initializerExpressionOpt = (BoundObjectInitializerExpressionBase?)this.Visit(node.InitializerExpressionOpt); TypeSymbol? type = this.VisitType(node.Type); - return node.Update(node.Constructor, node.ConstructorsGroup, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.ConstantValueOpt, initializerExpressionOpt, node.WasTargetTyped, node.BinderOpt, type); + return node.Update(node.Constructor, node.ConstructorsGroup, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.ConstantValueOpt, initializerExpressionOpt, node.WasTargetTyped, node.BinderOpt, type); } public override BoundNode? VisitTupleLiteral(BoundTupleLiteral node) { @@ -10574,7 +10586,7 @@ internal abstract partial class BoundTreeRewriter : BoundTreeVisitor ImmutableArray arguments = this.VisitList(node.Arguments); TypeSymbol? receiverType = this.VisitType(node.ReceiverType); TypeSymbol? type = this.VisitType(node.Type); - return node.Update(node.MemberSymbol, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.ResultKind, receiverType, node.Binder, type); + return node.Update(node.MemberSymbol, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.ResultKind, receiverType, node.Binder, type); } public override BoundNode? VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) { @@ -10594,7 +10606,7 @@ internal abstract partial class BoundTreeRewriter : BoundTreeVisitor ImmutableArray arguments = this.VisitList(node.Arguments); BoundExpression? implicitReceiverOpt = (BoundExpression?)this.Visit(node.ImplicitReceiverOpt); TypeSymbol? type = this.VisitType(node.Type); - return node.Update(node.AddMethod, arguments, implicitReceiverOpt, node.Expanded, node.ArgsToParamsOpt, node.InvokedAsExtensionMethod, node.ResultKind, node.BinderOpt, type); + return node.Update(node.AddMethod, arguments, implicitReceiverOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.InvokedAsExtensionMethod, node.ResultKind, node.BinderOpt, type); } public override BoundNode? VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) { @@ -10689,7 +10701,7 @@ internal abstract partial class BoundTreeRewriter : BoundTreeVisitor BoundExpression? receiverOpt = (BoundExpression?)this.Visit(node.ReceiverOpt); ImmutableArray arguments = this.VisitList(node.Arguments); TypeSymbol? type = this.VisitType(node.Type); - return node.Update(receiverOpt, node.Indexer, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.BinderOpt, node.UseSetterForDefaultArgumentGeneration, node.OriginalIndexersOpt, type); + return node.Update(receiverOpt, node.Indexer, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.BinderOpt, node.OriginalIndexersOpt, type); } public override BoundNode? VisitIndexOrRangePatternIndexerAccess(BoundIndexOrRangePatternIndexerAccess node) { @@ -12376,12 +12388,12 @@ public NullabilityRewriter(ImmutableDictionaryProvides the base class from which the classes that represent name syntax nodes are derived. This is an abstract class. internal abstract partial class NameSyntax : TypeSyntax { @@ -34120,6 +34122,7 @@ public override CSharpSyntaxNode VisitNullableDirectiveTrivia(NullableDirectiveT internal partial class ContextAwareSyntax { + private SyntaxFactoryContext context; public ContextAwareSyntax(SyntaxFactoryContext context) @@ -38993,6 +38996,7 @@ public NullableDirectiveTriviaSyntax NullableDirectiveTrivia(SyntaxToken hashTok internal static partial class SyntaxFactory { + public static IdentifierNameSyntax IdentifierName(SyntaxToken identifier) { #if DEBUG diff --git a/src/Compilers/CSharp/Portable/Generated/Syntax.xml.Main.Generated.cs b/src/Compilers/CSharp/Portable/Generated/CSharpSyntaxGenerator/CSharpSyntaxGenerator.SourceGenerator/Syntax.xml.Main.Generated.cs similarity index 99% rename from src/Compilers/CSharp/Portable/Generated/Syntax.xml.Main.Generated.cs rename to src/Compilers/CSharp/Portable/Generated/CSharpSyntaxGenerator/CSharpSyntaxGenerator.SourceGenerator/Syntax.xml.Main.Generated.cs index 74055633d91a7..86a0e9c3dc084 100644 --- a/src/Compilers/CSharp/Portable/Generated/Syntax.xml.Main.Generated.cs +++ b/src/Compilers/CSharp/Portable/Generated/CSharpSyntaxGenerator/CSharpSyntaxGenerator.SourceGenerator/Syntax.xml.Main.Generated.cs @@ -2103,6 +2103,7 @@ public partial class CSharpSyntaxRewriter : CSharpSyntaxVisitor public static partial class SyntaxFactory { + /// Creates a new IdentifierNameSyntax instance. public static IdentifierNameSyntax IdentifierName(SyntaxToken identifier) { diff --git a/src/Compilers/CSharp/Portable/Generated/Syntax.xml.Syntax.Generated.cs b/src/Compilers/CSharp/Portable/Generated/CSharpSyntaxGenerator/CSharpSyntaxGenerator.SourceGenerator/Syntax.xml.Syntax.Generated.cs similarity index 99% rename from src/Compilers/CSharp/Portable/Generated/Syntax.xml.Syntax.Generated.cs rename to src/Compilers/CSharp/Portable/Generated/CSharpSyntaxGenerator/CSharpSyntaxGenerator.SourceGenerator/Syntax.xml.Syntax.Generated.cs index 6aa40db272bb6..04aa76e5e9761 100644 --- a/src/Compilers/CSharp/Portable/Generated/Syntax.xml.Syntax.Generated.cs +++ b/src/Compilers/CSharp/Portable/Generated/CSharpSyntaxGenerator/CSharpSyntaxGenerator.SourceGenerator/Syntax.xml.Syntax.Generated.cs @@ -10,6 +10,8 @@ namespace Microsoft.CodeAnalysis.CSharp.Syntax { + + /// Provides the base class from which the classes that represent name syntax nodes are derived. This is an abstract class. public abstract partial class NameSyntax : TypeSyntax { @@ -42,6 +44,7 @@ internal SimpleNameSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? par /// public sealed partial class IdentifierNameSyntax : SimpleNameSyntax { + internal IdentifierNameSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -321,6 +324,7 @@ internal TypeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, i /// public sealed partial class PredefinedTypeSyntax : TypeSyntax { + internal PredefinedTypeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -753,6 +757,7 @@ public FunctionPointerUnmanagedCallingConventionListSyntax Update(SyntaxToken op /// public sealed partial class FunctionPointerUnmanagedCallingConventionSyntax : CSharpSyntaxNode { + internal FunctionPointerUnmanagedCallingConventionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -946,6 +951,7 @@ public TupleElementSyntax Update(TypeSyntax type, SyntaxToken identifier) /// public sealed partial class OmittedTypeArgumentSyntax : TypeSyntax { + internal OmittedTypeArgumentSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -1863,6 +1869,7 @@ internal InstanceExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxN /// public sealed partial class ThisExpressionSyntax : InstanceExpressionSyntax { + internal ThisExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -1902,6 +1909,7 @@ public ThisExpressionSyntax Update(SyntaxToken token) /// public sealed partial class BaseExpressionSyntax : InstanceExpressionSyntax { + internal BaseExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -1948,6 +1956,7 @@ public BaseExpressionSyntax Update(SyntaxToken token) /// public sealed partial class LiteralExpressionSyntax : ExpressionSyntax { + internal LiteralExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -4290,6 +4299,7 @@ public JoinClauseSyntax Update(SyntaxToken joinKeyword, TypeSyntax? type, Syntax /// public sealed partial class JoinIntoClauseSyntax : CSharpSyntaxNode { + internal JoinIntoClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -4626,6 +4636,7 @@ public QueryContinuationSyntax Update(SyntaxToken intoKeyword, SyntaxToken ident /// public sealed partial class OmittedArraySizeExpressionSyntax : ExpressionSyntax { + internal OmittedArraySizeExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -4867,6 +4878,7 @@ internal PatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent /// public sealed partial class DiscardPatternSyntax : PatternSyntax { + internal DiscardPatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -5519,6 +5531,7 @@ internal InterpolatedStringContentSyntax(InternalSyntax.CSharpSyntaxNode green, /// public sealed partial class InterpolatedStringTextSyntax : InterpolatedStringContentSyntax { + internal InterpolatedStringTextSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -5666,6 +5679,7 @@ public InterpolationAlignmentClauseSyntax Update(SyntaxToken commaToken, Express /// public sealed partial class InterpolationFormatClauseSyntax : CSharpSyntaxNode { + internal InterpolationFormatClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -6267,6 +6281,7 @@ internal VariableDesignationSyntax(InternalSyntax.CSharpSyntaxNode green, Syntax /// public sealed partial class SingleVariableDesignationSyntax : VariableDesignationSyntax { + internal SingleVariableDesignationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -6304,6 +6319,7 @@ public SingleVariableDesignationSyntax Update(SyntaxToken identifier) /// public sealed partial class DiscardDesignationSyntax : VariableDesignationSyntax { + internal DiscardDesignationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -8319,6 +8335,7 @@ public CaseSwitchLabelSyntax Update(SyntaxToken keyword, ExpressionSyntax value, /// public sealed partial class DefaultSwitchLabelSyntax : SwitchLabelSyntax { + internal DefaultSwitchLabelSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -8870,6 +8887,7 @@ public CompilationUnitSyntax Update(SyntaxList exter /// public sealed partial class ExternAliasDirectiveSyntax : CSharpSyntaxNode { + internal ExternAliasDirectiveSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -9205,6 +9223,7 @@ public AttributeListSyntax Update(SyntaxToken openBracketToken, AttributeTargetS /// public sealed partial class AttributeTargetSpecifierSyntax : CSharpSyntaxNode { + internal AttributeTargetSpecifierSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -10819,6 +10838,7 @@ internal TypeParameterConstraintSyntax(InternalSyntax.CSharpSyntaxNode green, Sy /// public sealed partial class ConstructorConstraintSyntax : TypeParameterConstraintSyntax { + internal ConstructorConstraintSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -10867,6 +10887,7 @@ public ConstructorConstraintSyntax Update(SyntaxToken newKeyword, SyntaxToken op /// public sealed partial class ClassOrStructConstraintSyntax : TypeParameterConstraintSyntax { + internal ClassOrStructConstraintSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -10958,6 +10979,7 @@ public TypeConstraintSyntax Update(TypeSyntax type) /// public sealed partial class DefaultConstraintSyntax : TypeParameterConstraintSyntax { + internal DefaultConstraintSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -12951,6 +12973,7 @@ public IncompleteMemberSyntax Update(SyntaxList attributeLi /// public sealed partial class SkippedTokensTriviaSyntax : StructuredTriviaSyntax { + internal SkippedTokensTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -13908,6 +13931,7 @@ public XmlNameSyntax Update(XmlPrefixSyntax? prefix, SyntaxToken localName) /// public sealed partial class XmlPrefixSyntax : CSharpSyntaxNode { + internal XmlPrefixSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -14172,6 +14196,7 @@ public XmlNameAttributeSyntax Update(XmlNameSyntax name, SyntaxToken equalsToken /// public sealed partial class XmlTextSyntax : XmlNodeSyntax { + internal XmlTextSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -14218,6 +14243,7 @@ public XmlTextSyntax Update(SyntaxTokenList textTokens) /// public sealed partial class XmlCDataSectionSyntax : XmlNodeSyntax { + internal XmlCDataSectionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -14327,6 +14353,7 @@ public XmlProcessingInstructionSyntax Update(SyntaxToken startProcessingInstruct /// public sealed partial class XmlCommentSyntax : XmlNodeSyntax { + internal XmlCommentSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -14544,6 +14571,7 @@ public ElifDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken elifK /// public sealed partial class ElseDirectiveTriviaSyntax : BranchingDirectiveTriviaSyntax { + internal ElseDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -14595,6 +14623,7 @@ public ElseDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken elseK /// public sealed partial class EndIfDirectiveTriviaSyntax : DirectiveTriviaSyntax { + internal EndIfDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -14643,6 +14672,7 @@ public EndIfDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken endI /// public sealed partial class RegionDirectiveTriviaSyntax : DirectiveTriviaSyntax { + internal RegionDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -14691,6 +14721,7 @@ public RegionDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken reg /// public sealed partial class EndRegionDirectiveTriviaSyntax : DirectiveTriviaSyntax { + internal EndRegionDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -14739,6 +14770,7 @@ public EndRegionDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken /// public sealed partial class ErrorDirectiveTriviaSyntax : DirectiveTriviaSyntax { + internal ErrorDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -14787,6 +14819,7 @@ public ErrorDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken erro /// public sealed partial class WarningDirectiveTriviaSyntax : DirectiveTriviaSyntax { + internal WarningDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -14835,6 +14868,7 @@ public WarningDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken wa /// public sealed partial class BadDirectiveTriviaSyntax : DirectiveTriviaSyntax { + internal BadDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -14883,6 +14917,7 @@ public BadDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken identi /// public sealed partial class DefineDirectiveTriviaSyntax : DirectiveTriviaSyntax { + internal DefineDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -14934,6 +14969,7 @@ public DefineDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken def /// public sealed partial class UndefDirectiveTriviaSyntax : DirectiveTriviaSyntax { + internal UndefDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -14985,6 +15021,7 @@ public UndefDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken unde /// public sealed partial class LineDirectiveTriviaSyntax : DirectiveTriviaSyntax { + internal LineDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -15114,6 +15151,7 @@ public PragmaWarningDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxTo /// public sealed partial class PragmaChecksumDirectiveTriviaSyntax : DirectiveTriviaSyntax { + internal PragmaChecksumDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -15174,6 +15212,7 @@ public PragmaChecksumDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxT /// public sealed partial class ReferenceDirectiveTriviaSyntax : DirectiveTriviaSyntax { + internal ReferenceDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -15225,6 +15264,7 @@ public ReferenceDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken /// public sealed partial class LoadDirectiveTriviaSyntax : DirectiveTriviaSyntax { + internal LoadDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -15276,6 +15316,7 @@ public LoadDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken loadK /// public sealed partial class ShebangDirectiveTriviaSyntax : DirectiveTriviaSyntax { + internal ShebangDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { @@ -15324,6 +15365,7 @@ public ShebangDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken ex /// public sealed partial class NullableDirectiveTriviaSyntax : DirectiveTriviaSyntax { + internal NullableDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { diff --git a/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureConversion.cs b/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureConversion.cs index 41775a76deae9..3cb69bb42616f 100644 --- a/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureConversion.cs +++ b/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureConversion.cs @@ -1057,6 +1057,7 @@ public override BoundNode VisitCall(BoundCall node) node.Expanded, node.InvokedAsExtensionMethod, node.ArgsToParamsOpt, + node.DefaultArguments, node.ResultKind, node.BinderOpt, type); diff --git a/src/Compilers/CSharp/Portable/Lowering/DiagnosticsPass_ExpressionTrees.cs b/src/Compilers/CSharp/Portable/Lowering/DiagnosticsPass_ExpressionTrees.cs index a73c13c54a668..e0ee712a4f94e 100644 --- a/src/Compilers/CSharp/Portable/Lowering/DiagnosticsPass_ExpressionTrees.cs +++ b/src/Compilers/CSharp/Portable/Lowering/DiagnosticsPass_ExpressionTrees.cs @@ -294,7 +294,7 @@ private void VisitCall( ImmutableArray arguments, ImmutableArray argumentRefKindsOpt, ImmutableArray argumentNamesOpt, - bool expanded, + BitVector defaultArguments, BoundNode node) { Debug.Assert((object)method != null); @@ -315,7 +315,7 @@ private void VisitCall( { Error(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, node); } - else if (arguments.Length < (((object)propertyAccess != null) ? propertyAccess.ParameterCount : method.ParameterCount) + (expanded ? -1 : 0)) + else if (hasDefaultArgument(arguments, defaultArguments)) { Error(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, node); } @@ -336,6 +336,19 @@ private void VisitCall( Error(ErrorCode.ERR_RefReturningCallInExpressionTree, node); } } + + static bool hasDefaultArgument(ImmutableArray arguments, BitVector defaultArguments) + { + for (int i = 0; i < arguments.Length; i++) + { + if (defaultArguments[i]) + { + return true; + } + } + + return false; + } } public override BoundNode Visit(BoundNode node) @@ -414,7 +427,7 @@ public override BoundNode VisitObjectInitializerMember(BoundObjectInitializerMem public override BoundNode VisitCall(BoundCall node) { - VisitCall(node.Method, null, node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt, node.Expanded, node); + VisitCall(node.Method, null, node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt, node.DefaultArguments, node); CheckReceiverIfField(node.ReceiverOpt); CheckReferenceToMethodIfLocalFunction(node, node.Method); return base.VisitCall(node); @@ -446,13 +459,13 @@ public override BoundNode VisitCollectionElementInitializer(BoundCollectionEleme Error(ErrorCode.ERR_ExtensionCollectionElementInitializerInExpressionTree, node); } - VisitCall(node.AddMethod, null, node.Arguments, default(ImmutableArray), default(ImmutableArray), node.Expanded, node); + VisitCall(node.AddMethod, null, node.Arguments, default(ImmutableArray), default(ImmutableArray), node.DefaultArguments, node); return base.VisitCollectionElementInitializer(node); } public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node) { - VisitCall(node.Constructor, null, node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt, node.Expanded, node); + VisitCall(node.Constructor, null, node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt, node.DefaultArguments, node); return base.VisitObjectCreationExpression(node); } @@ -462,7 +475,7 @@ public override BoundNode VisitIndexerAccess(BoundIndexerAccess node) var method = indexer.GetOwnOrInheritedGetMethod() ?? indexer.GetOwnOrInheritedSetMethod(); if ((object)method != null) { - VisitCall(method, indexer, node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt, node.Expanded, node); + VisitCall(method, indexer, node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt, node.DefaultArguments, node); } CheckReceiverIfField(node.ReceiverOpt); return base.VisitIndexerAccess(node); diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.PatternLocalRewriter.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.PatternLocalRewriter.cs index 503768bd08991..33cac427ab903 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.PatternLocalRewriter.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.PatternLocalRewriter.cs @@ -529,7 +529,7 @@ private BoundDecisionDag RewriteTupleInput( var rewrittenDag = decisionDag.Rewrite(makeReplacement); savedInputExpression = loweredInput.Update( loweredInput.Constructor, arguments: newArguments.ToImmutableAndFree(), loweredInput.ArgumentNamesOpt, loweredInput.ArgumentRefKindsOpt, - loweredInput.Expanded, loweredInput.ArgsToParamsOpt, loweredInput.ConstantValueOpt, + loweredInput.Expanded, loweredInput.ArgsToParamsOpt, loweredInput.DefaultArguments, loweredInput.ConstantValueOpt, loweredInput.InitializerExpressionOpt, loweredInput.BinderOpt, loweredInput.Type); return rewrittenDag; diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_AnonymousObjectCreation.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_AnonymousObjectCreation.cs index 4e7b718679d64..00c2e9c34be16 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_AnonymousObjectCreation.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_AnonymousObjectCreation.cs @@ -25,6 +25,7 @@ public override BoundNode VisitAnonymousObjectCreationExpression(BoundAnonymousO argumentRefKindsOpt: default(ImmutableArray), expanded: false, argsToParamsOpt: default(ImmutableArray), + defaultArguments: default(BitVector), constantValueOpt: null, initializerExpressionOpt: null, binderOpt: null, diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_AssignmentOperator.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_AssignmentOperator.cs index 90ea473a0085f..011d084b26418 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_AssignmentOperator.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_AssignmentOperator.cs @@ -299,7 +299,7 @@ private BoundExpression MakePropertyAssignment( if (setMethod is null) { var autoProp = (SourcePropertySymbolBase)property; - Debug.Assert(autoProp.IsAutoProperty, + Debug.Assert(autoProp.IsAutoPropertyWithGetAccessor, "only autoproperties can be assignable without having setters"); var backingField = autoProp.BackingField; @@ -315,7 +315,6 @@ private BoundExpression MakePropertyAssignment( syntax, rewrittenArguments, property, - setMethod, expanded, argsToParamsOpt, ref argumentRefKindsOpt, diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Call.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Call.cs index 96496c0bdb096..50c25f4cb2aff 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Call.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Call.cs @@ -178,7 +178,6 @@ private BoundExpression MakeCall( syntax, rewrittenArguments, method, - method, expanded, argsToParamsOpt, ref argumentRefKindsOpt, @@ -236,6 +235,7 @@ private BoundExpression MakeCall( expanded: false, invokedAsExtensionMethod: invokedAsExtensionMethod, argsToParamsOpt: default(ImmutableArray), + defaultArguments: default(BitVector), resultKind: resultKind, binderOpt: null, type: type); @@ -252,6 +252,7 @@ private BoundExpression MakeCall( false, node.InvokedAsExtensionMethod, default(ImmutableArray), + default(BitVector), node.ResultKind, node.BinderOpt, node.Type); @@ -372,16 +373,11 @@ private static bool IsSafeForReordering(BoundExpression expression, RefKind kind /// It is assumed that each argument has already been lowered, but we may need /// additional rewriting for the arguments, such as generating a params array, re-ordering /// arguments based on map, inserting arguments for optional parameters, etc. - /// is the method used for values of any optional parameters. - /// For indexers, this method must be an accessor, and for methods it must be the method - /// itself. is needed for indexers since getter and setter - /// may have distinct optional parameter values. /// private ImmutableArray MakeArguments( SyntaxNode syntax, ImmutableArray rewrittenArguments, Symbol methodOrIndexer, - MethodSymbol optionalParametersMethod, bool expanded, ImmutableArray argsToParamsOpt, ref ImmutableArray argumentRefKindsOpt, @@ -389,18 +385,12 @@ private ImmutableArray MakeArguments( bool invokedAsExtensionMethod = false, ThreeState enableCallerInfo = ThreeState.Unknown) { - // Either the methodOrIndexer is a property, in which case the method used - // for optional parameters is an accessor of that property (or an overridden - // property), or the methodOrIndexer is used for optional parameters directly. - Debug.Assert(((methodOrIndexer.Kind == SymbolKind.Property) && optionalParametersMethod.IsAccessor()) || - ReferenceEquals(methodOrIndexer, optionalParametersMethod)); // We need to do a fancy rewrite under the following circumstances: // (1) a params array is being used; we need to generate the array. // (2) there were named arguments that reordered the arguments; we might // have to generate temporaries to ensure that the arguments are // evaluated in source code order, not the actual call order. - // (3) there were optional parameters that had no corresponding arguments. // // If none of those are the case then we can just take an early out. @@ -496,9 +486,6 @@ private ImmutableArray MakeArguments( actualArguments[actualArguments.Length - 1] = BuildParamsArray(syntax, methodOrIndexer, argsToParamsOpt, rewrittenArguments, parameters, actualArguments[actualArguments.Length - 1]); } - // Step three: Now fill in the optional arguments. - InsertMissingOptionalArguments(syntax, optionalParametersMethod.Parameters, actualArguments, refKinds, enableCallerInfo); - if (isComReceiver) { RewriteArgumentsForComCall(parameters, actualArguments, refKinds, temporariesBuilder); @@ -515,6 +502,7 @@ private ImmutableArray MakeArguments( argumentRefKindsOpt = GetRefKindsOrNull(refKinds); refKinds.Free(); + Debug.Assert(actualArguments.All(static arg => arg is not null)); return actualArguments.AsImmutableOrNull(); } @@ -570,22 +558,14 @@ internal static ImmutableArray MakeArgumentsInEvaluationOrde SyntaxNode syntax, ImmutableArray arguments, Symbol methodOrIndexer, - MethodSymbol optionalParametersMethod, bool expanded, ImmutableArray argsToParamsOpt, + BitVector defaultArguments, bool invokedAsExtensionMethod) { - // Either the methodOrIndexer is a property, in which case the method used - // for optional parameters is an accessor of that property (or an overridden - // property), or the methodOrIndexer is used for optional parameters directly. - Debug.Assert(((methodOrIndexer.Kind == SymbolKind.Property) && - (optionalParametersMethod.IsAccessor() || - ((PropertySymbol)methodOrIndexer).MustCallMethodsDirectly)) || // This condition is a temporary workaround for https://github.com/dotnet/roslyn/issues/23852 - (object)methodOrIndexer == optionalParametersMethod); - // We need to do a fancy rewrite under the following circumstances: // (1) a params array is being used; we need to generate the array. - // (2) there were optional parameters that had no corresponding arguments. + // (2) named arguments were provided out-of-order of the parameters. // // If neither of those are the case then we can just take an early out. @@ -600,7 +580,8 @@ internal static ImmutableArray MakeArgumentsInEvaluationOrde int i = 0; for (; i < parameters.Length; ++i) { - argumentsBuilder.Add(operationFactory.CreateArgumentOperation(ArgumentKind.Explicit, parameters[i].GetPublicSymbol(), arguments[i])); + var argumentKind = defaultArguments[i] ? ArgumentKind.DefaultValue : ArgumentKind.Explicit; + argumentsBuilder.Add(operationFactory.CreateArgumentOperation(argumentKind, parameters[i].GetPublicSymbol(), arguments[i])); } // TODO: In case of __arglist, we will have more arguments than parameters, @@ -608,7 +589,8 @@ internal static ImmutableArray MakeArgumentsInEvaluationOrde // https://github.com/dotnet/roslyn/issues/19673 for (; i < arguments.Length; ++i) { - argumentsBuilder.Add(operationFactory.CreateArgumentOperation(ArgumentKind.Explicit, null, arguments[i])); + var argumentKind = defaultArguments[i] ? ArgumentKind.DefaultValue : ArgumentKind.Explicit; + argumentsBuilder.Add(operationFactory.CreateArgumentOperation(argumentKind, null, arguments[i])); } Debug.Assert(methodOrIndexer.GetIsVararg() ^ parameters.Length == arguments.Length); @@ -622,9 +604,9 @@ internal static ImmutableArray MakeArgumentsInEvaluationOrde operationFactory, syntax, methodOrIndexer, - optionalParametersMethod, expanded, argsToParamsOpt, + defaultArguments, arguments, binder); } @@ -771,9 +753,9 @@ private static ImmutableArray BuildArgumentsInEvaluationOrde CSharpOperationFactory operationFactory, SyntaxNode syntax, Symbol methodOrIndexer, - MethodSymbol optionalParametersMethod, bool expanded, ImmutableArray argsToParamsOpt, + BitVector defaultArguments, ImmutableArray arguments, Binder binder) { @@ -781,7 +763,7 @@ private static ImmutableArray BuildArgumentsInEvaluationOrde ArrayBuilder argumentsInEvaluationBuilder = ArrayBuilder.GetInstance(parameters.Length); - PooledHashSet processedParameters = PooledHashSet.GetInstance(); + bool visitedLastParam = false; // First, fill in all the explicitly provided arguments. for (int a = 0; a < arguments.Length; ++a) @@ -791,11 +773,12 @@ private static ImmutableArray BuildArgumentsInEvaluationOrde int p = (!argsToParamsOpt.IsDefault) ? argsToParamsOpt[a] : a; var parameter = parameters[p]; - Debug.Assert(!processedParameters.Contains(p)); - - processedParameters.Add(p); + if (!visitedLastParam) + { + visitedLastParam = p == parameters.Length - 1; + } - ArgumentKind kind = ArgumentKind.Explicit; + ArgumentKind kind = defaultArguments[a] ? ArgumentKind.DefaultValue : ArgumentKind.Explicit; if (IsBeginningOfParamArray(p, a, expanded, parameters.Length, arguments, argsToParamsOpt, out int paramArrayArgumentCount)) { @@ -819,23 +802,20 @@ private static ImmutableArray BuildArgumentsInEvaluationOrde argumentsInEvaluationBuilder.Add(operationFactory.CreateArgumentOperation(kind, parameter.GetPublicSymbol(), argument)); } - // Collect parameters with missing arguments. - ArrayBuilder missingParametersBuilder = ArrayBuilder.GetInstance(parameters.Length); - for (int i = 0; i < parameters.Length; ++i) + // Finally, append the missing empty params array if necessary. + var lastParam = !parameters.IsEmpty ? parameters[^1] : null; + if (expanded && lastParam is object && !visitedLastParam) { - if (!processedParameters.Contains(i)) - { - missingParametersBuilder.Add(parameters[i]); - } - } + Debug.Assert(lastParam.IsParams); - processedParameters.Free(); + // Create an empty array for omitted param array argument. + BoundExpression argument = CreateParamArrayArgument(syntax, lastParam.Type, ImmutableArray.Empty, null, binder); + ArgumentKind kind = ArgumentKind.ParamArray; - // Finally, append default value as arguments. - AppendMissingOptionalArguments(operationFactory, syntax, methodOrIndexer, optionalParametersMethod, expanded, binder, missingParametersBuilder, argumentsInEvaluationBuilder); - - missingParametersBuilder.Free(); + argumentsInEvaluationBuilder.Add(operationFactory.CreateArgumentOperation(kind, lastParam.GetPublicSymbol(), argument)); + } + Debug.Assert(argumentsInEvaluationBuilder.All(static arg => arg is not null)); return argumentsInEvaluationBuilder.ToImmutableAndFree(); } @@ -932,6 +912,7 @@ private BoundExpression BuildParamsArray( expanded: false, invokedAsExtensionMethod: false, argsToParamsOpt: default(ImmutableArray), + defaultArguments: default(BitVector), resultKind: LookupResultKind.Viable, binderOpt: null, type: arrayEmpty.ReturnType); @@ -1095,441 +1076,6 @@ private static int MergeArgumentsAndSideEffects( return tempsRemainedInUse; } - private void InsertMissingOptionalArguments(SyntaxNode syntax, - ImmutableArray parameters, - BoundExpression[] arguments, - ArrayBuilder refKinds, - ThreeState enableCallerInfo = ThreeState.Unknown) - { - Debug.Assert(refKinds.Count == arguments.Length); - - for (int p = 0; p < arguments.Length; ++p) - { - if (arguments[p] == null) - { - ParameterSymbol parameter = parameters[p]; - Debug.Assert(parameter.IsOptional); - - arguments[p] = GetDefaultParameterValue(syntax, parameter, enableCallerInfo); - Debug.Assert(TypeSymbol.Equals(arguments[p].Type, parameter.Type, TypeCompareKind.ConsiderEverything2)); - - if (parameters[p].RefKind == RefKind.In) - { - Debug.Assert(refKinds[p] == RefKind.None); - refKinds[p] = RefKind.In; - } - } - } - } - - private static void AppendMissingOptionalArguments( - CSharpOperationFactory operationFactory, - SyntaxNode syntax, - Symbol methodOrIndexer, - MethodSymbol optionalParametersMethod, - bool expanded, - Binder binder, - ArrayBuilder missingParameters, - ArrayBuilder argumentsBuilder) - { - ImmutableArray parameters = methodOrIndexer.GetParameters(); - ImmutableArray parametersOfOptionalParametersMethod = optionalParametersMethod.Parameters; - - foreach (ParameterSymbol parameter in missingParameters) - { - BoundExpression argument; - ArgumentKind kind; - - // In case of indexer access, missing parameters are corresponding to the indexer symbol, we need to - // get default values based on actual accessor method parameter symbols (but still want to tie resulted IArgument - // to the indexer parameter.) - ParameterSymbol parameterOfOptionalParametersMethod = parametersOfOptionalParametersMethod[parameter.Ordinal]; - - if (expanded && parameterOfOptionalParametersMethod.Ordinal == parameters.Length - 1) - { - Debug.Assert(parameterOfOptionalParametersMethod.IsParams); - - // Create an empty array for omitted param array argument. - argument = CreateParamArrayArgument(syntax, parameterOfOptionalParametersMethod.Type, ImmutableArray.Empty, null, binder); - kind = ArgumentKind.ParamArray; - } - else - { - Debug.Assert(parameterOfOptionalParametersMethod.IsOptional); - - var unusedDiagnostics = DiagnosticBag.GetInstance(); - - argument = GetDefaultParameterValue(syntax, - parameterOfOptionalParametersMethod, - enableCallerInfo: ThreeState.Unknown, - localRewriter: null, - binder: binder, - diagnostics: unusedDiagnostics); - kind = ArgumentKind.DefaultValue; - - unusedDiagnostics.Free(); - } - - argumentsBuilder.Add(operationFactory.CreateArgumentOperation(kind, parameter.GetPublicSymbol(), argument)); - } - } - - private static SourceLocation? GetCallerLocation(SyntaxNode syntax, ThreeState enableCallerInfo) - { - switch (enableCallerInfo) - { - case ThreeState.False: - return null; - case ThreeState.True: - return new SourceLocation(syntax.GetFirstToken()); - } - - Debug.Assert(enableCallerInfo == ThreeState.Unknown); - - switch (syntax.Kind()) - { - case SyntaxKind.InvocationExpression: - return new SourceLocation(((InvocationExpressionSyntax)syntax).ArgumentList.OpenParenToken); - case SyntaxKind.ObjectCreationExpression: - return new SourceLocation(((ObjectCreationExpressionSyntax)syntax).NewKeyword); - case SyntaxKind.BaseConstructorInitializer: - case SyntaxKind.ThisConstructorInitializer: - return new SourceLocation(((ConstructorInitializerSyntax)syntax).ArgumentList.OpenParenToken); - case SyntaxKind.PrimaryConstructorBaseType: - return new SourceLocation(((PrimaryConstructorBaseTypeSyntax)syntax).ArgumentList.OpenParenToken); - case SyntaxKind.ElementAccessExpression: - return new SourceLocation(((ElementAccessExpressionSyntax)syntax).ArgumentList.OpenBracketToken); - case SyntaxKind.FromClause: - case SyntaxKind.GroupClause: - case SyntaxKind.JoinClause: - case SyntaxKind.JoinIntoClause: - case SyntaxKind.LetClause: - case SyntaxKind.OrderByClause: - case SyntaxKind.SelectClause: - case SyntaxKind.WhereClause: - return new SourceLocation(syntax.GetFirstToken()); - default: - return null; - } - } - - /// - /// Gets the default value for the . - /// - /// - /// A syntax node corresponding to the invocation. - /// - /// - /// A parameter to get the default value for. - /// - /// - /// Indicates if caller info is to be enabled when processing this optional parameter. - /// The value means the decision is to be made based on the shape of the node. - /// - /// - /// DELIBERATE SPEC VIOLATION: When processing an implicit invocation of an Add method generated - /// for an element-initializer in a collection-initializer, the parameter - /// is set to . It means that if the optional parameter is annotated with , - /// or , and there is no explicit argument corresponding to it, - /// we will provide caller information as a value of this parameter. - /// This is done to match the native compiler behavior and user requests (see http://roslyn.codeplex.com/workitem/171). This behavior - /// does not match the C# spec that currently requires to provide caller information only in explicit invocations and query expressions. - /// - private BoundExpression GetDefaultParameterValue(SyntaxNode syntax, ParameterSymbol parameter, ThreeState enableCallerInfo) - { - return GetDefaultParameterValue(syntax, parameter, enableCallerInfo, this, null, this._diagnostics); - } - - /// - /// This helper is used by both LocalRewriter and IOperation. - /// - For lowering, 'localRewriter' must be passed in as an argument, and set 'binder' and 'diagnostics' to null. - /// - For deriving argument expression for IArgument operation, 'localRewriter' must be null, and 'compilation', 'diagnostics' - /// must be passed in, where 'callerMemberName' must not be null if 'parameter.IsCallerMemberName' is 'true'. - /// - internal static BoundExpression GetDefaultParameterValue( - SyntaxNode syntax, - ParameterSymbol parameter, - ThreeState enableCallerInfo, - LocalRewriter? localRewriter, - Binder? binder, - DiagnosticBag diagnostics) - { - Debug.Assert(localRewriter == null ^ binder == null); - Debug.Assert(diagnostics != null); - - bool isLowering; - CSharpCompilation compilation; - - if (localRewriter != null) - { - isLowering = true; - compilation = localRewriter._compilation; - } - else - { - isLowering = false; - compilation = binder!.Compilation; - } - - // TODO: Ideally, the enableCallerInfo parameter would be of just bool type with only 'true' and 'false' values, and all callers - // explicitly provided one of those values, so that we do not rely on shape of syntax nodes in the rewriter. There are not many immediate callers, - // but often the immediate caller does not have the required information, so all possible call chains should be analyzed and possibly updated - // to pass this information, and this might be a big task. We should consider doing this when the time permits. - - TypeSymbol parameterType = parameter.Type; - Debug.Assert(parameter.IsOptional); - ConstantValue defaultConstantValue = parameter.ExplicitDefaultConstantValue; - BoundExpression defaultValue; - SourceLocation? callerSourceLocation; - - // For compatibility with the native compiler we treat all bad imported constant - // values as default(T). However, we don't do this for IOperation purpose, in which case - // we will expose the bad node. - if (defaultConstantValue != null && defaultConstantValue.IsBad && isLowering) - { - defaultConstantValue = ConstantValue.Null; - } - - if (parameter.IsCallerLineNumber && ((callerSourceLocation = GetCallerLocation(syntax, enableCallerInfo)) != null)) - { - int line = callerSourceLocation.SourceTree.GetDisplayLineNumber(callerSourceLocation.SourceSpan); - - BoundExpression lineLiteral = MakeLiteral(syntax, ConstantValue.Create(line), compilation.GetSpecialType(SpecialType.System_Int32), localRewriter); - - if (parameterType.IsNullableType()) - { - TypeSymbol nullableType = parameterType.GetNullableUnderlyingType(); - defaultValue = MakeConversionNode(lineLiteral, nullableType, @checked: false); - - // wrap it in a nullable ctor. - defaultValue = new BoundObjectCreationExpression( - syntax, - UnsafeGetNullableMethod(syntax, parameterType, SpecialMember.System_Nullable_T__ctor, compilation, diagnostics), - null, - defaultValue) - { WasCompilerGenerated = true }; - } - else - { - defaultValue = MakeConversionNode(lineLiteral, parameterType, @checked: false); - } - } - else if (parameter.IsCallerFilePath && ((callerSourceLocation = GetCallerLocation(syntax, enableCallerInfo)) != null)) - { - string path = callerSourceLocation.SourceTree.GetDisplayPath(callerSourceLocation.SourceSpan, compilation.Options.SourceReferenceResolver); - BoundExpression memberNameLiteral = MakeLiteral(syntax, ConstantValue.Create(path), compilation.GetSpecialType(SpecialType.System_String), localRewriter); - defaultValue = MakeConversionNode(memberNameLiteral, parameterType, @checked: false); - } - else if (parameter.IsCallerMemberName && ((callerSourceLocation = GetCallerLocation(syntax, enableCallerInfo)) != null)) - { - string? memberName; - - if (isLowering) - { - Debug.Assert(localRewriter is { }); - MethodSymbol? topLevelMethod = localRewriter._factory.TopLevelMethod; - Debug.Assert(topLevelMethod is { }); - switch (topLevelMethod.MethodKind) - { - case MethodKind.Constructor: - case MethodKind.StaticConstructor: - // See if the code is actually part of a field, field-like event or property initializer and return the name of the corresponding member. - var memberDecl = syntax.Ancestors().OfType().FirstOrDefault(); - - if (memberDecl != null) - { - BaseFieldDeclarationSyntax? fieldDecl; - - if (memberDecl.Kind() == SyntaxKind.PropertyDeclaration) - { - var propDecl = (PropertyDeclarationSyntax)memberDecl; - EqualsValueClauseSyntax? initializer = propDecl.Initializer; - - if (initializer != null && initializer.Span.Contains(syntax.Span)) - { - memberName = propDecl.Identifier.ValueText; - break; - } - } - else if ((fieldDecl = memberDecl as BaseFieldDeclarationSyntax) != null) - { - memberName = null; - - foreach (VariableDeclaratorSyntax varDecl in fieldDecl.Declaration.Variables) - { - EqualsValueClauseSyntax? initializer = varDecl.Initializer; - - if (initializer != null && initializer.Span.Contains(syntax.Span)) - { - memberName = varDecl.Identifier.ValueText; - break; - } - } - - if (memberName != null) - { - break; - } - } - } - - goto default; - - default: - memberName = topLevelMethod.GetMemberCallerName(); - break; - } - } - else - { - memberName = binder!.ContainingMember().GetMemberCallerName(); - } - - BoundExpression memberNameLiteral = MakeLiteral(syntax, ConstantValue.Create(memberName), compilation.GetSpecialType(SpecialType.System_String), localRewriter); - defaultValue = MakeConversionNode(memberNameLiteral, parameterType, @checked: false); - } - else if (defaultConstantValue == ConstantValue.NotAvailable) - { - // There is no constant value given for the parameter in source/metadata. - if (parameterType.IsDynamic() || parameterType.SpecialType == SpecialType.System_Object) - { - // We have something like M([Optional] object x). We have special handling for such situations. - defaultValue = isLowering - ? localRewriter!.GetDefaultParameterSpecial(syntax, parameter) - : GetDefaultParameterSpecialForIOperation(syntax, parameter, compilation, diagnostics); - } - else - { - // The argument to M([Optional] int x) becomes default(int) - defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; - } - } - else if (defaultConstantValue.IsNull) - { - if (parameterType.IsValueType || (parameterType.IsNullableType() && parameterType.IsErrorType())) - { - // We have something like M(int? x = null) or M(S x = default(S)), - // so replace the argument with default(int?). - defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; - } - else - { - defaultValue = MakeLiteral(syntax, defaultConstantValue, parameterType, localRewriter); - } - } - else if (defaultConstantValue.IsBad) - { - defaultValue = new BoundBadExpression(syntax, LookupResultKind.Empty, ImmutableArray.Empty, ImmutableArray.Empty, parameterType, hasErrors: true) { WasCompilerGenerated = true }; - } - else if (parameterType.IsNullableType()) - { - // We have something like M(double? x = 1.23), so replace the argument - // with new double?(1.23). - - TypeSymbol constantType = compilation.GetSpecialType(defaultConstantValue.SpecialType); - defaultValue = MakeLiteral(syntax, defaultConstantValue, constantType, localRewriter); - - // The parameter's underlying type might not match the constant type. For example, we might have - // a default value of 5 (an integer) but a parameter type of decimal?. - - defaultValue = MakeConversionNode(defaultValue, parameterType.GetNullableUnderlyingType(), @checked: false, acceptFailingConversion: true); - - // Finally, wrap it in a nullable ctor. - defaultValue = new BoundObjectCreationExpression( - syntax, - UnsafeGetNullableMethod(syntax, parameterType, SpecialMember.System_Nullable_T__ctor, compilation, diagnostics), - null, - defaultValue) - { WasCompilerGenerated = true }; - } - else - { - // We have something like M(double x = 1.23), so replace the argument with 1.23. - - TypeSymbol constantType = compilation.GetSpecialType(defaultConstantValue.SpecialType); - defaultValue = MakeLiteral(syntax, defaultConstantValue, constantType, localRewriter); - // The parameter type might not match the constant type. - defaultValue = MakeConversionNode(defaultValue, parameterType, @checked: false, acceptFailingConversion: true); - } - - // CONSIDER: it feels like determining the exact value that will be emitted for a - // parameter default value is something that should be figured out at binding time, not in lowering. - defaultValue = defaultValue.WithSuppression(syntax.IsKind(SyntaxKind.SuppressNullableWarningExpression)); - - return defaultValue; - - BoundExpression MakeConversionNode(BoundExpression operand, TypeSymbol type, bool @checked, bool acceptFailingConversion = false) - { - if (isLowering) - { - return localRewriter!.MakeConversionNode(operand, type, @checked, acceptFailingConversion); - } - else - { - return MakeConversionForIOperation(operand, type, syntax, compilation, diagnostics, @checked, acceptFailingConversion); - } - } - } - - private BoundExpression GetDefaultParameterSpecial(SyntaxNode syntax, ParameterSymbol parameter) - { - BoundExpression defaultValue = GetDefaultParameterSpecialNoConversion(syntax, parameter, this._compilation); - return MakeConversionNode(defaultValue, parameter.Type, @checked: false); - } - - private static BoundExpression GetDefaultParameterSpecialForIOperation(SyntaxNode syntax, ParameterSymbol parameter, CSharpCompilation compilation, DiagnosticBag diagnostics) - { - BoundExpression defaultValue = GetDefaultParameterSpecialNoConversion(syntax, parameter, compilation); - return MakeConversionForIOperation(defaultValue, parameter.Type, syntax, compilation, diagnostics, @checked: false); - } - - private static BoundExpression GetDefaultParameterSpecialNoConversion(SyntaxNode syntax, ParameterSymbol parameter, CSharpCompilation compilation) - { - // We have a call to a method M([Optional] object x) which omits the argument. The value we generate - // for the argument depends on the presence or absence of other attributes. The rules are: - // - // * If the parameter is marked as [MarshalAs(Interface)], [MarshalAs(IUnknown)] or [MarshalAs(IDispatch)] - // then the argument is null. - // * Otherwise, if the parameter is marked as [IUnknownConstant] then the argument is - // new UnknownWrapper(null) - // * Otherwise, if the parameter is marked as [IDispatchConstant] then the argument is - // new DispatchWrapper(null) - // * Otherwise, the argument is Type.Missing. - - BoundExpression defaultValue; - - if (parameter.IsMarshalAsObject) - { - // default(object) - defaultValue = new BoundDefaultExpression(syntax, parameter.Type) { WasCompilerGenerated = true }; - } - else if (parameter.IsIUnknownConstant) - { - // new UnknownWrapper(default(object)) - var methodSymbol = (MethodSymbol?)compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_InteropServices_UnknownWrapper__ctor); - Debug.Assert(methodSymbol is { }); - var argument = new BoundDefaultExpression(syntax, parameter.Type) { WasCompilerGenerated = true }; - defaultValue = new BoundObjectCreationExpression(syntax, methodSymbol, null, argument) { WasCompilerGenerated = true }; - } - else if (parameter.IsIDispatchConstant) - { - // new DispatchWrapper(default(object)) - var methodSymbol = (MethodSymbol?)compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_InteropServices_DispatchWrapper__ctor); - Debug.Assert(methodSymbol is { }); - var argument = new BoundDefaultExpression(syntax, parameter.Type) { WasCompilerGenerated = true }; - defaultValue = new BoundObjectCreationExpression(syntax, methodSymbol, null, argument) { WasCompilerGenerated = true }; - } - else - { - // Type.Missing - var fieldSymbol = (FieldSymbol?)compilation.GetWellKnownTypeMember(WellKnownMember.System_Type__Missing); - Debug.Assert(fieldSymbol is { }); - defaultValue = new BoundFieldAccess(syntax, null, fieldSymbol, ConstantValue.NotAvailable) { WasCompilerGenerated = true }; - } - - return defaultValue; - } - // Omit ref feature for COM interop: We can pass arguments by value for ref parameters if we are calling a method/property on an instance of a COM imported type. // We should have ignored the 'ref' on the parameter during overload resolution for the given method call. // If we had any ref omitted argument for the given call, we create a temporary local and diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_CompoundAssignmentOperator.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_CompoundAssignmentOperator.cs index e128f182206cc..730cff65a69a6 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_CompoundAssignmentOperator.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_CompoundAssignmentOperator.cs @@ -4,6 +4,7 @@ using System.Collections.Immutable; using System.Diagnostics; +using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; @@ -335,7 +336,6 @@ private BoundIndexerAccess TransformIndexerAccess(BoundIndexerAccess indexerAcce // compound assignments, but for deconstructions we use the setter if the getter is missing.) var accessor = indexer.GetOwnOrInheritedGetMethod() ?? indexer.GetOwnOrInheritedSetMethod(); Debug.Assert(accessor is not null); - InsertMissingOptionalArguments(syntax, accessor.Parameters, actualArguments, refKinds); // For a call, step four would be to optimize away some of the temps. However, we need them all to prevent // duplicate side-effects, so we'll skip that step. @@ -345,6 +345,7 @@ private BoundIndexerAccess TransformIndexerAccess(BoundIndexerAccess indexerAcce RewriteArgumentsForComCall(parameters, actualArguments, refKinds, temps); } + Debug.Assert(actualArguments.All(static arg => arg is not null)); rewrittenArguments = actualArguments.AsImmutableOrNull(); foreach (BoundAssignmentOperator tempAssignment in storesToTemps) @@ -367,8 +368,8 @@ private BoundIndexerAccess TransformIndexerAccess(BoundIndexerAccess indexerAcce argumentRefKinds, false, default(ImmutableArray), + default(BitVector), null, - indexerAccess.UseSetterForDefaultArgumentGeneration, indexerAccess.Type); } diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ForEachStatement.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ForEachStatement.cs index 8b769c92f0454..ad63e24cb9b83 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ForEachStatement.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ForEachStatement.cs @@ -126,6 +126,7 @@ private BoundStatement RewriteEnumeratorForEachStatement(BoundForEachStatement n // ((C)(x)).GetEnumerator(); OR (x).GetEnumerator(); OR async variants (which fill-in arguments for optional parameters) BoundExpression enumeratorVarInitValue = SynthesizeCall( + enumeratorInfo.Binder, forEachSyntax, ConvertReceiverForInvocation(forEachSyntax, rewrittenExpression, getEnumeratorMethod, enumeratorInfo.CollectionConversion, enumeratorInfo.CollectionType), getEnumeratorMethod, @@ -167,6 +168,7 @@ private BoundStatement RewriteEnumeratorForEachStatement(BoundForEachStatement n var rewrittenBodyBlock = CreateBlockDeclaringIterationVariables(iterationVariables, iterationVarDecl, rewrittenBody, forEachSyntax); BoundExpression rewrittenCondition = SynthesizeCall( + binder: enumeratorInfo.Binder, syntax: forEachSyntax, receiver: boundEnumeratorVar, method: enumeratorInfo.MoveNextMethod, @@ -286,6 +288,7 @@ private BoundStatement WrapWithTryFinallyDispose( // ((IDisposable)e).Dispose() or e.Dispose() or await ((IAsyncDisposable)e).DisposeAsync() or await e.DisposeAsync() BoundExpression disposeCall = MakeCallWithNoExplicitArgument( + enumeratorInfo.Binder, forEachSyntax, receiver, disposeMethod); @@ -482,12 +485,12 @@ private BoundExpression ConvertReceiverForInvocation(CSharpSyntaxNode syntax, Bo return receiver; } - private BoundExpression SynthesizeCall(CSharpSyntaxNode syntax, BoundExpression receiver, MethodSymbol method, bool allowExtensionAndOptionalParameters) + private BoundExpression SynthesizeCall(Binder binder, CSharpSyntaxNode syntax, BoundExpression receiver, MethodSymbol method, bool allowExtensionAndOptionalParameters) { if (allowExtensionAndOptionalParameters) { // Generate a call with zero explicit arguments, but with implicit arguments for optional and params parameters. - return MakeCallWithNoExplicitArgument(syntax, receiver, method); + return MakeCallWithNoExplicitArgument(binder, syntax, receiver, method); } // Generate a call with literally zero arguments diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_FunctionPointerInvocation.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_FunctionPointerInvocation.cs index b6aa20ce1bc91..4fb484d7861b4 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_FunctionPointerInvocation.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_FunctionPointerInvocation.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. @@ -22,7 +22,6 @@ internal sealed partial class LocalRewriter node.Syntax, rewrittenArgs, functionPointer, - functionPointer, expanded: false, argsToParamsOpt: default, ref argumentRefKindsOpt, diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_IndexerAccess.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_IndexerAccess.cs index 99bd07e03534a..d616d91feff34 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_IndexerAccess.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_IndexerAccess.cs @@ -95,6 +95,7 @@ private BoundExpression VisitIndexerAccess(BoundIndexerAccess node, bool isLeftO node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, + node.DefaultArguments, node.Type, node, isLeftOfAssignment); @@ -109,6 +110,7 @@ private BoundExpression MakeIndexerAccess( ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, + BitVector defaultArguments, TypeSymbol type, BoundIndexerAccess? oldNodeOpt, bool isLeftOfAssignment) @@ -119,8 +121,8 @@ private BoundExpression MakeIndexerAccess( // This node will be rewritten with MakePropertyAssignment when rewriting the enclosing BoundAssignmentOperator. return oldNodeOpt != null ? - oldNodeOpt.Update(rewrittenReceiver, indexer, rewrittenArguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, null, isLeftOfAssignment, type) : - new BoundIndexerAccess(syntax, rewrittenReceiver, indexer, rewrittenArguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, null, isLeftOfAssignment, type); + oldNodeOpt.Update(rewrittenReceiver, indexer, rewrittenArguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, null, type) : + new BoundIndexerAccess(syntax, rewrittenReceiver, indexer, rewrittenArguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, null, type); } else { @@ -134,7 +136,6 @@ private BoundExpression MakeIndexerAccess( syntax, rewrittenArguments, indexer, - getMethod, expanded, argsToParamsOpt, ref argumentRefKindsOpt, @@ -251,6 +252,7 @@ private BoundSequence VisitIndexPatternIndexerAccess( default, expanded: false, argsToParamsOpt: default, + defaultArguments: default, intIndexer.Type, oldNodeOpt: null, isLeftOfAssignment)); diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Literal.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Literal.cs index 02a33ef02da96..fdd9bacf87752 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Literal.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Literal.cs @@ -134,7 +134,7 @@ private BoundExpression MakeDecimalLiteral(SyntaxNode syntax, ConstantValue cons return new BoundObjectCreationExpression( syntax, ctor, arguments.ToImmutableAndFree(), - default(ImmutableArray), default(ImmutableArray), false, default(ImmutableArray), + default(ImmutableArray), default(ImmutableArray), false, default(ImmutableArray), default(BitVector), constantValue, null, null, ctor.ContainingType); } @@ -153,7 +153,7 @@ private BoundExpression MakeDateTimeLiteral(SyntaxNode syntax, ConstantValue con // This is not a constant from C#'s perspective, so do not mark it as one. return new BoundObjectCreationExpression( syntax, ctor, arguments.ToImmutableAndFree(), - default(ImmutableArray), default(ImmutableArray), false, default(ImmutableArray), + default(ImmutableArray), default(ImmutableArray), false, default(ImmutableArray), default(BitVector), ConstantValue.NotAvailable, null, null, ctor.ContainingType); } } diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectCreationExpression.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectCreationExpression.cs index 3085d3735df28..3cad0227e0660 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectCreationExpression.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectCreationExpression.cs @@ -32,19 +32,18 @@ public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpre // Rewrite the arguments. // NOTE: We may need additional argument rewriting such as generating a params array, - // re-ordering arguments based on argsToParamsOpt map, inserting arguments for optional parameters, etc. + // re-ordering arguments based on argsToParamsOpt map, etc. // NOTE: This is done later by MakeArguments, for now we just lower each argument. var rewrittenArguments = VisitList(node.Arguments); // We have already lowered each argument, but we may need some additional rewriting for the arguments, - // such as generating a params array, re-ordering arguments based on argsToParamsOpt map, inserting arguments for optional parameters, etc. + // such as generating a params array, re-ordering arguments based on argsToParamsOpt map, etc. ImmutableArray temps; ImmutableArray argumentRefKindsOpt = node.ArgumentRefKindsOpt; rewrittenArguments = MakeArguments( node.Syntax, rewrittenArguments, node.Constructor, - node.Constructor, node.Expanded, node.ArgsToParamsOpt, ref argumentRefKindsOpt, @@ -246,6 +245,7 @@ private BoundExpression MakeNewT(SyntaxNode syntax, TypeParameterSymbol typePara expanded: false, invokedAsExtensionMethod: false, argsToParamsOpt: default(ImmutableArray), + defaultArguments: default(BitVector), resultKind: LookupResultKind.Viable, binderOpt: null, type: typeParameter); diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectOrCollectionInitializerExpression.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectOrCollectionInitializerExpression.cs index 16df869ba1714..93f9c1ea6438e 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectOrCollectionInitializerExpression.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectOrCollectionInitializerExpression.cs @@ -183,7 +183,7 @@ private BoundExpression MakeDynamicCollectionInitializer(BoundExpression rewritt argumentRefKindsOpt = builder.ToImmutableAndFree(); } - rewrittenArguments = MakeArguments(syntax, rewrittenArguments, addMethod, addMethod, initializer.Expanded, initializer.ArgsToParamsOpt, ref argumentRefKindsOpt, out temps, enableCallerInfo: ThreeState.True); + rewrittenArguments = MakeArguments(syntax, rewrittenArguments, addMethod, initializer.Expanded, initializer.ArgsToParamsOpt, ref argumentRefKindsOpt, out temps, enableCallerInfo: ThreeState.True); if (initializer.InvokedAsExtensionMethod) { @@ -195,7 +195,7 @@ private BoundExpression MakeDynamicCollectionInitializer(BoundExpression rewritt if (_inExpressionLambda) { - return initializer.Update(addMethod, rewrittenArguments, rewrittenReceiver, expanded: false, argsToParamsOpt: default, initializer.InvokedAsExtensionMethod, initializer.ResultKind, initializer.BinderOpt, rewrittenType); + return initializer.Update(addMethod, rewrittenArguments, rewrittenReceiver, expanded: false, argsToParamsOpt: default, defaultArguments: default, initializer.InvokedAsExtensionMethod, initializer.ResultKind, initializer.BinderOpt, rewrittenType); } return MakeCall(null, syntax, rewrittenReceiver, addMethod, rewrittenArguments, argumentRefKindsOpt, initializer.InvokedAsExtensionMethod, initializer.ResultKind, addMethod.ReturnType, temps); @@ -268,6 +268,7 @@ private void AddObjectInitializer( memberInit.ArgumentRefKindsOpt, memberInit.Expanded, memberInit.ArgsToParamsOpt, + memberInit.DefaultArguments, memberInit.ResultKind, memberInit.ReceiverType, memberInit.Binder, @@ -482,6 +483,7 @@ private BoundExpression MakeObjectInitializerMemberAccess( rewrittenLeft.ArgumentRefKindsOpt, rewrittenLeft.Expanded, rewrittenLeft.ArgsToParamsOpt, + rewrittenLeft.DefaultArguments, type: propertySymbol.Type, oldNodeOpt: null, isLeftOfAssignment: !isRhsNestedInitializer); diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_TupleCreationExpression.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_TupleCreationExpression.cs index fe76565b149cf..f99c2e5c829b7 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_TupleCreationExpression.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_TupleCreationExpression.cs @@ -99,6 +99,7 @@ private BoundExpression MakeTupleCreationExpression(SyntaxNode syntax, NamedType currentCreation.ArgumentRefKindsOpt, currentCreation.Expanded, currentCreation.ArgsToParamsOpt, + currentCreation.DefaultArguments, currentCreation.ConstantValue, currentCreation.InitializerExpressionOpt, currentCreation.BinderOpt, diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_UsingStatement.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_UsingStatement.cs index 823b2b4fcfc25..3f5023868f3ca 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_UsingStatement.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_UsingStatement.cs @@ -6,6 +6,7 @@ using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { @@ -446,7 +447,7 @@ private BoundExpression GenerateDisposeCall( } else { - disposeCall = MakeCallWithNoExplicitArgument(syntax, disposedExpression, methodOpt); + disposeCall = MakeCallWithNoExplicitArgument(_compilation.GetBinder((CSharpSyntaxNode)syntax), syntax, disposedExpression, methodOpt); if (awaitOpt is object) { @@ -464,24 +465,40 @@ private BoundExpression GenerateDisposeCall( /// /// Synthesize a call `expression.Method()`, but with some extra smarts to handle extension methods, and to fill-in optional and params parameters. /// - private BoundExpression MakeCallWithNoExplicitArgument(SyntaxNode syntax, BoundExpression expression, MethodSymbol method) + private BoundExpression MakeCallWithNoExplicitArgument(Binder binder, SyntaxNode syntax, BoundExpression expression, MethodSymbol method) { var receiver = method.IsExtensionMethod ? null : expression; - var args = method.IsExtensionMethod - ? ImmutableArray.Create(expression) - : ImmutableArray.Empty; + var argsBuilder = ArrayBuilder.GetInstance(); + if (method.IsExtensionMethod) + { + argsBuilder.Add(expression); + } Debug.Assert(!method.IsExtensionMethod || method.ParameterRefKinds.IsDefaultOrEmpty || method.ParameterRefKinds[0] != RefKind.Ref); + var expanded = method.HasParamsParameter(); + + var argsToParams = default(ImmutableArray); + binder.BindDefaultArguments( + syntax, + method.Parameters, + argsBuilder, + argumentRefKindsBuilder: null, + ref argsToParams, + out var defaultArguments, + expanded, + enableCallerInfo: false, + _diagnostics); + BoundExpression disposeCall = MakeCall(syntax: syntax, rewrittenReceiver: receiver, method: method, - rewrittenArguments: args, + rewrittenArguments: argsBuilder.ToImmutableAndFree(), argumentRefKindsOpt: default, - expanded: method.HasParamsParameter(), + expanded, invokedAsExtensionMethod: method.IsExtensionMethod, - argsToParamsOpt: default, + argsToParamsOpt: argsToParams, resultKind: LookupResultKind.Viable, type: method.ReturnType); diff --git a/src/Compilers/CSharp/Portable/Lowering/MethodToClassRewriter.cs b/src/Compilers/CSharp/Portable/Lowering/MethodToClassRewriter.cs index 7db66f9e8b7ab..66d4150f283fa 100644 --- a/src/Compilers/CSharp/Portable/Lowering/MethodToClassRewriter.cs +++ b/src/Compilers/CSharp/Portable/Lowering/MethodToClassRewriter.cs @@ -255,6 +255,7 @@ public override BoundNode VisitCall(BoundCall node) node.Expanded, node.InvokedAsExtensionMethod, node.ArgsToParamsOpt, + node.DefaultArguments, node.ResultKind, node.BinderOpt, rewrittenType); @@ -483,6 +484,7 @@ public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpre rewritten.ArgumentRefKindsOpt, rewritten.Expanded, rewritten.ArgsToParamsOpt, + rewritten.DefaultArguments, rewritten.ConstantValueOpt, rewritten.InitializerExpressionOpt, rewritten.BinderOpt, @@ -619,7 +621,7 @@ public override BoundNode VisitObjectInitializerMember(BoundObjectInitializerMem break; } - return node.Update(member, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.ResultKind, receiverType, node.Binder, type); + return node.Update(member, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.ResultKind, receiverType, node.Binder, type); } public override BoundNode VisitReadOnlySpanFromArray(BoundReadOnlySpanFromArray node) diff --git a/src/Compilers/CSharp/Portable/Lowering/SpillSequenceSpiller.cs b/src/Compilers/CSharp/Portable/Lowering/SpillSequenceSpiller.cs index e9d5e7535dde4..9fcd007e69a70 100644 --- a/src/Compilers/CSharp/Portable/Lowering/SpillSequenceSpiller.cs +++ b/src/Compilers/CSharp/Portable/Lowering/SpillSequenceSpiller.cs @@ -1158,7 +1158,7 @@ public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpre Debug.Assert(node.InitializerExpressionOpt == null); BoundSpillSequenceBuilder builder = null; var arguments = this.VisitExpressionList(ref builder, node.Arguments, node.ArgumentRefKindsOpt); - return UpdateExpression(builder, node.Update(node.Constructor, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.ConstantValueOpt, node.InitializerExpressionOpt, node.BinderOpt, node.Type)); + return UpdateExpression(builder, node.Update(node.Constructor, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.ConstantValueOpt, node.InitializerExpressionOpt, node.BinderOpt, node.Type)); } public override BoundNode VisitPointerElementAccess(BoundPointerElementAccess node) diff --git a/src/Compilers/CSharp/Portable/Lowering/SynthesizedMethodBaseSymbol.cs b/src/Compilers/CSharp/Portable/Lowering/SynthesizedMethodBaseSymbol.cs index 623e758614ddf..e251241fc67c0 100644 --- a/src/Compilers/CSharp/Portable/Lowering/SynthesizedMethodBaseSymbol.cs +++ b/src/Compilers/CSharp/Portable/Lowering/SynthesizedMethodBaseSymbol.cs @@ -88,8 +88,11 @@ public sealed override ImmutableArray TypeParameters get { return _typeParameters; } } - public sealed override ImmutableArray GetTypeParameterConstraintClauses(bool canIgnoreNullableContext) - => ImmutableArray.Empty; + public sealed override ImmutableArray> GetTypeParameterConstraintTypes() + => ImmutableArray>.Empty; + + public sealed override ImmutableArray GetTypeParameterConstraintKinds() + => ImmutableArray.Empty; internal override int ParameterCount { diff --git a/src/Compilers/CSharp/Portable/Lowering/SyntheticBoundNodeFactory.cs b/src/Compilers/CSharp/Portable/Lowering/SyntheticBoundNodeFactory.cs index cfe9260ec078f..1c0f09d1bf3cf 100644 --- a/src/Compilers/CSharp/Portable/Lowering/SyntheticBoundNodeFactory.cs +++ b/src/Compilers/CSharp/Portable/Lowering/SyntheticBoundNodeFactory.cs @@ -736,7 +736,7 @@ public BoundCall Call(BoundExpression? receiver, MethodSymbol method, ImmutableA return new BoundCall( Syntax, receiver, method, args, default(ImmutableArray), method.ParameterRefKinds, false, false, false, - default(ImmutableArray), LookupResultKind.Viable, null, method.ReturnType, + default(ImmutableArray), default(BitVector), LookupResultKind.Viable, null, method.ReturnType, hasErrors: method.OriginalDefinition is ErrorMethodSymbol) { WasCompilerGenerated = true }; } @@ -747,7 +747,7 @@ public BoundCall Call(BoundExpression? receiver, MethodSymbol method, ImmutableA return new BoundCall( Syntax, receiver, method, args, default(ImmutableArray), refKinds, false, false, false, - ImmutableArray.Empty, LookupResultKind.Viable, null, method.ReturnType) + ImmutableArray.Empty, default(BitVector), LookupResultKind.Viable, null, method.ReturnType) { WasCompilerGenerated = true }; } diff --git a/src/Compilers/CSharp/Portable/Microsoft.CodeAnalysis.CSharp.csproj b/src/Compilers/CSharp/Portable/Microsoft.CodeAnalysis.CSharp.csproj index 8efb8bd695299..b3722e7f93812 100644 --- a/src/Compilers/CSharp/Portable/Microsoft.CodeAnalysis.CSharp.csproj +++ b/src/Compilers/CSharp/Portable/Microsoft.CodeAnalysis.CSharp.csproj @@ -15,15 +15,27 @@ .NET Compiler Platform ("Roslyn") support for C#, Microsoft.CodeAnalysis.CSharp.dll. + + + true + Generated + + Analyzer + false + + TargetFramework=netstandard2.0 + - + @@ -33,6 +45,11 @@ + + + diff --git a/src/Compilers/CSharp/Portable/Operations/CSharpOperationFactory.cs b/src/Compilers/CSharp/Portable/Operations/CSharpOperationFactory.cs index da9280d82a66f..e1ca97c84fbd5 100644 --- a/src/Compilers/CSharp/Portable/Operations/CSharpOperationFactory.cs +++ b/src/Compilers/CSharp/Portable/Operations/CSharpOperationFactory.cs @@ -596,11 +596,7 @@ private IOperation CreateBoundIndexerAccessOperation(BoundIndexerAccess boundInd ConstantValue constantValue = boundIndexerAccess.ConstantValue; bool isImplicit = boundIndexerAccess.WasCompilerGenerated; - MethodSymbol accessor = boundIndexerAccess.UseSetterForDefaultArgumentGeneration - ? property.GetOwnOrInheritedSetMethod() - : property.GetOwnOrInheritedGetMethod(); - - if (!boundIndexerAccess.OriginalIndexersOpt.IsDefault || boundIndexerAccess.ResultKind == LookupResultKind.OverloadResolutionFailure || accessor == null || accessor.OriginalDefinition is ErrorMethodSymbol) + if (!boundIndexerAccess.OriginalIndexersOpt.IsDefault || boundIndexerAccess.ResultKind == LookupResultKind.OverloadResolutionFailure) { return new CSharpLazyInvalidOperation(this, boundIndexerAccess, _semanticModel, syntax, type, constantValue, isImplicit); } @@ -1613,18 +1609,17 @@ internal ForEachLoopOperationInfo GetForEachLoopOperatorInfo(BoundForEachStateme false, enumeratorInfoOpt.CurrentConversion, boundForEachStatement.ElementConversion, - getEnumeratorArguments: enumeratorInfoOpt.GetEnumeratorMethod is { IsExtensionMethod: true, Parameters: var parameters } enumeratorMethod + getEnumeratorArguments: enumeratorInfoOpt.GetEnumeratorMethod is { IsExtensionMethod: true } enumeratorMethod ? Operation.SetParentOperation( DeriveArguments( boundForEachStatement, enumeratorInfoOpt.Binder, enumeratorMethod, - enumeratorMethod, ImmutableArray.Create(boundForEachStatement.Expression), argumentNamesOpt: default, argumentsToParametersOpt: default, + defaultArguments: default, argumentRefKindsOpt: default, - parameters, expanded: false, boundForEachStatement.Expression.Syntax, invokedAsExtensionMethod: true), diff --git a/src/Compilers/CSharp/Portable/Operations/CSharpOperationFactory_Methods.cs b/src/Compilers/CSharp/Portable/Operations/CSharpOperationFactory_Methods.cs index a8ab3552ec04a..dc17c135946df 100644 --- a/src/Compilers/CSharp/Portable/Operations/CSharpOperationFactory_Methods.cs +++ b/src/Compilers/CSharp/Portable/Operations/CSharpOperationFactory_Methods.cs @@ -220,17 +220,15 @@ internal ImmutableArray DeriveArguments(BoundNode containing var boundObjectInitializerMember = (BoundObjectInitializerMember)containingExpression; var property = (PropertySymbol?)boundObjectInitializerMember.MemberSymbol; Debug.Assert(property is not null); - MethodSymbol? accessor = isObjectOrCollectionInitializer ? property.GetOwnOrInheritedGetMethod() : property.GetOwnOrInheritedSetMethod(); return DeriveArguments( boundObjectInitializerMember, boundObjectInitializerMember.Binder, property, - accessor, boundObjectInitializerMember.Arguments, boundObjectInitializerMember.ArgumentNamesOpt, boundObjectInitializerMember.ArgsToParamsOpt, + boundObjectInitializerMember.DefaultArguments, boundObjectInitializerMember.ArgumentRefKindsOpt, - property.Parameters, boundObjectInitializerMember.Expanded, boundObjectInitializerMember.Syntax); } @@ -251,13 +249,11 @@ internal ImmutableArray DeriveArguments(BoundNode containing return DeriveArguments(boundIndexer, boundIndexer.BinderOpt, boundIndexer.Indexer, - boundIndexer.UseSetterForDefaultArgumentGeneration ? boundIndexer.Indexer.GetOwnOrInheritedSetMethod() : - boundIndexer.Indexer.GetOwnOrInheritedGetMethod(), boundIndexer.Arguments, boundIndexer.ArgumentNamesOpt, boundIndexer.ArgsToParamsOpt, + boundIndexer.DefaultArguments, boundIndexer.ArgumentRefKindsOpt, - boundIndexer.Indexer.Parameters, boundIndexer.Expanded, boundIndexer.Syntax); } @@ -267,12 +263,11 @@ internal ImmutableArray DeriveArguments(BoundNode containing return DeriveArguments(objectCreation, objectCreation.BinderOpt, objectCreation.Constructor, - objectCreation.Constructor, objectCreation.Arguments, objectCreation.ArgumentNamesOpt, objectCreation.ArgsToParamsOpt, + objectCreation.DefaultArguments, objectCreation.ArgumentRefKindsOpt, - objectCreation.Constructor.Parameters, objectCreation.Expanded, objectCreation.Syntax); } @@ -282,12 +277,11 @@ internal ImmutableArray DeriveArguments(BoundNode containing return DeriveArguments(boundCall, boundCall.BinderOpt, boundCall.Method, - boundCall.Method, boundCall.Arguments, boundCall.ArgumentNamesOpt, boundCall.ArgsToParamsOpt, + boundCall.DefaultArguments, boundCall.ArgumentRefKindsOpt, - boundCall.Method.Parameters, boundCall.Expanded, boundCall.Syntax, boundCall.InvokedAsExtensionMethod); @@ -298,12 +292,11 @@ internal ImmutableArray DeriveArguments(BoundNode containing return DeriveArguments(boundCollectionElementInitializer, boundCollectionElementInitializer.BinderOpt, boundCollectionElementInitializer.AddMethod, - boundCollectionElementInitializer.AddMethod, boundCollectionElementInitializer.Arguments, argumentNamesOpt: default, boundCollectionElementInitializer.ArgsToParamsOpt, + boundCollectionElementInitializer.DefaultArguments, argumentRefKindsOpt: default, - boundCollectionElementInitializer.AddMethod.Parameters, boundCollectionElementInitializer.Expanded, boundCollectionElementInitializer.Syntax, boundCollectionElementInitializer.InvokedAsExtensionMethod); @@ -319,12 +312,11 @@ private ImmutableArray DeriveArguments( BoundNode boundNode, Binder binder, Symbol methodOrIndexer, - MethodSymbol? optionalParametersMethod, ImmutableArray boundArguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentsToParametersOpt, + BitVector defaultArguments, ImmutableArray argumentRefKindsOpt, - ImmutableArray parameters, bool expanded, SyntaxNode invocationSyntax, bool invokedAsExtensionMethod = false) @@ -332,22 +324,20 @@ private ImmutableArray DeriveArguments( // We can simply return empty array only if both parameters and boundArguments are empty, because: // - if only parameters is empty, there's error in code but we still need to return provided expression. // - if boundArguments is empty, then either there's error or we need to provide values for optional/param-array parameters. - if (parameters.IsDefaultOrEmpty && boundArguments.IsDefaultOrEmpty) + if (methodOrIndexer.GetParameters().IsDefaultOrEmpty && boundArguments.IsDefaultOrEmpty) { return ImmutableArray.Empty; } - Debug.Assert(optionalParametersMethod is not null); - return LocalRewriter.MakeArgumentsInEvaluationOrder( operationFactory: this, binder: binder, syntax: invocationSyntax, arguments: boundArguments, methodOrIndexer: methodOrIndexer, - optionalParametersMethod: optionalParametersMethod, expanded: expanded, argsToParamsOpt: argumentsToParametersOpt, + defaultArguments: defaultArguments, invokedAsExtensionMethod: invokedAsExtensionMethod); } #nullable disable diff --git a/src/Compilers/CSharp/Portable/SourceGeneration/CSharpGeneratorDriver.cs b/src/Compilers/CSharp/Portable/SourceGeneration/CSharpGeneratorDriver.cs index 9929e6a4a61bf..8a17671c8dfb9 100644 --- a/src/Compilers/CSharp/Portable/SourceGeneration/CSharpGeneratorDriver.cs +++ b/src/Compilers/CSharp/Portable/SourceGeneration/CSharpGeneratorDriver.cs @@ -62,5 +62,7 @@ internal override SyntaxTree ParseGeneratedSourceText(GeneratedSourceText input, internal override GeneratorDriver FromState(GeneratorDriverState state) => new CSharpGeneratorDriver(state); internal override CommonMessageProvider MessageProvider => CSharp.MessageProvider.Instance; + + internal override AdditionalSourcesCollection CreateSourcesCollection() => new AdditionalSourcesCollection(".cs"); } } diff --git a/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousType.TypePublicSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousType.TypePublicSymbol.cs index 1904a5bf76d77..0d646b56d8d50 100644 --- a/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousType.TypePublicSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousType.TypePublicSymbol.cs @@ -330,10 +330,8 @@ internal override ImmutableArray GetDeclaredInterfaces(ConsList internal override bool IsRecord => false; - internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison, IReadOnlyDictionary isValueTypeOverrideOpt = null) + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { - Debug.Assert(isValueTypeOverrideOpt == null); - if (ReferenceEquals(this, t2)) { return true; diff --git a/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.TypeParameterSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.TypeParameterSymbol.cs index 8adfadaea31b6..252080f9666c0 100644 --- a/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.TypeParameterSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.TypeParameterSymbol.cs @@ -72,6 +72,11 @@ public override bool HasReferenceTypeConstraint get { return false; } } + public override bool IsReferenceTypeFromConstraintTypes + { + get { return false; } + } + internal override bool? ReferenceTypeConstraintIsNullable { get { return false; } @@ -86,6 +91,11 @@ public override bool HasValueTypeConstraint get { return false; } } + public override bool IsValueTypeFromConstraintTypes + { + get { return false; } + } + public override bool HasUnmanagedTypeConstraint { get { return false; } @@ -101,11 +111,11 @@ public override VarianceKind Variance get { return VarianceKind.None; } } - internal override void EnsureAllConstraintsAreResolved(bool canIgnoreNullableContext) + internal override void EnsureAllConstraintsAreResolved() { } - internal override ImmutableArray GetConstraintTypes(ConsList inProgress, bool canIgnoreNullableContext) + internal override ImmutableArray GetConstraintTypes(ConsList inProgress) { return ImmutableArray.Empty; } diff --git a/src/Compilers/CSharp/Portable/Symbols/ArrayTypeSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/ArrayTypeSymbol.cs index 29c4693dd516e..5eb13ac1cca3d 100644 --- a/src/Compilers/CSharp/Portable/Symbols/ArrayTypeSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/ArrayTypeSymbol.cs @@ -337,12 +337,12 @@ public override TResult Accept(CSharpSymbolVisitor visitor) return visitor.VisitArrayType(this); } - internal override bool Equals(TypeSymbol? t2, TypeCompareKind comparison, IReadOnlyDictionary? isValueTypeOverrideOpt = null) + internal override bool Equals(TypeSymbol? t2, TypeCompareKind comparison) { - return this.Equals(t2 as ArrayTypeSymbol, comparison, isValueTypeOverrideOpt); + return this.Equals(t2 as ArrayTypeSymbol, comparison); } - private bool Equals(ArrayTypeSymbol? other, TypeCompareKind comparison, IReadOnlyDictionary? isValueTypeOverrideOpt) + private bool Equals(ArrayTypeSymbol? other, TypeCompareKind comparison) { if (ReferenceEquals(this, other)) { @@ -350,7 +350,7 @@ private bool Equals(ArrayTypeSymbol? other, TypeCompareKind comparison, IReadOnl } if ((object?)other == null || !other.HasSameShapeAs(this) || - !other.ElementTypeWithAnnotations.Equals(ElementTypeWithAnnotations, comparison, isValueTypeOverrideOpt)) + !other.ElementTypeWithAnnotations.Equals(ElementTypeWithAnnotations, comparison)) { return false; } diff --git a/src/Compilers/CSharp/Portable/Symbols/CompletionPart.cs b/src/Compilers/CSharp/Portable/Symbols/CompletionPart.cs index fd0189840d81c..ed8d0f09657bf 100644 --- a/src/Compilers/CSharp/Portable/Symbols/CompletionPart.cs +++ b/src/Compilers/CSharp/Portable/Symbols/CompletionPart.cs @@ -80,16 +80,27 @@ internal enum CompletionPart FinishMethodChecks = 1 << 14, MethodSymbolAll = Attributes | ReturnTypeAttributes | Parameters | Type | TypeParameters | StartMethodChecks | FinishMethodChecks | StartAsyncMethodChecks | FinishAsyncMethodChecks, + // For complex parameter symbols + StartDefaultSyntaxValue = 1 << 11, + EndDefaultSyntaxValue = 1 << 12, + EndDefaultSyntaxValueDiagnostics = 1 << 13, + ComplexParameterSymbolAll = Attributes | StartDefaultSyntaxValue | EndDefaultSyntaxValue | EndDefaultSyntaxValueDiagnostics, + // For type parameter symbols TypeParameterConstraints = 1 << 11, TypeParameterSymbolAll = Attributes | TypeParameterConstraints, // For property symbols - StartPropertyParameters = 1 << 4, - FinishPropertyParameters = 1 << 5, - StartPropertyType = 1 << 6, - FinishPropertyType = 1 << 7, - PropertySymbolAll = Attributes | StartPropertyParameters | FinishPropertyParameters | StartPropertyType | FinishPropertyType, + StartPropertyEnsureSignature = 1 << 4, + FinishPropertyEnsureSignature = 1 << 5, + StartPropertyParameters = 1 << 6, + FinishPropertyParameters = 1 << 7, + StartPropertyType = 1 << 8, + FinishPropertyType = 1 << 9, + StartPropertyFinalCompletion = 1 << 10, + FinishPropertyFinalCompletion = 1 << 11, + PropertySymbolAll = Attributes | StartPropertyEnsureSignature | FinishPropertyEnsureSignature | StartPropertyParameters | FinishPropertyParameters | + StartPropertyType | FinishPropertyType | StartPropertyFinalCompletion | FinishPropertyFinalCompletion, // For alias symbols AliasTarget = 1 << 4, diff --git a/src/Compilers/CSharp/Portable/Symbols/ConstraintsHelper.cs b/src/Compilers/CSharp/Portable/Symbols/ConstraintsHelper.cs index 1b9bb10ed3fa4..dc7b407e8f4ca 100644 --- a/src/Compilers/CSharp/Portable/Symbols/ConstraintsHelper.cs +++ b/src/Compilers/CSharp/Portable/Symbols/ConstraintsHelper.cs @@ -8,6 +8,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; @@ -71,13 +72,12 @@ public static TypeParameterBounds ResolveBounds( ConsList inProgress, ImmutableArray constraintTypes, bool inherited, - bool ignoresNullableContext, CSharpCompilation currentCompilation, DiagnosticBag diagnostics) { var diagnosticsBuilder = ArrayBuilder.GetInstance(); ArrayBuilder useSiteDiagnosticsBuilder = null; - var bounds = typeParameter.ResolveBounds(corLibrary, inProgress, constraintTypes, inherited, ignoresNullableContext: ignoresNullableContext, currentCompilation, diagnosticsBuilder, ref useSiteDiagnosticsBuilder); + var bounds = typeParameter.ResolveBounds(corLibrary, inProgress, constraintTypes, inherited, currentCompilation, diagnosticsBuilder, ref useSiteDiagnosticsBuilder); if (useSiteDiagnosticsBuilder != null) { @@ -100,7 +100,6 @@ public static TypeParameterBounds ResolveBounds( ConsList inProgress, ImmutableArray constraintTypes, bool inherited, - bool ignoresNullableContext, CSharpCompilation currentCompilation, ArrayBuilder diagnosticsBuilder, ref ArrayBuilder useSiteDiagnosticsBuilder) @@ -299,7 +298,7 @@ public static TypeParameterBounds ResolveBounds( return null; } - var bounds = new TypeParameterBounds(constraintTypes, interfaces, effectiveBaseClass, deducedBaseType, ignoresNullableContext); + var bounds = new TypeParameterBounds(constraintTypes, interfaces, effectiveBaseClass, deducedBaseType); // Additional constraint checks for overrides. if (inherited) @@ -310,37 +309,124 @@ public static TypeParameterBounds ResolveBounds( return bounds; } - internal static ImmutableArray MakeTypeParameterConstraints( - this Symbol containingSymbol, + internal static ImmutableArray> MakeTypeParameterConstraintTypes( + this MethodSymbol containingSymbol, Binder binder, ImmutableArray typeParameters, TypeParameterListSyntax typeParameterList, SyntaxList constraintClauses, - bool canIgnoreNullableContext, DiagnosticBag diagnostics) + { + if (typeParameters.Length == 0 || constraintClauses.Count == 0) + { + return ImmutableArray>.Empty; + } + + // Wrap binder from factory in a generic constraints specific binder + // to avoid checking constraints when binding type names. + Debug.Assert(!binder.Flags.Includes(BinderFlags.GenericConstraintsClause)); + binder = binder.WithAdditionalFlags(BinderFlags.GenericConstraintsClause | BinderFlags.SuppressConstraintChecks); + + ImmutableArray clauses; + clauses = binder.BindTypeParameterConstraintClauses(containingSymbol, typeParameters, typeParameterList, constraintClauses, + diagnostics, performOnlyCycleSafeValidation: false); + + if (clauses.All(clause => clause.ConstraintTypes.IsEmpty)) + { + return ImmutableArray>.Empty; + } + + return clauses.SelectAsArray(clause => clause.ConstraintTypes); + } + + internal static ImmutableArray MakeTypeParameterConstraintKinds( + this MethodSymbol containingSymbol, + Binder binder, + ImmutableArray typeParameters, + TypeParameterListSyntax typeParameterList, + SyntaxList constraintClauses) { if (typeParameters.Length == 0) { - return ImmutableArray.Empty; + return ImmutableArray.Empty; } + ImmutableArray clauses; + if (constraintClauses.Count == 0) { - ImmutableArray defaultClauses = binder.GetDefaultTypeParameterConstraintClauses(typeParameterList); + clauses = binder.GetDefaultTypeParameterConstraintClauses(typeParameterList); + } + else + { + // Wrap binder from factory in a generic constraints specific binder + // Also, suppress type argument binding in constraint types, this helps to avoid cycles while we figure out constraint kinds. + // to avoid checking constraints when binding type names. + Debug.Assert(!binder.Flags.Includes(BinderFlags.GenericConstraintsClause)); + binder = binder.WithAdditionalFlags(BinderFlags.GenericConstraintsClause | BinderFlags.SuppressConstraintChecks | BinderFlags.SuppressTypeArgumentBinding); - return defaultClauses.ContainsOnlyEmptyConstraintClauses() ? ImmutableArray.Empty : defaultClauses; + var discarded = DiagnosticBag.GetInstance(); // We will recompute this diagnostics more accurately later, when binding without BinderFlags.SuppressTypeArgumentBinding + clauses = binder.BindTypeParameterConstraintClauses(containingSymbol, typeParameters, typeParameterList, constraintClauses, + discarded, performOnlyCycleSafeValidation: true); + discarded.Free(); + + clauses = AdjustConstraintKindsBasedOnConstraintTypes(containingSymbol, typeParameters, clauses); } - // Wrap binder from factory in a generic constraints specific binder - // to avoid checking constraints when binding type names. - Debug.Assert(!binder.Flags.Includes(BinderFlags.GenericConstraintsClause)); - binder = binder.WithAdditionalFlags(BinderFlags.GenericConstraintsClause | BinderFlags.SuppressConstraintChecks); + if (clauses.All(clause => clause.Constraints == TypeParameterConstraintKind.None)) + { + return ImmutableArray.Empty; + } + + return clauses.SelectAsArray(clause => clause.Constraints); + } + + internal static ImmutableArray AdjustConstraintKindsBasedOnConstraintTypes(Symbol container, ImmutableArray typeParameters, ImmutableArray constraintClauses) + { + int arity = typeParameters.Length; + + Debug.Assert(constraintClauses.Length == arity); + + SmallDictionary isValueTypeMap = TypeParameterConstraintClause.BuildIsValueTypeMap(container, typeParameters, constraintClauses); + SmallDictionary isReferenceTypeFromConstraintTypesMap = TypeParameterConstraintClause.BuildIsReferenceTypeFromConstraintTypesMap(container, typeParameters, constraintClauses); + ArrayBuilder builder = null; + + for (int i = 0; i < arity; i++) + { + var constraint = constraintClauses[i]; + var typeParameter = typeParameters[i]; + TypeParameterConstraintKind constraintKind = constraint.Constraints; + + Debug.Assert((constraintKind & (TypeParameterConstraintKind.ValueTypeFromConstraintTypes | TypeParameterConstraintKind.ReferenceTypeFromConstraintTypes)) == 0); + + if ((constraintKind & TypeParameterConstraintKind.AllValueTypeKinds) == 0 && isValueTypeMap[typeParameter]) + { + constraintKind |= TypeParameterConstraintKind.ValueTypeFromConstraintTypes; + } + + if (isReferenceTypeFromConstraintTypesMap[typeParameter]) + { + constraintKind |= TypeParameterConstraintKind.ReferenceTypeFromConstraintTypes; + } + + if (constraint.Constraints != constraintKind) + { + if (builder == null) + { + builder = ArrayBuilder.GetInstance(constraintClauses.Length); + builder.AddRange(constraintClauses); + } + + builder[i] = TypeParameterConstraintClause.Create(constraintKind, constraint.ConstraintTypes); + } + } + + if (builder != null) + { + constraintClauses = builder.ToImmutableAndFree(); + } - IReadOnlyDictionary isValueTypeOverride = null; - return binder.BindTypeParameterConstraintClauses(containingSymbol, typeParameters, typeParameterList, constraintClauses, - canIgnoreNullableContext, - ref isValueTypeOverride, - diagnostics); + return constraintClauses; } // Based on SymbolLoader::SetOverrideConstraints. @@ -1147,12 +1233,12 @@ private static bool SatisfiesConstraintType( private static bool IsReferenceType(TypeParameterSymbol typeParameter, ImmutableArray constraintTypes) { - return typeParameter.HasReferenceTypeConstraint || TypeParameterSymbol.IsReferenceTypeFromConstraintTypes(constraintTypes); + return typeParameter.HasReferenceTypeConstraint || TypeParameterSymbol.CalculateIsReferenceTypeFromConstraintTypes(constraintTypes); } private static bool IsValueType(TypeParameterSymbol typeParameter, ImmutableArray constraintTypes) { - return typeParameter.HasValueTypeConstraint || TypeParameterSymbol.IsValueTypeFromConstraintTypes(constraintTypes); + return typeParameter.HasValueTypeConstraint || TypeParameterSymbol.CalculateIsValueTypeFromConstraintTypes(constraintTypes); } private static TypeParameterDiagnosticInfo GenerateConflictingConstraintsError(TypeParameterSymbol typeParameter, TypeSymbol deducedBase, bool classConflict) diff --git a/src/Compilers/CSharp/Portable/Symbols/DynamicTypeSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/DynamicTypeSymbol.cs index 667f7d1081e6f..8dfb42522cd38 100644 --- a/src/Compilers/CSharp/Portable/Symbols/DynamicTypeSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/DynamicTypeSymbol.cs @@ -192,7 +192,7 @@ public override int GetHashCode() return (int)Microsoft.CodeAnalysis.SpecialType.System_Object; } - internal override bool Equals(TypeSymbol? t2, TypeCompareKind comparison, IReadOnlyDictionary? isValueTypeOverrideOpt = null) + internal override bool Equals(TypeSymbol? t2, TypeCompareKind comparison) { if ((object?)t2 == null) { diff --git a/src/Compilers/CSharp/Portable/Symbols/ErrorTypeSymbol.ErrorTypeParameterSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/ErrorTypeSymbol.ErrorTypeParameterSymbol.cs index 7c9e2c5bbf36a..efe4c2211d380 100644 --- a/src/Compilers/CSharp/Portable/Symbols/ErrorTypeSymbol.ErrorTypeParameterSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/ErrorTypeSymbol.ErrorTypeParameterSymbol.cs @@ -63,6 +63,14 @@ public override bool HasReferenceTypeConstraint } } + public override bool IsReferenceTypeFromConstraintTypes + { + get + { + return false; + } + } + internal override bool? ReferenceTypeConstraintIsNullable { get @@ -83,6 +91,14 @@ public override bool HasValueTypeConstraint } } + public override bool IsValueTypeFromConstraintTypes + { + get + { + return false; + } + } + public override bool HasUnmanagedTypeConstraint { get @@ -131,11 +147,11 @@ public override bool IsImplicitlyDeclared } } - internal override void EnsureAllConstraintsAreResolved(bool canIgnoreNullableContext) + internal override void EnsureAllConstraintsAreResolved() { } - internal override ImmutableArray GetConstraintTypes(ConsList inProgress, bool canIgnoreNullableContext) + internal override ImmutableArray GetConstraintTypes(ConsList inProgress) { return ImmutableArray.Empty; } @@ -160,7 +176,7 @@ public override int GetHashCode() return Hash.Combine(_container.GetHashCode(), _ordinal); } - internal override bool Equals(TypeSymbol? t2, TypeCompareKind comparison, IReadOnlyDictionary? isValueTypeOverrideOpt = null) + internal override bool Equals(TypeSymbol? t2, TypeCompareKind comparison) { if (ReferenceEquals(this, t2)) { @@ -170,7 +186,7 @@ internal override bool Equals(TypeSymbol? t2, TypeCompareKind comparison, IReadO var other = t2 as ErrorTypeParameterSymbol; return (object?)other != null && other._ordinal == _ordinal && - other.ContainingType.Equals(this.ContainingType, comparison, isValueTypeOverrideOpt); + other.ContainingType.Equals(this.ContainingType, comparison); } } } diff --git a/src/Compilers/CSharp/Portable/Symbols/ExtendedErrorTypeSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/ExtendedErrorTypeSymbol.cs index 3eea818368fc5..e9ff594eb1100 100644 --- a/src/Compilers/CSharp/Portable/Symbols/ExtendedErrorTypeSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/ExtendedErrorTypeSymbol.cs @@ -280,7 +280,7 @@ internal static TypeKind ExtractNonErrorTypeKind(TypeSymbol oldSymbol) return commonTypeKind; } - internal override bool Equals(TypeSymbol? t2, TypeCompareKind comparison, IReadOnlyDictionary? isValueTypeOverrideOpt = null) + internal override bool Equals(TypeSymbol? t2, TypeCompareKind comparison) { if (ReferenceEquals(this, t2)) { @@ -294,7 +294,7 @@ internal override bool Equals(TypeSymbol? t2, TypeCompareKind comparison, IReadO } return - ((object)this.ContainingType != null ? this.ContainingType.Equals(other.ContainingType, comparison, isValueTypeOverrideOpt) : + ((object)this.ContainingType != null ? this.ContainingType.Equals(other.ContainingType, comparison) : (object?)this.ContainingSymbol == null ? (object?)other.ContainingSymbol == null : this.ContainingSymbol.Equals(other.ContainingSymbol)) && this.Name == other.Name && this.Arity == other.Arity; } diff --git a/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerMethodSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerMethodSymbol.cs index 0ce9046675abe..e6e39ce81b085 100644 --- a/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerMethodSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerMethodSymbol.cs @@ -698,22 +698,22 @@ public override bool Equals(Symbol other, TypeCompareKind compareKind) return false; } - return Equals(method, compareKind, isValueTypeOverride: null); + return Equals(method, compareKind); } - internal bool Equals(FunctionPointerMethodSymbol other, TypeCompareKind compareKind, IReadOnlyDictionary? isValueTypeOverride) + internal bool Equals(FunctionPointerMethodSymbol other, TypeCompareKind compareKind) { return ReferenceEquals(this, other) || - (EqualsNoParameters(other, compareKind, isValueTypeOverride) - && _parameters.SequenceEqual(other._parameters, (compareKind, isValueTypeOverride), - (param1, param2, args) => param1.MethodEqualityChecks(param2, args.compareKind, args.isValueTypeOverride))); + (EqualsNoParameters(other, compareKind) + && _parameters.SequenceEqual(other._parameters, compareKind, + (param1, param2, compareKind) => param1.MethodEqualityChecks(param2, compareKind))); } - private bool EqualsNoParameters(FunctionPointerMethodSymbol other, TypeCompareKind compareKind, IReadOnlyDictionary? isValueTypeOverride) + private bool EqualsNoParameters(FunctionPointerMethodSymbol other, TypeCompareKind compareKind) { if (CallingConvention != other.CallingConvention || !FunctionPointerTypeSymbol.RefKindEquals(compareKind, RefKind, other.RefKind) - || !ReturnTypeWithAnnotations.Equals(other.ReturnTypeWithAnnotations, compareKind, isValueTypeOverride)) + || !ReturnTypeWithAnnotations.Equals(other.ReturnTypeWithAnnotations, compareKind)) { return false; } diff --git a/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerParameterSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerParameterSymbol.cs index 46a4d5319994b..7cb664a1fafd4 100644 --- a/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerParameterSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerParameterSymbol.cs @@ -40,18 +40,18 @@ public override bool Equals(Symbol other, TypeCompareKind compareKind) return false; } - return Equals(param, compareKind, isValueTypeOverride: null); + return Equals(param, compareKind); } - internal bool Equals(FunctionPointerParameterSymbol other, TypeCompareKind compareKind, IReadOnlyDictionary? isValueTypeOverride) + internal bool Equals(FunctionPointerParameterSymbol other, TypeCompareKind compareKind) => other.Ordinal == Ordinal - && _containingSymbol.Equals(other._containingSymbol, compareKind, isValueTypeOverride); + && _containingSymbol.Equals(other._containingSymbol, compareKind); - internal bool MethodEqualityChecks(FunctionPointerParameterSymbol other, TypeCompareKind compareKind, IReadOnlyDictionary? isValueTypeOverride) + internal bool MethodEqualityChecks(FunctionPointerParameterSymbol other, TypeCompareKind compareKind) => FunctionPointerTypeSymbol.RefKindEquals(compareKind, RefKind, other.RefKind) && ((compareKind & TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds) != 0 || RefCustomModifiers.SequenceEqual(other.RefCustomModifiers)) - && TypeWithAnnotations.Equals(other.TypeWithAnnotations, compareKind, isValueTypeOverride); + && TypeWithAnnotations.Equals(other.TypeWithAnnotations, compareKind); public override int GetHashCode() { diff --git a/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerTypeSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerTypeSymbol.cs index ac6d381fe816b..962e2ecc4d29a 100644 --- a/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerTypeSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerTypeSymbol.cs @@ -96,7 +96,7 @@ private FunctionPointerTypeSymbol(FunctionPointerMethodSymbol signature) internal override TResult Accept(CSharpSymbolVisitor visitor, TArgument a) => visitor.VisitFunctionPointerType(this, a); internal override ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList? basesBeingResolved = null) => ImmutableArray.Empty; - internal override bool Equals(TypeSymbol t2, TypeCompareKind compareKind, IReadOnlyDictionary? isValueTypeOverrideOpt = null) + internal override bool Equals(TypeSymbol t2, TypeCompareKind compareKind) { if (ReferenceEquals(this, t2)) { @@ -108,7 +108,7 @@ internal override bool Equals(TypeSymbol t2, TypeCompareKind compareKind, IReadO return false; } - return Signature.Equals(other.Signature, compareKind, isValueTypeOverrideOpt); + return Signature.Equals(other.Signature, compareKind); } public override int GetHashCode() diff --git a/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEMethodSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEMethodSymbol.cs index 64bd26d8a0f77..84f3e0b91bba4 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEMethodSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEMethodSymbol.cs @@ -11,7 +11,6 @@ using System.Globalization; using System.Reflection; using System.Reflection.Metadata; -using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.DocumentationComments; using Microsoft.CodeAnalysis.CSharp.Emit; @@ -1194,9 +1193,6 @@ private MethodKind ComputeMethodKind() public override ImmutableArray ExplicitInterfaceImplementations { - // Disabling optimization to work around a JIT bug in .NET 5. - // See https://github.com/dotnet/roslyn/issues/46575 - [MethodImpl(MethodImplOptions.NoOptimization)] get { var explicitInterfaceImplementations = _lazyExplicitMethodImplementations; diff --git a/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PENamedTypeSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PENamedTypeSymbol.cs index 09d6fedf4fb86..d2c250534fe54 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PENamedTypeSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PENamedTypeSymbol.cs @@ -2350,11 +2350,11 @@ internal override NamedTypeSymbol AsNativeInteger() internal override NamedTypeSymbol NativeIntegerUnderlyingType => null; - internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison, IReadOnlyDictionary isValueTypeOverrideOpt = null) + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { return t2 is NativeIntegerTypeSymbol nativeInteger ? - nativeInteger.Equals(this, comparison, isValueTypeOverrideOpt) : - base.Equals(t2, comparison, isValueTypeOverrideOpt); + nativeInteger.Equals(this, comparison) : + base.Equals(t2, comparison); } } diff --git a/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PETypeParameterSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PETypeParameterSymbol.cs index 59f70c45addb3..b3418c1a6723d 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PETypeParameterSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PETypeParameterSymbol.cs @@ -453,6 +453,14 @@ public override bool HasReferenceTypeConstraint } } + public override bool IsReferenceTypeFromConstraintTypes + { + get + { + return CalculateIsReferenceTypeFromConstraintTypes(ConstraintTypesNoUseSiteDiagnostics); + } + } + /// /// Returns the byte value from the (single byte) NullableAttribute or nearest /// NullableContextAttribute. Returns 0 if neither attribute is specified. @@ -553,6 +561,15 @@ public override bool HasValueTypeConstraint } } + public override bool IsValueTypeFromConstraintTypes + { + get + { + Debug.Assert(!HasValueTypeConstraint); + return CalculateIsValueTypeFromConstraintTypes(ConstraintTypesNoUseSiteDiagnostics); + } + } + public override bool HasUnmanagedTypeConstraint { get @@ -570,19 +587,18 @@ public override VarianceKind Variance } } - internal override void EnsureAllConstraintsAreResolved(bool canIgnoreNullableContext) + internal override void EnsureAllConstraintsAreResolved() { - canIgnoreNullableContext = false; // Resolve bounds eagerly. - if (!_lazyBounds.HasValue(canIgnoreNullableContext)) + if (!_lazyBounds.IsSet()) { var typeParameters = (_containingSymbol.Kind == SymbolKind.Method) ? ((PEMethodSymbol)_containingSymbol).TypeParameters : ((PENamedTypeSymbol)_containingSymbol).TypeParameters; - EnsureAllConstraintsAreResolved(typeParameters, canIgnoreNullableContext); + EnsureAllConstraintsAreResolved(typeParameters); } } - internal override ImmutableArray GetConstraintTypes(ConsList inProgress, bool canIgnoreNullableContext) + internal override ImmutableArray GetConstraintTypes(ConsList inProgress) { var bounds = this.GetBounds(inProgress); return (bounds != null) ? bounds.ConstraintTypes : ImmutableArray.Empty; @@ -637,7 +653,7 @@ private TypeParameterBounds GetBounds(ConsList inProgress) var diagnostics = ArrayBuilder.GetInstance(); ArrayBuilder useSiteDiagnosticsBuilder = null; bool inherited = (_containingSymbol.Kind == SymbolKind.Method) && ((MethodSymbol)_containingSymbol).IsOverride; - var bounds = this.ResolveBounds(this.ContainingAssembly.CorLibrary, inProgress.Prepend(this), constraintTypes, inherited, ignoresNullableContext: false, currentCompilation: null, + var bounds = this.ResolveBounds(this.ContainingAssembly.CorLibrary, inProgress.Prepend(this), constraintTypes, inherited, currentCompilation: null, diagnosticsBuilder: diagnostics, useSiteDiagnosticsBuilder: ref useSiteDiagnosticsBuilder); DiagnosticInfo errorInfo = null; @@ -673,7 +689,7 @@ private TypeParameterBounds GetBounds(ConsList inProgress) internal override DiagnosticInfo GetConstraintsUseSiteErrorInfo() { - EnsureAllConstraintsAreResolved(canIgnoreNullableContext: false); + EnsureAllConstraintsAreResolved(); Debug.Assert(!ReferenceEquals(_lazyConstraintsUseSiteErrorInfo, CSDiagnosticInfo.EmptyErrorInfo)); return _lazyConstraintsUseSiteErrorInfo; } diff --git a/src/Compilers/CSharp/Portable/Symbols/MissingMetadataTypeSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/MissingMetadataTypeSymbol.cs index 34274c1112a95..7536f79854e32 100644 --- a/src/Compilers/CSharp/Portable/Symbols/MissingMetadataTypeSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/MissingMetadataTypeSymbol.cs @@ -347,7 +347,7 @@ private TopLevel AsNativeInteger(bool asNativeInt) internal sealed override NamedTypeSymbol? NativeIntegerUnderlyingType => _isNativeInt ? AsNativeInteger(asNativeInt: false) : null; - internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison, IReadOnlyDictionary? isValueTypeOverrideOpt = null) + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { if (ReferenceEquals(this, t2)) { @@ -437,7 +437,7 @@ public override int GetHashCode() return Hash.Combine(_containingType, Hash.Combine(MetadataName, arity)); } - internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison, IReadOnlyDictionary? isValueTypeOverrideOpt = null) + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { if (ReferenceEquals(this, t2)) { @@ -447,7 +447,7 @@ internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison, IReadOn var other = t2 as Nested; return (object?)other != null && string.Equals(MetadataName, other.MetadataName, StringComparison.Ordinal) && arity == other.arity && - _containingType.Equals(other._containingType, comparison, isValueTypeOverrideOpt); + _containingType.Equals(other._containingType, comparison); } } } diff --git a/src/Compilers/CSharp/Portable/Symbols/NamedTypeSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/NamedTypeSymbol.cs index db3af4e24bfee..3b431ddfbb454 100644 --- a/src/Compilers/CSharp/Portable/Symbols/NamedTypeSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/NamedTypeSymbol.cs @@ -65,7 +65,7 @@ internal ImmutableArray TypeArgumentsWithDefinitionUseSiteD foreach (var typeArgument in result) { - AddDefinitionUseSiteDiagnostics(typeArgument, ref useSiteDiagnostics); + typeArgument.Type.OriginalDefinition.AddUseSiteDiagnostics(ref useSiteDiagnostics); } return result; @@ -74,15 +74,10 @@ internal ImmutableArray TypeArgumentsWithDefinitionUseSiteD internal TypeWithAnnotations TypeArgumentWithDefinitionUseSiteDiagnostics(int index, ref HashSet useSiteDiagnostics) { var result = TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[index]; - AddDefinitionUseSiteDiagnostics(result, ref useSiteDiagnostics); + result.Type.OriginalDefinition.AddUseSiteDiagnostics(ref useSiteDiagnostics); return result; } - private static void AddDefinitionUseSiteDiagnostics(TypeWithAnnotations type, ref HashSet useSiteDiagnostics) - { - type.DefaultType.OriginalDefinition.AddUseSiteDiagnostics(ref useSiteDiagnostics); - } - /// /// Returns the type symbol that this type was constructed from. This type symbol /// has the same containing type (if any), but has type arguments that are the same @@ -648,7 +643,7 @@ public override int GetHashCode() /// /// Compares this type to another type. /// - internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison, IReadOnlyDictionary isValueTypeOverrideOpt = null) + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { if ((object)t2 == this) return true; if ((object)t2 == null) return false; @@ -691,23 +686,23 @@ internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison, IReadOn // symbols. Therefore this code may not behave correctly if 'this' is List // where List`1 is a missing metadata type symbol, and other is similarly List // but for a reference-distinct List`1. - if (!Equals(thisOriginalDefinition, otherOriginalDefinition, comparison, isValueTypeOverrideOpt)) + if (!Equals(thisOriginalDefinition, otherOriginalDefinition, comparison)) { return false; } // The checks above are supposed to handle the vast majority of cases. // More complicated cases are handled in a special helper to make the common case scenario simple/fast (fewer locals and smaller stack frame) - return EqualsComplicatedCases(other, comparison, isValueTypeOverrideOpt); + return EqualsComplicatedCases(other, comparison); } /// /// Helper for more complicated cases of Equals like when we have generic instantiations or types nested within them. /// - private bool EqualsComplicatedCases(NamedTypeSymbol other, TypeCompareKind comparison, IReadOnlyDictionary isValueTypeOverrideOpt) + private bool EqualsComplicatedCases(NamedTypeSymbol other, TypeCompareKind comparison) { if ((object)this.ContainingType != null && - !this.ContainingType.Equals(other.ContainingType, comparison, isValueTypeOverrideOpt)) + !this.ContainingType.Equals(other.ContainingType, comparison)) { return false; } @@ -747,7 +742,7 @@ private bool EqualsComplicatedCases(NamedTypeSymbol other, TypeCompareKind compa { var typeArgument = typeArguments[i]; var otherTypeArgument = otherTypeArguments[i]; - if (!typeArgument.Equals(otherTypeArgument, comparison, isValueTypeOverrideOpt)) + if (!typeArgument.Equals(otherTypeArgument, comparison)) { return false; } diff --git a/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs index 27fba0edda5d0..f42a29fdc6bfb 100644 --- a/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs @@ -166,7 +166,7 @@ ImmutableArray makeMembers(ImmutableArray underlyingMembers) internal sealed override bool IsRecord => false; internal sealed override bool HasPossibleWellKnownCloneMethod() => false; - internal override bool Equals(TypeSymbol? other, TypeCompareKind comparison, IReadOnlyDictionary? isValueTypeOverrideOpt = null) + internal override bool Equals(TypeSymbol? other, TypeCompareKind comparison) { if (other is null) { @@ -176,7 +176,7 @@ internal override bool Equals(TypeSymbol? other, TypeCompareKind comparison, IRe { return true; } - if (!_underlyingType.Equals(other, comparison, isValueTypeOverrideOpt)) + if (!_underlyingType.Equals(other, comparison)) { return false; } diff --git a/src/Compilers/CSharp/Portable/Symbols/NoPiaAmbiguousCanonicalTypeSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/NoPiaAmbiguousCanonicalTypeSymbol.cs index e652a6e888cab..0b578b6715240 100644 --- a/src/Compilers/CSharp/Portable/Symbols/NoPiaAmbiguousCanonicalTypeSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/NoPiaAmbiguousCanonicalTypeSymbol.cs @@ -86,7 +86,7 @@ public override int GetHashCode() return RuntimeHelpers.GetHashCode(this); } - internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison, IReadOnlyDictionary? isValueTypeOverrideOpt = null) + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { return ReferenceEquals(this, t2); } diff --git a/src/Compilers/CSharp/Portable/Symbols/NoPiaIllegalGenericInstantiationSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/NoPiaIllegalGenericInstantiationSymbol.cs index 5bc8369126972..f8247bddef230 100644 --- a/src/Compilers/CSharp/Portable/Symbols/NoPiaIllegalGenericInstantiationSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/NoPiaIllegalGenericInstantiationSymbol.cs @@ -72,7 +72,7 @@ public override int GetHashCode() return RuntimeHelpers.GetHashCode(this); } - internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison, IReadOnlyDictionary? isValueTypeOverrideOpt = null) + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { return ReferenceEquals(this, t2); } diff --git a/src/Compilers/CSharp/Portable/Symbols/NoPiaMissingCanonicalTypeSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/NoPiaMissingCanonicalTypeSymbol.cs index 505fad6d2937b..c50c29cbe0fad 100644 --- a/src/Compilers/CSharp/Portable/Symbols/NoPiaMissingCanonicalTypeSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/NoPiaMissingCanonicalTypeSymbol.cs @@ -110,7 +110,7 @@ public override int GetHashCode() return RuntimeHelpers.GetHashCode(this); } - internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison, IReadOnlyDictionary? isValueTypeOverrideOpt = null) + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { return ReferenceEquals(this, t2); } diff --git a/src/Compilers/CSharp/Portable/Symbols/ParameterSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/ParameterSymbol.cs index b6054d515ef7e..d9d946daea76e 100644 --- a/src/Compilers/CSharp/Portable/Symbols/ParameterSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/ParameterSymbol.cs @@ -232,6 +232,7 @@ public object ExplicitDefaultValue } } +#nullable enable /// /// Returns the default value constant of the parameter, /// or null if the parameter doesn't have a default value or @@ -243,7 +244,8 @@ public object ExplicitDefaultValue /// This is used for emitting. It does not reflect the language semantics /// (i.e. even non-optional parameters can have default values). /// - internal abstract ConstantValue ExplicitDefaultConstantValue { get; } + internal abstract ConstantValue? ExplicitDefaultConstantValue { get; } +#nullable disable /// /// Gets the kind of this symbol. diff --git a/src/Compilers/CSharp/Portable/Symbols/PlaceholderTypeArgumentSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/PlaceholderTypeArgumentSymbol.cs new file mode 100644 index 0000000000000..3c8eb1aa884d2 --- /dev/null +++ b/src/Compilers/CSharp/Portable/Symbols/PlaceholderTypeArgumentSymbol.cs @@ -0,0 +1,70 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Immutable; +using System.Diagnostics; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols +{ + /// + /// Used for lightweight binding of type constraints. Instead of binding type arguments, + /// we'll just use these placeholders instead. That's good enough binding to compute + /// with minimal binding. + /// + internal sealed class PlaceholderTypeArgumentSymbol : ErrorTypeSymbol + { + private static readonly TypeWithAnnotations s_instance = TypeWithAnnotations.Create(new PlaceholderTypeArgumentSymbol()); + + public static ImmutableArray CreateTypeArguments(ImmutableArray typeParameters) + { + return typeParameters.SelectAsArray(_ => s_instance); + } + + private PlaceholderTypeArgumentSymbol() + { + } + + protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + throw ExceptionUtilities.Unreachable; + } + + public override string Name + { + get + { + return string.Empty; + } + } + + internal override bool MangleName + { + get + { + Debug.Assert(Arity == 0); + return false; + } + } + + internal override DiagnosticInfo? ErrorInfo + { + get + { + return null; + } + } + + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) + { + return (object)t2 == this; + } + + public override int GetHashCode() + { + return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(this); + } + } +} + diff --git a/src/Compilers/CSharp/Portable/Symbols/PointerTypeSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/PointerTypeSymbol.cs index 49b666168577c..ed886a99c7f43 100644 --- a/src/Compilers/CSharp/Portable/Symbols/PointerTypeSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/PointerTypeSymbol.cs @@ -227,19 +227,19 @@ public override int GetHashCode() return Hash.Combine(current, indirections); } - internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison, IReadOnlyDictionary isValueTypeOverrideOpt = null) + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { - return this.Equals(t2 as PointerTypeSymbol, comparison, isValueTypeOverrideOpt); + return this.Equals(t2 as PointerTypeSymbol, comparison); } - private bool Equals(PointerTypeSymbol other, TypeCompareKind comparison, IReadOnlyDictionary isValueTypeOverrideOpt) + private bool Equals(PointerTypeSymbol other, TypeCompareKind comparison) { if (ReferenceEquals(this, other)) { return true; } - if ((object)other == null || !other._pointedAtType.Equals(_pointedAtType, comparison, isValueTypeOverrideOpt)) + if ((object)other == null || !other._pointedAtType.Equals(_pointedAtType, comparison)) { return false; } diff --git a/src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingTypeParameterSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingTypeParameterSymbol.cs index 2aa4ba2582d18..2ff127565b8d0 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingTypeParameterSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingTypeParameterSymbol.cs @@ -81,9 +81,9 @@ internal override ModuleSymbol ContainingModule } } - internal override ImmutableArray GetConstraintTypes(ConsList inProgress, bool canIgnoreNullableContext) + internal override ImmutableArray GetConstraintTypes(ConsList inProgress) { - return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetConstraintTypes(inProgress, canIgnoreNullableContext)); + return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetConstraintTypes(inProgress)); } internal override bool? IsNotNullable diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/CrefTypeParameterSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/CrefTypeParameterSymbol.cs index 7afe51cd7308f..fc58366c6ee63 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/CrefTypeParameterSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/CrefTypeParameterSymbol.cs @@ -93,10 +93,8 @@ public override int Ordinal get { return _ordinal; } } - internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison, IReadOnlyDictionary isValueTypeOverrideOpt = null) + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { - Debug.Assert(isValueTypeOverrideOpt == null); - if (ReferenceEquals(this, t2)) { return true; @@ -129,11 +127,21 @@ public override bool HasValueTypeConstraint get { return false; } } + public override bool IsValueTypeFromConstraintTypes + { + get { return false; } + } + public override bool HasReferenceTypeConstraint { get { return false; } } + public override bool IsReferenceTypeFromConstraintTypes + { + get { return false; } + } + internal override bool? ReferenceTypeConstraintIsNullable { get { return false; } @@ -177,11 +185,11 @@ public override ImmutableArray DeclaringSyntaxReferences } } - internal override void EnsureAllConstraintsAreResolved(bool canIgnoreNullableContext) + internal override void EnsureAllConstraintsAreResolved() { } - internal override ImmutableArray GetConstraintTypes(ConsList inProgress, bool canIgnoreNullableContext) + internal override ImmutableArray GetConstraintTypes(ConsList inProgress) { return ImmutableArray.Empty; } diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/IndexedTypeParameterSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/IndexedTypeParameterSymbol.cs index 9a00eec1ce2cc..063dfe270c7b7 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/IndexedTypeParameterSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/IndexedTypeParameterSymbol.cs @@ -105,7 +105,7 @@ public override int Ordinal } // These object are unique (per index). - internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison, IReadOnlyDictionary isValueTypeOverrideOpt = null) + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { return ReferenceEquals(this, t2); } @@ -125,11 +125,21 @@ public override bool HasValueTypeConstraint get { return false; } } + public override bool IsValueTypeFromConstraintTypes + { + get { return false; } + } + public override bool HasReferenceTypeConstraint { get { return false; } } + public override bool IsReferenceTypeFromConstraintTypes + { + get { return false; } + } + internal override bool? ReferenceTypeConstraintIsNullable { get { return false; } @@ -173,11 +183,11 @@ public override ImmutableArray DeclaringSyntaxReferences } } - internal override void EnsureAllConstraintsAreResolved(bool canIgnoreNullableContext) + internal override void EnsureAllConstraintsAreResolved() { } - internal override ImmutableArray GetConstraintTypes(ConsList inProgress, bool canIgnoreNullableContext) + internal override ImmutableArray GetConstraintTypes(ConsList inProgress) { return ImmutableArray.Empty; } diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/LambdaSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/LambdaSymbol.cs index 2ec0efa7c70e7..15dac695e754c 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/LambdaSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/LambdaSymbol.cs @@ -417,7 +417,9 @@ internal override bool GenerateDebugInfo internal override bool IsInitOnly => false; - public override ImmutableArray GetTypeParameterConstraintClauses(bool canIgnoreNullableContext) => ImmutableArray.Empty; + public override ImmutableArray> GetTypeParameterConstraintTypes() => ImmutableArray>.Empty; + + public override ImmutableArray GetTypeParameterConstraintKinds() => ImmutableArray.Empty; internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/LocalFunctionSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/LocalFunctionSymbol.cs index 7ebbfd84eec8b..43e3c79da6a07 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/LocalFunctionSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/LocalFunctionSymbol.cs @@ -23,7 +23,8 @@ internal sealed class LocalFunctionSymbol : SourceMethodSymbolWithAttributes private ImmutableArray _lazyParameters; private bool _lazyIsVarArg; // Initialized in two steps. Hold a copy if accessing during initialization. - private ImmutableArray _lazyTypeParameterConstraints; + private ImmutableArray> _lazyTypeParameterConstraintTypes; + private ImmutableArray _lazyTypeParameterConstraintKinds; private TypeWithAnnotations.Boxed? _lazyReturnType; private TypeWithAnnotations.Boxed? _lazyIteratorElementType; @@ -459,35 +460,49 @@ private ImmutableArray MakeTypeParameters(Diagn return result.ToImmutableAndFree(); } - public override ImmutableArray GetTypeParameterConstraintClauses(bool canIgnoreNullableContext) + public override ImmutableArray> GetTypeParameterConstraintTypes() { - if (!_lazyTypeParameterConstraints.HasValue(canIgnoreNullableContext)) + if (_lazyTypeParameterConstraintTypes.IsDefault) { + GetTypeParameterConstraintKinds(); + var syntax = Syntax; var diagnostics = DiagnosticBag.GetInstance(); - var constraints = this.MakeTypeParameterConstraints( + var constraints = this.MakeTypeParameterConstraintTypes( _binder, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses, - canIgnoreNullableContext, diagnostics); lock (_declarationDiagnostics) { - canIgnoreNullableContext = constraints.IgnoresNullableContext(); - if (!_lazyTypeParameterConstraints.HasValue(canIgnoreNullableContext)) + if (_lazyTypeParameterConstraintTypes.IsDefault) { - if (!canIgnoreNullableContext) - { - _declarationDiagnostics.AddRange(diagnostics); - } - _lazyTypeParameterConstraints = constraints; + _declarationDiagnostics.AddRange(diagnostics); + _lazyTypeParameterConstraintTypes = constraints; } } diagnostics.Free(); } - return _lazyTypeParameterConstraints; + return _lazyTypeParameterConstraintTypes; + } + + public override ImmutableArray GetTypeParameterConstraintKinds() + { + if (_lazyTypeParameterConstraintKinds.IsDefault) + { + var syntax = Syntax; + var constraints = this.MakeTypeParameterConstraintKinds( + _binder, + TypeParameters, + syntax.TypeParameterList, + syntax.ConstraintClauses); + + ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameterConstraintKinds, constraints); + } + + return _lazyTypeParameterConstraintKinds; } public override int GetHashCode() diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceComplexParameterSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceComplexParameterSymbol.cs index 83fecabf2c2c3..fef13c0966383 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceComplexParameterSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceComplexParameterSymbol.cs @@ -44,7 +44,6 @@ internal SourceComplexParameterSymbol( string name, ImmutableArray locations, SyntaxReference syntaxRef, - ConstantValue defaultSyntaxValue, bool isParams, bool isExtensionMethodThis) : base(owner, parameterType, ordinal, refKind, name, locations) @@ -71,7 +70,7 @@ internal SourceComplexParameterSymbol( _parameterSyntaxKind |= ParameterSyntaxKind.DefaultParameter; } - _lazyDefaultSyntaxValue = defaultSyntaxValue; + _lazyDefaultSyntaxValue = ConstantValue.Unset; } private Binder ParameterBinderOpt => (ContainingSymbol as LocalFunctionSymbol)?.ParameterBinder; @@ -80,8 +79,6 @@ internal SourceComplexParameterSymbol( internal ParameterSyntax CSharpSyntaxNode => (ParameterSyntax)_syntaxRef?.GetSyntax(); - internal SyntaxTree SyntaxTree => _syntaxRef == null ? null : _syntaxRef.SyntaxTree; - public sealed override bool IsDiscard => false; internal override ConstantValue ExplicitDefaultConstantValue @@ -196,38 +193,108 @@ internal bool HasEnumeratorCancellationAttribute } } +#nullable enable + private ConstantValue DefaultSyntaxValue { get { - if (_lazyDefaultSyntaxValue == ConstantValue.Unset) + if (state.NotePartComplete(CompletionPart.StartDefaultSyntaxValue)) { var diagnostics = DiagnosticBag.GetInstance(); - - if (Interlocked.CompareExchange( + var previousValue = Interlocked.CompareExchange( ref _lazyDefaultSyntaxValue, - MakeDefaultExpression(diagnostics, ParameterBinderOpt), - ConstantValue.Unset) == ConstantValue.Unset) + MakeDefaultExpression(diagnostics, out var binder, out var parameterEqualsValue), + ConstantValue.Unset); + Debug.Assert(previousValue == ConstantValue.Unset); + + var completedOnThisThread = state.NotePartComplete(CompletionPart.EndDefaultSyntaxValue); + Debug.Assert(completedOnThisThread); + + if (binder is not null && parameterEqualsValue is not null && !_lazyDefaultSyntaxValue.IsBad) { - // This is a race condition where the thread that loses - // the compare exchange tries to access the diagnostics - // before the thread which won the race finishes adding - // them. https://github.com/dotnet/roslyn/issues/17243 - AddDeclarationDiagnostics(diagnostics); + NullableWalker.AnalyzeIfNeeded(binder, parameterEqualsValue, diagnostics); + VerifyParamDefaultValueMatchesAttributeIfAny(_lazyDefaultSyntaxValue, parameterEqualsValue.Value.Syntax, diagnostics); } + AddDeclarationDiagnostics(diagnostics); diagnostics.Free(); + + completedOnThisThread = state.NotePartComplete(CompletionPart.EndDefaultSyntaxValueDiagnostics); + Debug.Assert(completedOnThisThread); } + state.SpinWaitComplete(CompletionPart.EndDefaultSyntaxValue, default(CancellationToken)); return _lazyDefaultSyntaxValue; } } - // If binder is null, then get it from the compilation. Otherwise use the provided binder. - // Don't always get it from the compilation because we might be in a speculative context (local function parameter), - // in which case the declaring compilation is the wrong one. - protected ConstantValue MakeDefaultExpression(DiagnosticBag diagnostics, Binder binder) + private Binder GetBinder(SyntaxNode syntax) + { + var binder = ParameterBinderOpt; + + // If binder is null, then get it from the compilation. Otherwise use the provided binder. + // Don't always get it from the compilation because we might be in a speculative context (local function parameter), + // in which case the declaring compilation is the wrong one. + if (binder == null) + { + var compilation = this.DeclaringCompilation; + var binderFactory = compilation.GetBinderFactory(syntax.SyntaxTree); + binder = binderFactory.GetBinder(syntax); + } + Debug.Assert(binder.GetBinder(syntax) == null); + return binder; + } + + private void NullableAnalyzeParameterDefaultValueFromAttributes() + { + if (!NullableWalker.NeedsAnalysis(DeclaringCompilation)) + { + return; + } + + var defaultValue = DefaultValueFromAttributes; + if (defaultValue == null || defaultValue.IsBad) + { + return; + } + + var parameterSyntax = this.CSharpSyntaxNode; + if (parameterSyntax == null) + { + // If there is no syntax at all for the parameter, it means we are in a situation like + // a property setter whose 'value' parameter has a default value from attributes. + // There isn't a sensible use for this in the language, so we just bail in such scenarios. + return; + } + + var binder = GetBinder(parameterSyntax); + + // Nullable warnings *within* the attribute argument (such as a W-warning for `(string)null`) + // are reported when we nullable-analyze attribute arguments separately from here. + // However, this analysis of the constant value's compatibility with the parameter + // needs to wait until the attributes are populated on the parameter symbol. + var parameterEqualsValue = new BoundParameterEqualsValue( + parameterSyntax, + this, + ImmutableArray.Empty, + // note that if the parameter type conflicts with the default value from attributes, + // we will just get a bad constant value above and return early. + new BoundLiteral(parameterSyntax, defaultValue, Type)); + + var diagnostics = DiagnosticBag.GetInstance(); + NullableWalker.AnalyzeIfNeeded(binder, parameterEqualsValue, diagnostics); + AddDeclarationDiagnostics(diagnostics); + diagnostics.Free(); + } + + // This method *must not* depend on attributes on the parameter symbol. + // Otherwise we will have cycles when binding usage of attributes whose constructors have optional parameters + private ConstantValue MakeDefaultExpression(DiagnosticBag diagnostics, out Binder? binder, out BoundParameterEqualsValue? parameterEqualsValue) { + binder = null; + parameterEqualsValue = null; + var parameterSyntax = this.CSharpSyntaxNode; if (parameterSyntax == null) { @@ -240,27 +307,18 @@ protected ConstantValue MakeDefaultExpression(DiagnosticBag diagnostics, Binder return ConstantValue.NotAvailable; } - if (binder == null) - { - var syntaxTree = _syntaxRef.SyntaxTree; - var compilation = this.DeclaringCompilation; - var binderFactory = compilation.GetBinderFactory(syntaxTree); - binder = binderFactory.GetBinder(defaultSyntax); - } - - Debug.Assert(binder.GetBinder(defaultSyntax) == null); - + binder = GetBinder(defaultSyntax); Binder binderForDefault = binder.CreateBinderForParameterDefaultValue(this, defaultSyntax); Debug.Assert(binderForDefault.InParameterDefaultValue); Debug.Assert(binderForDefault.ContainingMemberOrLambda == ContainingSymbol); - BoundExpression valueBeforeConversion; - BoundExpression convertedExpression = binderForDefault.BindParameterDefaultValue(defaultSyntax, this, diagnostics, out valueBeforeConversion).Value; + parameterEqualsValue = binderForDefault.BindParameterDefaultValue(defaultSyntax, this, diagnostics, out var valueBeforeConversion); if (valueBeforeConversion.HasErrors) { return ConstantValue.Bad; } + BoundExpression convertedExpression = parameterEqualsValue.Value; bool hasErrors = ParameterHelpers.ReportDefaultParameterErrors(binder, ContainingSymbol, parameterSyntax, this, valueBeforeConversion, convertedExpression, diagnostics); if (hasErrors) { @@ -282,10 +340,11 @@ protected ConstantValue MakeDefaultExpression(DiagnosticBag diagnostics, Binder // represent default(struct) by a Null constant: var value = convertedExpression.ConstantValue ?? ConstantValue.Null; - VerifyParamDefaultValueMatchesAttributeIfAny(value, defaultSyntax.Value, diagnostics); return value; } +#nullable disable + public override string MetadataName { get @@ -470,6 +529,7 @@ internal sealed override CustomAttributesBag GetAttributesB if (bagCreatedOnThisThread) { + NullableAnalyzeParameterDefaultValueFromAttributes(); state.NotePartComplete(CompletionPart.Attributes); } } @@ -702,7 +762,7 @@ private void DecodeDefaultParameterValueAttribute(AttributeDescription descripti /// (DefaultParameterValueAttribute, DateTimeConstantAttribute or DecimalConstantAttribute). /// If not, report ERR_ParamDefaultValueDiffersFromAttribute. /// - private void VerifyParamDefaultValueMatchesAttributeIfAny(ConstantValue value, CSharpSyntaxNode syntax, DiagnosticBag diagnostics) + private void VerifyParamDefaultValueMatchesAttributeIfAny(ConstantValue value, SyntaxNode syntax, DiagnosticBag diagnostics) { var data = GetEarlyDecodedWellKnownAttributeData(); if (data != null) @@ -1093,10 +1153,9 @@ internal sealed override MarshalPseudoCustomAttributeData MarshallingInformation internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { - base.ForceComplete(locationOpt, cancellationToken); - - // Force binding of default value. - var unused = this.ExplicitDefaultConstantValue; + _ = this.GetAttributes(); + _ = this.ExplicitDefaultConstantValue; + state.SpinWaitComplete(CompletionPart.ComplexParameterSymbolAll, cancellationToken); } } @@ -1113,10 +1172,9 @@ internal SourceComplexParameterSymbolWithCustomModifiersPrecedingByRef( string name, ImmutableArray locations, SyntaxReference syntaxRef, - ConstantValue defaultSyntaxValue, bool isParams, bool isExtensionMethodThis) - : base(owner, ordinal, parameterType, refKind, name, locations, syntaxRef, defaultSyntaxValue, isParams, isExtensionMethodThis) + : base(owner, ordinal, parameterType, refKind, name, locations, syntaxRef, isParams, isExtensionMethodThis) { Debug.Assert(!refCustomModifiers.IsEmpty); diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceConstructorSymbolBase.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceConstructorSymbolBase.cs index 197607346231a..4549b43538b32 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceConstructorSymbolBase.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceConstructorSymbolBase.cs @@ -138,8 +138,11 @@ public sealed override ImmutableArray TypeParameters get { return ImmutableArray.Empty; } } - public sealed override ImmutableArray GetTypeParameterConstraintClauses(bool canIgnoreNullableContext) - => ImmutableArray.Empty; + public sealed override ImmutableArray> GetTypeParameterConstraintTypes() + => ImmutableArray>.Empty; + + public sealed override ImmutableArray GetTypeParameterConstraintKinds() + => ImmutableArray.Empty; public override RefKind RefKind { diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceDelegateMethodSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceDelegateMethodSymbol.cs index 93915560f3af9..029f53d877cc8 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceDelegateMethodSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceDelegateMethodSymbol.cs @@ -138,8 +138,11 @@ public override ImmutableArray TypeParameters } } - public override ImmutableArray GetTypeParameterConstraintClauses(bool canIgnoreNullableContext) - => ImmutableArray.Empty; + public override ImmutableArray> GetTypeParameterConstraintTypes() + => ImmutableArray>.Empty; + + public override ImmutableArray GetTypeParameterConstraintKinds() + => ImmutableArray.Empty; public sealed override TypeWithAnnotations ReturnTypeWithAnnotations { diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceDestructorSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceDestructorSymbol.cs index 80d5677a29fcf..4b1a2100f3299 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceDestructorSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceDestructorSymbol.cs @@ -98,8 +98,11 @@ public override ImmutableArray TypeParameters get { return ImmutableArray.Empty; } } - public override ImmutableArray GetTypeParameterConstraintClauses(bool canIgnoreNullableContext) - => ImmutableArray.Empty; + public override ImmutableArray> GetTypeParameterConstraintTypes() + => ImmutableArray>.Empty; + + public override ImmutableArray GetTypeParameterConstraintKinds() + => ImmutableArray.Empty; public override RefKind RefKind { diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceEventAccessorSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceEventAccessorSymbol.cs index 79624b769ff14..fbfccf3e3873a 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceEventAccessorSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceEventAccessorSymbol.cs @@ -208,8 +208,11 @@ public sealed override ImmutableArray TypeParameters get { return ImmutableArray.Empty; } } - public sealed override ImmutableArray GetTypeParameterConstraintClauses(bool canIgnoreNullableContext) - => ImmutableArray.Empty; + public sealed override ImmutableArray> GetTypeParameterConstraintTypes() + => ImmutableArray>.Empty; + + public sealed override ImmutableArray GetTypeParameterConstraintKinds() + => ImmutableArray.Empty; internal Location Location { diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol.cs index ef90e51f51770..9d22f94f23437 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol.cs @@ -3034,6 +3034,14 @@ private void AddSynthesizedRecordMembersIfNecessary(MembersAndInitializersBuilde var members = ArrayBuilder.GetInstance(builder.NonTypeNonIndexerMembers.Count + 1); foreach (var member in builder.NonTypeNonIndexerMembers) { + switch (member) + { + case FieldSymbol: + case EventSymbol: + case MethodSymbol { MethodKind: not (MethodKind.Ordinary or MethodKind.Constructor) }: + continue; + } + if (!memberSignatures.ContainsKey(member)) { memberSignatures.Add(member, member); @@ -3291,7 +3299,7 @@ ImmutableArray addProperties(ImmutableArray rec } if (existingMember is null) { - addProperty(new SynthesizedRecordPropertySymbol(this, syntax, param, isOverride: false, diagnostics)); + addProperty(new SynthesizedRecordPropertySymbol(this, syntax, param, isOverride: false)); } else if (existingMember is PropertySymbol { IsStatic: false, GetMethod: { } } prop && prop.TypeWithAnnotations.Equals(param.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions)) @@ -3299,7 +3307,7 @@ ImmutableArray addProperties(ImmutableArray rec // There already exists a member corresponding to the candidate synthesized property. if (isInherited && prop.IsAbstract) { - addProperty(new SynthesizedRecordPropertySymbol(this, syntax, param, isOverride: true, diagnostics)); + addProperty(new SynthesizedRecordPropertySymbol(this, syntax, param, isOverride: true)); } else { @@ -3320,6 +3328,8 @@ void addProperty(SynthesizedRecordPropertySymbol property) { existingOrAddedMembers.Add(property); members.Add(property); + Debug.Assert(property.GetMethod is object); + Debug.Assert(property.SetMethod is object); members.Add(property.GetMethod); members.Add(property.SetMethod); members.Add(property.BackingField); @@ -3393,7 +3403,7 @@ PropertySymbol addEqualityContract() if (!memberSignatures.TryGetValue(targetProperty, out Symbol? existingEqualityContractProperty)) { - equalityContract = new SynthesizedRecordEqualityContractProperty(this, diagnostics); + equalityContract = new SynthesizedRecordEqualityContractProperty(this); members.Add(equalityContract); members.Add(equalityContract.GetMethod); } diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceMethodSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceMethodSymbol.cs index 75efa7a39e371..894522cc7704e 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceMethodSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceMethodSymbol.cs @@ -17,10 +17,15 @@ internal abstract class SourceMethodSymbol : MethodSymbol { /// /// If there are no constraints, returns an empty immutable array. Otherwise, returns an immutable - /// array of clauses, indexed by the constrained type parameter in . - /// If a type parameter does not have constraints, the corresponding entry in the array is null. + /// array of types, indexed by the constrained type parameter in . /// - public abstract ImmutableArray GetTypeParameterConstraintClauses(bool canIgnoreNullableContext); + public abstract ImmutableArray> GetTypeParameterConstraintTypes(); + + /// + /// If there are no constraints, returns an empty immutable array. Otherwise, returns an immutable + /// array of kinds, indexed by the constrained type parameter in . + /// + public abstract ImmutableArray GetTypeParameterConstraintKinds(); protected static void ReportBadRefToken(TypeSyntax returnTypeSyntax, DiagnosticBag diagnostics) { @@ -39,7 +44,7 @@ protected bool AreContainingSymbolLocalsZeroed { return method.AreLocalsZeroed; } - else if (ContainingType is SourceNamedTypeSymbol type) + else if (ContainingType is SourceMemberContainerTypeSymbol type) { return type.AreLocalsZeroed; } diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceNamedTypeSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceNamedTypeSymbol.cs index 793b0c9fcb0e9..998eb6a00eb2c 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceNamedTypeSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceNamedTypeSymbol.cs @@ -25,10 +25,16 @@ internal sealed partial class SourceNamedTypeSymbol : SourceMemberContainerTypeS private ImmutableArray _lazyTypeParameters; /// - /// A collection of type parameter constraints, populated when - /// constraints for the first type parameter are requested. + /// A collection of type parameter constraint types, populated when + /// constraint types for the first type parameter are requested. /// - private ImmutableArray _lazyTypeParameterConstraints; + private ImmutableArray> _lazyTypeParameterConstraintTypes; + + /// + /// A collection of type parameter constraint kinds, populated when + /// constraint kinds for the first type parameter are requested. + /// + private ImmutableArray _lazyTypeParameterConstraintKinds; private CustomAttributesBag _lazyCustomAttributesBag; @@ -251,27 +257,55 @@ private ImmutableArray MakeTypeParameters(DiagnosticBag dia } /// - /// Returns the constraint clause for the given type parameter. + /// Returns the constraint types for the given type parameter. /// - internal TypeParameterConstraintClause GetTypeParameterConstraintClause(bool canIgnoreNullableContext, int ordinal) + internal ImmutableArray GetTypeParameterConstraintTypes(int ordinal) { - var clauses = _lazyTypeParameterConstraints; - if (!clauses.HasValue(canIgnoreNullableContext)) + var constraintTypes = GetTypeParameterConstraintTypes(); + return (constraintTypes.Length > 0) ? constraintTypes[ordinal] : ImmutableArray.Empty; + } + + private ImmutableArray> GetTypeParameterConstraintTypes() + { + var constraintTypes = _lazyTypeParameterConstraintTypes; + if (constraintTypes.IsDefault) { + GetTypeParameterConstraintKinds(); + var diagnostics = DiagnosticBag.GetInstance(); - if (TypeParameterConstraintClauseExtensions.InterlockedUpdate(ref _lazyTypeParameterConstraints, MakeTypeParameterConstraints(canIgnoreNullableContext, diagnostics)) && - _lazyTypeParameterConstraints.HasValue(canIgnoreNullableContext: false)) + if (ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameterConstraintTypes, MakeTypeParameterConstraintTypes(diagnostics))) { this.AddDeclarationDiagnostics(diagnostics); } diagnostics.Free(); - clauses = _lazyTypeParameterConstraints; + constraintTypes = _lazyTypeParameterConstraintTypes; + } + + return constraintTypes; + } + + /// + /// Returns the constraint kind for the given type parameter. + /// + internal TypeParameterConstraintKind GetTypeParameterConstraintKind(int ordinal) + { + var constraintKinds = GetTypeParameterConstraintKinds(); + return (constraintKinds.Length > 0) ? constraintKinds[ordinal] : TypeParameterConstraintKind.None; + } + + private ImmutableArray GetTypeParameterConstraintKinds() + { + var constraintKinds = _lazyTypeParameterConstraintKinds; + if (constraintKinds.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameterConstraintKinds, MakeTypeParameterConstraintKinds()); + constraintKinds = _lazyTypeParameterConstraintKinds; } - return (clauses.Length > 0) ? clauses[ordinal] : TypeParameterConstraintClause.Empty; + return constraintKinds; } - private ImmutableArray MakeTypeParameterConstraints(bool canIgnoreNullableContext, DiagnosticBag diagnostics) + private ImmutableArray> MakeTypeParameterConstraintTypes(DiagnosticBag diagnostics) { var typeParameters = this.TypeParameters; var results = ImmutableArray.Empty; @@ -279,18 +313,88 @@ private ImmutableArray MakeTypeParameterConstrain int arity = typeParameters.Length; if (arity > 0) { - bool skipPartialDeclarationsWithoutConstraintClauses = false; + bool skipPartialDeclarationsWithoutConstraintClauses = SkipPartialDeclarationsWithoutConstraintClauses(); + ArrayBuilder> otherPartialClauses = null; foreach (var decl in declaration.Declarations) { - if (GetConstraintClauses((CSharpSyntaxNode)decl.SyntaxReference.GetSyntax(), out _).Count != 0) + var syntaxRef = decl.SyntaxReference; + var constraintClauses = GetConstraintClauses((CSharpSyntaxNode)syntaxRef.GetSyntax(), out TypeParameterListSyntax typeParameterList); + + if (skipPartialDeclarationsWithoutConstraintClauses && constraintClauses.Count == 0) { - skipPartialDeclarationsWithoutConstraintClauses = true; - break; + continue; + } + + var binderFactory = this.DeclaringCompilation.GetBinderFactory(syntaxRef.SyntaxTree); + Binder binder; + ImmutableArray constraints; + + if (constraintClauses.Count == 0) + { + binder = binderFactory.GetBinder(typeParameterList.Parameters[0]); + + constraints = binder.GetDefaultTypeParameterConstraintClauses(typeParameterList); + } + else + { + binder = binderFactory.GetBinder(constraintClauses[0]); + + // Wrap binder from factory in a generic constraints specific binder + // to avoid checking constraints when binding type names. + Debug.Assert(!binder.Flags.Includes(BinderFlags.GenericConstraintsClause)); + binder = binder.WithContainingMemberOrLambda(this).WithAdditionalFlags(BinderFlags.GenericConstraintsClause | BinderFlags.SuppressConstraintChecks); + + constraints = binder.BindTypeParameterConstraintClauses(this, typeParameters, typeParameterList, constraintClauses, diagnostics, performOnlyCycleSafeValidation: false); + } + + Debug.Assert(constraints.Length == arity); + + if (results.Length == 0) + { + results = constraints; + } + else + { + (otherPartialClauses ??= ArrayBuilder>.GetInstance()).Add(constraints); } } - IReadOnlyDictionary isValueTypeOverride = null; + results = MergeConstraintTypesForPartialDeclarations(results, otherPartialClauses, diagnostics); + + if (results.All(clause => clause.ConstraintTypes.IsEmpty)) + { + results = ImmutableArray.Empty; + } + + otherPartialClauses?.Free(); + } + + return results.SelectAsArray(clause => clause.ConstraintTypes); + } + + private bool SkipPartialDeclarationsWithoutConstraintClauses() + { + foreach (var decl in declaration.Declarations) + { + if (GetConstraintClauses((CSharpSyntaxNode)decl.SyntaxReference.GetSyntax(), out _).Count != 0) + { + return true; + } + } + + return false; + } + + private ImmutableArray MakeTypeParameterConstraintKinds() + { + var typeParameters = this.TypeParameters; + var results = ImmutableArray.Empty; + + int arity = typeParameters.Length; + if (arity > 0) + { + bool skipPartialDeclarationsWithoutConstraintClauses = SkipPartialDeclarationsWithoutConstraintClauses(); ArrayBuilder> otherPartialClauses = null; foreach (var decl in declaration.Declarations) @@ -310,7 +414,6 @@ private ImmutableArray MakeTypeParameterConstrain if (constraintClauses.Count == 0) { binder = binderFactory.GetBinder(typeParameterList.Parameters[0]); - constraints = binder.GetDefaultTypeParameterConstraintClauses(typeParameterList); } else @@ -319,11 +422,13 @@ private ImmutableArray MakeTypeParameterConstrain // Wrap binder from factory in a generic constraints specific binder // to avoid checking constraints when binding type names. + // Also, suppress type argument binding in constraint types, this helps to avoid cycles while we figure out constraint kinds. Debug.Assert(!binder.Flags.Includes(BinderFlags.GenericConstraintsClause)); - binder = binder.WithContainingMemberOrLambda(this).WithAdditionalFlags( - BinderFlags.GenericConstraintsClause | BinderFlags.SuppressConstraintChecks | (canIgnoreNullableContext ? BinderFlags.IgnoreNullableContext : 0)); + binder = binder.WithContainingMemberOrLambda(this).WithAdditionalFlags(BinderFlags.GenericConstraintsClause | BinderFlags.SuppressConstraintChecks | BinderFlags.SuppressTypeArgumentBinding); - constraints = binder.BindTypeParameterConstraintClauses(this, typeParameters, typeParameterList, constraintClauses, canIgnoreNullableContext, ref isValueTypeOverride, diagnostics); + var discarded = DiagnosticBag.GetInstance(); // We will recompute this diagnostics more accurately later, when binding without BinderFlags.SuppressTypeArgumentBinding + constraints = binder.BindTypeParameterConstraintClauses(this, typeParameters, typeParameterList, constraintClauses, discarded, performOnlyCycleSafeValidation: true); + discarded.Free(); } Debug.Assert(constraints.Length == arity); @@ -338,9 +443,10 @@ private ImmutableArray MakeTypeParameterConstrain } } - results = MergeConstraintsForPartialDeclarations(results, otherPartialClauses, isValueTypeOverride, diagnostics); + results = MergeConstraintKindsForPartialDeclarations(results, otherPartialClauses); + results = ConstraintsHelper.AdjustConstraintKindsBasedOnConstraintTypes(this, typeParameters, results); - if (results.ContainsOnlyEmptyConstraintClauses()) + if (results.All(clause => clause.Constraints == TypeParameterConstraintKind.None)) { results = ImmutableArray.Empty; } @@ -348,7 +454,7 @@ private ImmutableArray MakeTypeParameterConstrain otherPartialClauses?.Free(); } - return results; + return results.SelectAsArray(clause => clause.Constraints); } private static SyntaxList GetConstraintClauses(CSharpSyntaxNode node, out TypeParameterListSyntax typeParameterList) @@ -374,10 +480,9 @@ private static SyntaxList GetConstraintClau /// /// Note, only nullability aspects are merged if possible, other mismatches are treated as failures. /// - private ImmutableArray MergeConstraintsForPartialDeclarations(ImmutableArray constraintClauses, - ArrayBuilder> otherPartialClauses, - IReadOnlyDictionary isValueTypeOverride, - DiagnosticBag diagnostics) + private ImmutableArray MergeConstraintTypesForPartialDeclarations(ImmutableArray constraintClauses, + ArrayBuilder> otherPartialClauses, + DiagnosticBag diagnostics) { if (otherPartialClauses == null) { @@ -394,17 +499,16 @@ private ImmutableArray MergeConstraintsForPartial { var constraint = constraintClauses[i]; - TypeParameterConstraintKind mergedKind = constraint.Constraints; ImmutableArray originalConstraintTypes = constraint.ConstraintTypes; ArrayBuilder mergedConstraintTypes = null; SmallDictionary originalConstraintTypesMap = null; // Constraints defined on multiple partial declarations. // Report any mismatched constraints. - bool report = false; + bool report = (GetTypeParameterConstraintKind(i) & TypeParameterConstraintKind.PartialMismatch) != 0; foreach (ImmutableArray otherPartialConstraints in otherPartialClauses) { - if (!mergeConstraints(ref mergedKind, originalConstraintTypes, ref originalConstraintTypesMap, ref mergedConstraintTypes, otherPartialConstraints[i], isValueTypeOverride)) + if (!mergeConstraints(originalConstraintTypes, ref originalConstraintTypesMap, ref mergedConstraintTypes, otherPartialConstraints[i])) { report = true; } @@ -416,23 +520,14 @@ private ImmutableArray MergeConstraintsForPartial diagnostics.Add(ErrorCode.ERR_PartialWrongConstraints, Locations[0], this, typeParameters[i]); } - if (constraint.Constraints != mergedKind || mergedConstraintTypes != null) + if (mergedConstraintTypes != null) { - Debug.Assert((constraint.Constraints & (TypeParameterConstraintKind.AllNonNullableKinds | TypeParameterConstraintKind.NotNull)) == - (mergedKind & (TypeParameterConstraintKind.AllNonNullableKinds | TypeParameterConstraintKind.NotNull))); - Debug.Assert((mergedKind & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) == 0 || - (constraint.Constraints & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) != 0); - Debug.Assert((constraint.Constraints & TypeParameterConstraintKind.AllReferenceTypeKinds) == (mergedKind & TypeParameterConstraintKind.AllReferenceTypeKinds) || - (constraint.Constraints & TypeParameterConstraintKind.AllReferenceTypeKinds) == TypeParameterConstraintKind.ReferenceType); #if DEBUG - if (mergedConstraintTypes != null) - { - Debug.Assert(originalConstraintTypes.Length == mergedConstraintTypes.Count); + Debug.Assert(originalConstraintTypes.Length == mergedConstraintTypes.Count); - for (int j = 0; j < originalConstraintTypes.Length; j++) - { - Debug.Assert(originalConstraintTypes[j].Equals(mergedConstraintTypes[j], TypeCompareKind.ObliviousNullableModifierMatchesAny, isValueTypeOverride)); - } + for (int j = 0; j < originalConstraintTypes.Length; j++) + { + Debug.Assert(originalConstraintTypes[j].Equals(mergedConstraintTypes[j], TypeCompareKind.ObliviousNullableModifierMatchesAny)); } #endif if (builder == null) @@ -441,8 +536,8 @@ private ImmutableArray MergeConstraintsForPartial builder.AddRange(constraintClauses); } - builder[i] = TypeParameterConstraintClause.Create(mergedKind, - mergedConstraintTypes?.ToImmutableAndFree() ?? originalConstraintTypes, ignoresNullableContext: constraint.IgnoresNullableContext); + builder[i] = TypeParameterConstraintClause.Create(constraint.Constraints, + mergedConstraintTypes?.ToImmutableAndFree() ?? originalConstraintTypes); } } @@ -453,50 +548,16 @@ private ImmutableArray MergeConstraintsForPartial return constraintClauses; - static bool mergeConstraints(ref TypeParameterConstraintKind mergedKind, ImmutableArray originalConstraintTypes, + static bool mergeConstraints(ImmutableArray originalConstraintTypes, ref SmallDictionary originalConstraintTypesMap, ref ArrayBuilder mergedConstraintTypes, - TypeParameterConstraintClause clause, IReadOnlyDictionary isValueTypeOverride) + TypeParameterConstraintClause clause) { bool result = true; - if ((mergedKind & (TypeParameterConstraintKind.AllNonNullableKinds | TypeParameterConstraintKind.NotNull)) != (clause.Constraints & (TypeParameterConstraintKind.AllNonNullableKinds | TypeParameterConstraintKind.NotNull))) - { - result = false; - } - - if ((mergedKind & TypeParameterConstraintKind.ReferenceType) != 0 && (clause.Constraints & TypeParameterConstraintKind.ReferenceType) != 0) - { - // Try merging nullability of a 'class' constraint - TypeParameterConstraintKind clause1Constraints = mergedKind & TypeParameterConstraintKind.AllReferenceTypeKinds; - TypeParameterConstraintKind clause2Constraints = clause.Constraints & TypeParameterConstraintKind.AllReferenceTypeKinds; - if (clause1Constraints != clause2Constraints) - { - if (clause1Constraints == TypeParameterConstraintKind.ReferenceType) // Oblivious - { - // Take nullability from clause2 - mergedKind = (mergedKind & (~TypeParameterConstraintKind.AllReferenceTypeKinds)) | clause2Constraints; - } - else if (clause2Constraints != TypeParameterConstraintKind.ReferenceType) - { - // Neither nullability is oblivious and they do not match. Cannot merge. - result = false; - } - } - } - if (originalConstraintTypes.Length == 0) { if (clause.ConstraintTypes.Length == 0) { - // Try merging nullability of implied 'object' constraint - if (((mergedKind | clause.Constraints) & ~(TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType | TypeParameterConstraintKind.Constructor)) == 0 && - (mergedKind & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) != 0 && // 'object~' - (clause.Constraints & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) == 0) // 'object?' - { - // Merged value is 'object?' - mergedKind &= ~TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType; - } - return result; } @@ -508,7 +569,7 @@ static bool mergeConstraints(ref TypeParameterConstraintKind mergedKind, Immutab } originalConstraintTypesMap ??= toDictionary(originalConstraintTypes, - new TypeWithAnnotations.EqualsComparer(TypeCompareKind.IgnoreNullableModifiersForReferenceTypes, isValueTypeOverride)); + TypeWithAnnotations.EqualsComparer.IgnoreNullableModifiersForReferenceTypesComparer); SmallDictionary clauseConstraintTypesMap = toDictionary(clause.ConstraintTypes, originalConstraintTypesMap.Comparer); foreach (int index1 in originalConstraintTypesMap.Values) @@ -525,14 +586,14 @@ static bool mergeConstraints(ref TypeParameterConstraintKind mergedKind, Immutab TypeWithAnnotations constraintType2 = clause.ConstraintTypes[index2]; - if (!constraintType1.Equals(constraintType2, TypeCompareKind.ObliviousNullableModifierMatchesAny, isValueTypeOverride)) + if (!constraintType1.Equals(constraintType2, TypeCompareKind.ObliviousNullableModifierMatchesAny)) { // Nullability mismatch that doesn't involve oblivious result = false; continue; } - if (!constraintType1.Equals(constraintType2, TypeCompareKind.ConsiderEverything, isValueTypeOverride)) + if (!constraintType1.Equals(constraintType2, TypeCompareKind.ConsiderEverything)) { // Mismatch with oblivious, merge if (mergedConstraintTypes == null) @@ -570,6 +631,102 @@ static SmallDictionary toDictionary(ImmutableArray + /// Note, only nullability aspects are merged if possible, other mismatches are treated as failures. + /// + private ImmutableArray MergeConstraintKindsForPartialDeclarations(ImmutableArray constraintClauses, + ArrayBuilder> otherPartialClauses) + { + if (otherPartialClauses == null) + { + return constraintClauses; + } + + ArrayBuilder builder = null; + var typeParameters = TypeParameters; + int arity = typeParameters.Length; + + Debug.Assert(constraintClauses.Length == arity); + + for (int i = 0; i < arity; i++) + { + var constraint = constraintClauses[i]; + + TypeParameterConstraintKind mergedKind = constraint.Constraints; + ImmutableArray originalConstraintTypes = constraint.ConstraintTypes; + + foreach (ImmutableArray otherPartialConstraints in otherPartialClauses) + { + mergeConstraints(ref mergedKind, originalConstraintTypes, otherPartialConstraints[i]); + } + + if (constraint.Constraints != mergedKind) + { + Debug.Assert((constraint.Constraints & (TypeParameterConstraintKind.AllNonNullableKinds | TypeParameterConstraintKind.NotNull)) == + (mergedKind & (TypeParameterConstraintKind.AllNonNullableKinds | TypeParameterConstraintKind.NotNull))); + Debug.Assert((mergedKind & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) == 0 || + (constraint.Constraints & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) != 0); + Debug.Assert((constraint.Constraints & TypeParameterConstraintKind.AllReferenceTypeKinds) == (mergedKind & TypeParameterConstraintKind.AllReferenceTypeKinds) || + (constraint.Constraints & TypeParameterConstraintKind.AllReferenceTypeKinds) == TypeParameterConstraintKind.ReferenceType); + + if (builder == null) + { + builder = ArrayBuilder.GetInstance(constraintClauses.Length); + builder.AddRange(constraintClauses); + } + + builder[i] = TypeParameterConstraintClause.Create(mergedKind, originalConstraintTypes); + } + } + + if (builder != null) + { + constraintClauses = builder.ToImmutableAndFree(); + } + + return constraintClauses; + + static void mergeConstraints(ref TypeParameterConstraintKind mergedKind, ImmutableArray originalConstraintTypes, TypeParameterConstraintClause clause) + { + if ((mergedKind & (TypeParameterConstraintKind.AllNonNullableKinds | TypeParameterConstraintKind.NotNull)) != (clause.Constraints & (TypeParameterConstraintKind.AllNonNullableKinds | TypeParameterConstraintKind.NotNull))) + { + mergedKind |= TypeParameterConstraintKind.PartialMismatch; + } + + if ((mergedKind & TypeParameterConstraintKind.ReferenceType) != 0 && (clause.Constraints & TypeParameterConstraintKind.ReferenceType) != 0) + { + // Try merging nullability of a 'class' constraint + TypeParameterConstraintKind clause1Constraints = mergedKind & TypeParameterConstraintKind.AllReferenceTypeKinds; + TypeParameterConstraintKind clause2Constraints = clause.Constraints & TypeParameterConstraintKind.AllReferenceTypeKinds; + if (clause1Constraints != clause2Constraints) + { + if (clause1Constraints == TypeParameterConstraintKind.ReferenceType) // Oblivious + { + // Take nullability from clause2 + mergedKind = (mergedKind & (~TypeParameterConstraintKind.AllReferenceTypeKinds)) | clause2Constraints; + } + else if (clause2Constraints != TypeParameterConstraintKind.ReferenceType) + { + // Neither nullability is oblivious and they do not match. Cannot merge. + mergedKind |= TypeParameterConstraintKind.PartialMismatch; + } + } + } + + if (originalConstraintTypes.Length == 0 && clause.ConstraintTypes.Length == 0) + { + // Try merging nullability of implied 'object' constraint + if (((mergedKind | clause.Constraints) & ~(TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType | TypeParameterConstraintKind.Constructor)) == 0 && + (mergedKind & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) != 0 && // 'object~' + (clause.Constraints & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) == 0) // 'object?' + { + // Merged value is 'object?' + mergedKind &= ~TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType; + } + } + } + } + internal sealed override ImmutableArray TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get @@ -1389,11 +1546,11 @@ internal override NamedTypeSymbol AsNativeInteger() internal override NamedTypeSymbol NativeIntegerUnderlyingType => null; - internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison, IReadOnlyDictionary isValueTypeOverrideOpt = null) + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { return t2 is NativeIntegerTypeSymbol nativeInteger ? - nativeInteger.Equals(this, comparison, isValueTypeOverrideOpt) : - base.Equals(t2, comparison, isValueTypeOverrideOpt); + nativeInteger.Equals(this, comparison) : + base.Equals(t2, comparison); } } } diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceOrdinaryMethodSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceOrdinaryMethodSymbol.cs index 4fc98acf1df89..a66a05a6382d3 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceOrdinaryMethodSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceOrdinaryMethodSymbol.cs @@ -8,6 +8,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; +using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; @@ -25,11 +26,18 @@ internal sealed class SourceOrdinaryMethodSymbol : SourceOrdinaryMethodSymbolBas private bool _lazyIsVararg; /// - /// A collection of type parameter constraints, populated when - /// constraints for the first type parameter is requested. + /// A collection of type parameter constraint types, populated when + /// constraint types for the first type parameter is requested. /// Initialized in two steps. Hold a copy if accessing during initialization. /// - private ImmutableArray _lazyTypeParameterConstraints; + private ImmutableArray> _lazyTypeParameterConstraintTypes; + + /// + /// A collection of type parameter constraint kinds, populated when + /// constraint kinds for the first type parameter is requested. + /// Initialized in two steps. Hold a copy if accessing during initialization. + /// + private ImmutableArray _lazyTypeParameterConstraintKinds; /// /// If this symbol represents a partial method definition or implementation part, its other part (if any). @@ -163,12 +171,10 @@ protected override (TypeWithAnnotations ReturnType, ImmutableArray isValueTypeOverride = null; declaredConstraints = signatureBinder.WithAdditionalFlags(BinderFlags.GenericConstraintsClause | BinderFlags.SuppressConstraintChecks). BindTypeParameterConstraintClauses(this, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses, - canIgnoreNullableContext: false, - ref isValueTypeOverride, - diagnostics, isForOverride: true); + diagnostics, performOnlyCycleSafeValidation: false, isForOverride: true); + Debug.Assert(declaredConstraints.All(clause => clause.ConstraintTypes.IsEmpty)); } // Force resolution of nullable type parameter used in the signature of an override or explicit interface implementation @@ -283,32 +289,53 @@ protected override void CompleteAsyncMethodChecksBetweenStartAndFinish() } } - public override ImmutableArray GetTypeParameterConstraintClauses(bool canIgnoreNullableContext) + public override ImmutableArray> GetTypeParameterConstraintTypes() { - if (!_lazyTypeParameterConstraints.HasValue(canIgnoreNullableContext)) + if (_lazyTypeParameterConstraintTypes.IsDefault) { + GetTypeParameterConstraintKinds(); + var diagnostics = DiagnosticBag.GetInstance(); var syntax = GetSyntax(); var withTypeParametersBinder = this.DeclaringCompilation .GetBinderFactory(syntax.SyntaxTree) .GetBinder(syntax.ReturnType, syntax, this); - var constraints = this.MakeTypeParameterConstraints( + var constraints = this.MakeTypeParameterConstraintTypes( withTypeParametersBinder, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses, - canIgnoreNullableContext, diagnostics); - if (TypeParameterConstraintClauseExtensions.InterlockedUpdate(ref _lazyTypeParameterConstraints, constraints) && - _lazyTypeParameterConstraints.HasValue(canIgnoreNullableContext: false)) + if (ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameterConstraintTypes, constraints)) { this.AddDeclarationDiagnostics(diagnostics); } diagnostics.Free(); } - return _lazyTypeParameterConstraints; + return _lazyTypeParameterConstraintTypes; + } + + public override ImmutableArray GetTypeParameterConstraintKinds() + { + if (_lazyTypeParameterConstraintKinds.IsDefault) + { + var syntax = GetSyntax(); + var withTypeParametersBinder = + this.DeclaringCompilation + .GetBinderFactory(syntax.SyntaxTree) + .GetBinder(syntax.ReturnType, syntax, this); + var constraints = this.MakeTypeParameterConstraintKinds( + withTypeParametersBinder, + TypeParameters, + syntax.TypeParameterList, + syntax.ConstraintClauses); + + ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameterConstraintKinds, constraints); + } + + return _lazyTypeParameterConstraintKinds; } public override bool IsVararg diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceParameterSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceParameterSymbol.cs index 14ecb74fd4e17..d4b0df693e299 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceParameterSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceParameterSymbol.cs @@ -66,7 +66,6 @@ public static SourceParameterSymbol Create( name, locations, syntax.GetReference(), - ConstantValue.Unset, isParams, isExtensionMethodThis); } @@ -88,7 +87,6 @@ public static SourceParameterSymbol Create( name, locations, syntax.GetReference(), - ConstantValue.Unset, isParams, isExtensionMethodThis); } @@ -136,7 +134,6 @@ internal SourceParameterSymbol WithCustomModifiersAndParamsCore(TypeSymbol newTy _name, _locations, this.SyntaxReference, - this.ExplicitDefaultConstantValue, newIsParams, this.IsExtensionMethodThis); } @@ -153,7 +150,6 @@ internal SourceParameterSymbol WithCustomModifiersAndParamsCore(TypeSymbol newTy _name, _locations, this.SyntaxReference, - this.ExplicitDefaultConstantValue, newIsParams, this.IsExtensionMethodThis); } diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertyAccessorSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertyAccessorSymbol.cs index a9d6380c959ca..6eac1408f1848 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertyAccessorSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertyAccessorSymbol.cs @@ -452,8 +452,11 @@ public sealed override ImmutableArray TypeParameters get { return ImmutableArray.Empty; } } - public sealed override ImmutableArray GetTypeParameterConstraintClauses(bool canIgnoreNullableContext) - => ImmutableArray.Empty; + public sealed override ImmutableArray> GetTypeParameterConstraintTypes() + => ImmutableArray>.Empty; + + public sealed override ImmutableArray GetTypeParameterConstraintKinds() + => ImmutableArray.Empty; public sealed override RefKind RefKind { diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbol.cs index 695b7c6b73247..4ca8ef4726c75 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbol.cs @@ -30,7 +30,7 @@ internal static SourcePropertySymbol Create(SourceMemberContainerTypeSymbol cont private static SourcePropertySymbol Create( SourceMemberContainerTypeSymbol containingType, - Binder bodyBinder, + Binder binder, BasePropertyDeclarationSyntax syntax, string name, Location location, @@ -45,71 +45,91 @@ private static SourcePropertySymbol Create( out bool isInitOnly, out var getSyntax, out var setSyntax); - // This has the value that IsIndexer will ultimately have, once we've populated the fields of this object. - bool isIndexer = syntax.Kind() == SyntaxKind.IndexerDeclaration; + var explicitInterfaceSpecifier = GetExplicitInterfaceSpecifier(syntax); + SyntaxTokenList modifiersTokenList = GetModifierTokensSyntax(syntax); + bool isExplicitInterfaceImplementation = explicitInterfaceSpecifier is object; var modifiers = MakeModifiers( containingType, - GetModifierTokensSyntax(syntax), - isExplicitInterfaceImplementation: explicitInterfaceSpecifier is object, - isIndexer: isIndexer, + modifiersTokenList, + isExplicitInterfaceImplementation, + isIndexer: syntax.Kind() == SyntaxKind.IndexerDeclaration, accessorsHaveImplementation: accessorsHaveImplementation, location, diagnostics, out _); + + bool isExpressionBodied = !hasAccessorList && GetArrowExpression(syntax) != null; + + binder = binder.WithUnsafeRegionIfNecessary(modifiersTokenList); + TypeSymbol? explicitInterfaceType; + string? aliasQualifierOpt; + string memberName = ExplicitInterfaceHelpers.GetMemberNameAndInterfaceSymbol(binder, explicitInterfaceSpecifier, name, diagnostics, out explicitInterfaceType, out aliasQualifierOpt); + return new SourcePropertySymbol( containingType, - bodyBinder, syntax, - getSyntax: getSyntax, - setSyntax: setSyntax, - explicitInterfaceSpecifier, + hasGetAccessor: getSyntax != null || isExpressionBodied, + hasSetAccessor: setSyntax != null, + isExplicitInterfaceImplementation, + explicitInterfaceType, + aliasQualifierOpt, modifiers, - isIndexer: isIndexer, isAutoProperty: isAutoProperty, - hasAccessorList: hasAccessorList, + isExpressionBodied: isExpressionBodied, isInitOnly: isInitOnly, - name, + memberName, location, diagnostics); } private SourcePropertySymbol( - SourceMemberContainerTypeSymbol containingType, - Binder bodyBinder, - BasePropertyDeclarationSyntax syntax, - CSharpSyntaxNode? getSyntax, - CSharpSyntaxNode? setSyntax, - ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, + SourceMemberContainerTypeSymbol containingType, + BasePropertyDeclarationSyntax syntax, + bool hasGetAccessor, + bool hasSetAccessor, + bool isExplicitInterfaceImplementation, + TypeSymbol? explicitInterfaceType, + string? aliasQualifierOpt, DeclarationModifiers modifiers, - bool isIndexer, bool isAutoProperty, - bool hasAccessorList, + bool isExpressionBodied, bool isInitOnly, - string name, - Location location, - DiagnosticBag diagnostics) - : base( + string memberName, + Location location, + DiagnosticBag diagnostics) + : base( containingType, - bodyBinder, syntax, - getSyntax: getSyntax, - setSyntax: setSyntax, - arrowExpression: GetArrowExpression(syntax), - explicitInterfaceSpecifier, + hasGetAccessor, + hasSetAccessor, + isExplicitInterfaceImplementation, + explicitInterfaceType, + aliasQualifierOpt, modifiers, - isIndexer: isIndexer, hasInitializer: HasInitializer(syntax), isAutoProperty: isAutoProperty, - hasAccessorList: hasAccessorList, + isExpressionBodied: isExpressionBodied, isInitOnly: isInitOnly, syntax.Type.GetRefKind(), - name, - location, - typeOpt: default, - hasParameters: GetParameterListSyntax(syntax) is object, - diagnostics) + memberName, + syntax.AttributeLists, + location) { + if (IsAutoProperty) + { + Binder.CheckFeatureAvailability( + syntax, + (hasGetAccessor && !hasSetAccessor) ? MessageID.IDS_FeatureReadonlyAutoImplementedProperties : MessageID.IDS_FeatureAutoImplementedProperties, + diagnostics, + location); + } + + CheckForBlockAndExpressionBody( + syntax.AccessorList, + syntax.GetExpressionBodySyntax(), + syntax, + diagnostics); } private TypeSyntax GetTypeSyntax(SyntaxNode syntax) => ((BasePropertyDeclarationSyntax)syntax).Type; @@ -117,9 +137,6 @@ private SourcePropertySymbol( protected override Location TypeLocation => GetTypeSyntax(CSharpSyntaxNode).Location; - protected override SyntaxTokenList GetModifierTokens(SyntaxNode syntax) - => GetModifierTokensSyntax(syntax); - private static SyntaxTokenList GetModifierTokensSyntax(SyntaxNode syntax) => ((BasePropertyDeclarationSyntax)syntax).Modifiers; @@ -214,14 +231,33 @@ private static void GetAccessorDeclarations( } } - protected override void CheckForBlockAndExpressionBody(CSharpSyntaxNode syntax, DiagnosticBag diagnostics) + private static AccessorDeclarationSyntax GetGetAccessorDeclaration(BasePropertyDeclarationSyntax syntax) { - var prop = (BasePropertyDeclarationSyntax)syntax; - CheckForBlockAndExpressionBody( - prop.AccessorList, - prop.GetExpressionBodySyntax(), - prop, - diagnostics); + foreach (var accessor in syntax.AccessorList!.Accessors) + { + switch (accessor.Kind()) + { + case SyntaxKind.GetAccessorDeclaration: + return accessor; + } + } + + throw ExceptionUtilities.Unreachable; + } + + private static AccessorDeclarationSyntax GetSetAccessorDeclaration(BasePropertyDeclarationSyntax syntax) + { + foreach (var accessor in syntax.AccessorList!.Accessors) + { + switch (accessor.Kind()) + { + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.InitAccessorDeclaration: + return accessor; + } + } + + throw ExceptionUtilities.Unreachable; } private static DeclarationModifiers MakeModifiers( @@ -308,25 +344,51 @@ private static DeclarationModifiers MakeModifiers( return mods; } - protected override SourcePropertyAccessorSymbol? CreateAccessorSymbol( - bool isGet, - CSharpSyntaxNode? syntaxOpt, + protected override SourcePropertyAccessorSymbol CreateGetAccessorSymbol(bool isAutoPropertyAccessor, bool isExplicitInterfaceImplementation, PropertySymbol? explicitlyImplementedPropertyOpt, DiagnosticBag diagnostics) + { + var syntax = (BasePropertyDeclarationSyntax)CSharpSyntaxNode; + ArrowExpressionClauseSyntax? arrowExpression = GetArrowExpression(syntax); + string? aliasQualifierOpt = GetExplicitInterfaceSpecifier(syntax)?.Name.GetAliasQualifierOpt(); + + if (syntax.AccessorList is null && arrowExpression != null) + { + return CreateExpressionBodiedAccessor( + arrowExpression, + explicitlyImplementedPropertyOpt, + aliasQualifierOpt, + isExplicitInterfaceImplementation, + diagnostics); + } + else + { + return CreateAccessorSymbol(GetGetAccessorDeclaration(syntax), explicitlyImplementedPropertyOpt, aliasQualifierOpt, isAutoPropertyAccessor, isExplicitInterfaceImplementation, diagnostics); + } + } + + protected override SourcePropertyAccessorSymbol CreateSetAccessorSymbol(bool isAutoPropertyAccessor, bool isExplicitInterfaceImplementation, PropertySymbol? explicitlyImplementedPropertyOpt, DiagnosticBag diagnostics) + { + var syntax = (BasePropertyDeclarationSyntax)CSharpSyntaxNode; + string? aliasQualifierOpt = GetExplicitInterfaceSpecifier(syntax)?.Name.GetAliasQualifierOpt(); + + Debug.Assert(!(syntax.AccessorList is null && GetArrowExpression(syntax) != null)); + + return CreateAccessorSymbol(GetSetAccessorDeclaration(syntax), explicitlyImplementedPropertyOpt, aliasQualifierOpt, isAutoPropertyAccessor, isExplicitInterfaceImplementation, diagnostics); + } + + private SourcePropertyAccessorSymbol CreateAccessorSymbol( + AccessorDeclarationSyntax syntax, PropertySymbol? explicitlyImplementedPropertyOpt, string? aliasQualifierOpt, bool isAutoPropertyAccessor, bool isExplicitInterfaceImplementation, DiagnosticBag diagnostics) { - if (syntaxOpt is null) - { - return null; - } return SourcePropertyAccessorSymbol.CreateAccessorSymbol( ContainingType, this, _modifiers, _sourceName, - (AccessorDeclarationSyntax)syntaxOpt, + syntax, explicitlyImplementedPropertyOpt, aliasQualifierOpt, isAutoPropertyAccessor, @@ -334,7 +396,7 @@ private static DeclarationModifiers MakeModifiers( diagnostics); } - protected override SourcePropertyAccessorSymbol CreateExpressionBodiedAccessor( + private SourcePropertyAccessorSymbol CreateExpressionBodiedAccessor( ArrowExpressionClauseSyntax syntax, PropertySymbol? explicitlyImplementedPropertyOpt, string? aliasQualifierOpt, @@ -360,15 +422,21 @@ private Binder CreateBinderForTypeAndParameters() var syntax = CSharpSyntaxNode; var binderFactory = compilation.GetBinderFactory(syntaxTree); var binder = binderFactory.GetBinder(syntax, syntax, this); - SyntaxTokenList modifiers = GetModifierTokens(syntax); + SyntaxTokenList modifiers = GetModifierTokensSyntax(syntax); binder = binder.WithUnsafeRegionIfNecessary(modifiers); return binder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this); } - protected override TypeWithAnnotations ComputeType(Binder? binder, SyntaxNode syntax, DiagnosticBag diagnostics) + protected override (TypeWithAnnotations Type, ImmutableArray Parameters) MakeParametersAndBindType(DiagnosticBag diagnostics) { - binder ??= CreateBinderForTypeAndParameters(); + Binder binder = CreateBinderForTypeAndParameters(); + var syntax = CSharpSyntaxNode; + + return (ComputeType(binder, syntax, diagnostics), ComputeParameters(binder, syntax, diagnostics)); + } + private TypeWithAnnotations ComputeType(Binder binder, SyntaxNode syntax, DiagnosticBag diagnostics) + { RefKind refKind; var typeSyntax = GetTypeSyntax(syntax).SkipRef(out refKind); var type = binder.BindType(typeSyntax, diagnostics); @@ -433,17 +501,22 @@ private static ImmutableArray MakeParameters( return parameters; } - protected override ImmutableArray ComputeParameters(Binder? binder, CSharpSyntaxNode syntax, DiagnosticBag diagnostics) + private ImmutableArray ComputeParameters(Binder binder, CSharpSyntaxNode syntax, DiagnosticBag diagnostics) { - binder ??= CreateBinderForTypeAndParameters(); - var parameterSyntaxOpt = GetParameterListSyntax(syntax); var parameters = MakeParameters(binder, this, parameterSyntaxOpt, diagnostics, addRefReadOnlyModifier: IsVirtual || IsAbstract); + return parameters; + } + + internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, DiagnosticBag diagnostics) + { + base.AfterAddingTypeMembersChecks(conversions, diagnostics); + HashSet? useSiteDiagnostics = null; - foreach (ParameterSymbol param in parameters) + foreach (ParameterSymbol param in Parameters) { - if (GetExplicitInterfaceSpecifier(syntax) == null && !this.IsNoMoreVisibleThan(param.Type, ref useSiteDiagnostics)) + if (!IsExplicitInterfaceImplementation && !this.IsNoMoreVisibleThan(param.Type, ref useSiteDiagnostics)) { diagnostics.Add(ErrorCode.ERR_BadVisIndexerParam, Location, this, param.Type); } @@ -454,7 +527,6 @@ protected override ImmutableArray ComputeParameters(Binder? bin } diagnostics.Add(Location, useSiteDiagnostics); - return parameters; } protected override bool HasPointerTypeSyntactically diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbolBase.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbolBase.cs index 97a6e528bb402..562d625644a5a 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbolBase.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbolBase.cs @@ -30,6 +30,10 @@ private enum Flags : byte IsExpressionBodied = 1 << 0, IsAutoProperty = 1 << 1, IsExplicitInterfaceImplementation = 1 << 2, + HasGetAccessor = 1 << 3, + HasSetAccessor = 1 << 4, + HasInitializer = 1 << 5, + IsAutoPropertyWithGetAccessor = IsAutoProperty | HasGetAccessor, } // TODO (tomat): consider splitting into multiple subclasses/rare data. @@ -38,11 +42,14 @@ private enum Flags : byte private readonly string _name; private readonly SyntaxReference _syntaxRef; protected readonly DeclarationModifiers _modifiers; - private readonly ImmutableArray _refCustomModifiers; - private readonly SourcePropertyAccessorSymbol _getMethod; - private readonly SourcePropertyAccessorSymbol _setMethod; + private ImmutableArray _lazyRefCustomModifiers; +#nullable enable + private SourcePropertyAccessorSymbol? _lazyGetMethod; + private SourcePropertyAccessorSymbol? _lazySetMethod; + private DiagnosticBag? _lazyDiagnosticBag; +#nullable disable private readonly TypeSymbol _explicitInterfaceType; - private readonly ImmutableArray _explicitInterfaceImplementations; + private ImmutableArray _lazyExplicitInterfaceImplementations; private readonly Flags _propertyFlags; private readonly RefKind _refKind; @@ -66,58 +73,72 @@ private enum Flags : byte public Location Location { get; } #nullable enable - /// - /// The is passed for explicit interface implementations or - /// overrides to . If a binder is not required in this situation - /// the parameter can be null. - /// protected SourcePropertySymbolBase( SourceMemberContainerTypeSymbol containingType, - Binder? binder, CSharpSyntaxNode syntax, - CSharpSyntaxNode? getSyntax, - CSharpSyntaxNode? setSyntax, - ArrowExpressionClauseSyntax? arrowExpression, - ExplicitInterfaceSpecifierSyntax? interfaceSpecifier, + bool hasGetAccessor, + bool hasSetAccessor, + bool isExplicitInterfaceImplementation, + TypeSymbol? explicitInterfaceType, + string? aliasQualifierOpt, DeclarationModifiers modifiers, - bool isIndexer, bool hasInitializer, bool isAutoProperty, - bool hasAccessorList, + bool isExpressionBodied, bool isInitOnly, RefKind refKind, - string name, - Location location, - TypeWithAnnotations typeOpt, - bool hasParameters, - DiagnosticBag diagnostics) + string memberName, + SyntaxList indexerNameAttributeLists, + Location location) { + Debug.Assert(!isExpressionBodied || !isAutoProperty); + Debug.Assert(!isExpressionBodied || !hasInitializer); + _syntaxRef = syntax.GetReference(); Location = location; + _containingType = containingType; + _refKind = refKind; + _modifiers = modifiers; + _explicitInterfaceType = explicitInterfaceType; - bool isExplicitInterfaceImplementation = interfaceSpecifier != null; if (isExplicitInterfaceImplementation) { _propertyFlags |= Flags.IsExplicitInterfaceImplementation; } + else + { + _lazyExplicitInterfaceImplementations = ImmutableArray.Empty; + } - _containingType = containingType; - _refKind = refKind; + bool isIndexer = IsIndexer; + isAutoProperty = isAutoProperty && !(containingType.IsInterface && !IsStatic) && !IsAbstract && !IsExtern && !isIndexer; - if (binder is object) + if (isAutoProperty) { - binder = binder.WithUnsafeRegionIfNecessary(GetModifierTokens(syntax)); - binder = binder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this); + _propertyFlags |= Flags.IsAutoProperty; } - _modifiers = modifiers; - this.CheckAccessibility(location, diagnostics, isExplicitInterfaceImplementation); + if (hasGetAccessor) + { + _propertyFlags |= Flags.HasGetAccessor; + } - this.CheckModifiers(isExplicitInterfaceImplementation, location, isIndexer, diagnostics); + if (hasSetAccessor) + { + _propertyFlags |= Flags.HasSetAccessor; + } - isAutoProperty = isAutoProperty && !(containingType.IsInterface && !IsStatic) && !IsAbstract && !IsExtern && !isIndexer; + if (hasInitializer) + { + _propertyFlags |= Flags.HasInitializer; + } - if (isIndexer && !isExplicitInterfaceImplementation) + if (isExpressionBodied) + { + _propertyFlags |= Flags.IsExpressionBodied; + } + + if (isIndexer && indexerNameAttributeLists.Count != 0 && !isExplicitInterfaceImplementation) { // Evaluate the attributes immediately in case the IndexerNameAttribute has been applied. // NOTE: we want IsExplicitInterfaceImplementation, IsOverride, Locations, and the syntax reference @@ -128,7 +149,7 @@ protected SourcePropertySymbolBase( // always use the real attribute bag of this symbol and modify LoadAndValidateAttributes to // handle partially filled bags. CustomAttributesBag? temp = null; - LoadAndValidateAttributes(OneOrMany.Create(AttributeDeclarationSyntaxList), ref temp, earlyDecodingOnly: true); + LoadAndValidateAttributes(OneOrMany.Create(indexerNameAttributeLists), ref temp, earlyDecodingOnly: true); if (temp != null) { Debug.Assert(temp.IsEarlyDecodedWellKnownAttributeDataComputed); @@ -140,75 +161,28 @@ protected SourcePropertySymbolBase( } } - string aliasQualifierOpt; - string memberName = ExplicitInterfaceHelpers.GetMemberNameAndInterfaceSymbol(binder, interfaceSpecifier, name, diagnostics, out _explicitInterfaceType, out aliasQualifierOpt); - _sourceName = _sourceName ?? memberName; //sourceName may have been set while loading attributes + _sourceName = _sourceName ?? memberName; // _sourceName may have been set while loading attributes _name = isIndexer ? ExplicitInterfaceHelpers.GetMemberName(WellKnownMemberNames.Indexer, _explicitInterfaceType, aliasQualifierOpt) : _sourceName; - if (hasInitializer) + if ((isAutoProperty && hasGetAccessor) || hasInitializer) { - CheckInitializer(isAutoProperty, containingType.IsInterface, IsStatic, location, diagnostics); - } - - var hasGetAccessor = getSyntax is object; - var hasSetAccessor = setSyntax is object; - - if (isAutoProperty || hasInitializer) - { - var isAutoPropertyWithGetSyntax = isAutoProperty && hasGetAccessor; - if (isAutoPropertyWithGetSyntax) - { - _propertyFlags |= Flags.IsAutoProperty; - } - - bool isGetterOnly = hasGetAccessor && !hasSetAccessor; - - if (isAutoPropertyWithGetSyntax && !IsStatic && !isGetterOnly && !isInitOnly) - { - if (ContainingType.IsReadOnly) - { - diagnostics.Add(ErrorCode.ERR_AutoPropsInRoStruct, location); - } - else if (HasReadOnlyModifier) - { - diagnostics.Add(ErrorCode.ERR_AutoPropertyWithSetterCantBeReadOnly, location, this); - } - } - - if (isAutoPropertyWithGetSyntax || hasInitializer) - { - if (isAutoPropertyWithGetSyntax) - { - //issue a diagnostic if the compiler generated attribute ctor is not found. - Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(DeclaringCompilation, - WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor, diagnostics, syntax: syntax); - - if (this._refKind != RefKind.None && !_containingType.IsInterface) - { - diagnostics.Add(ErrorCode.ERR_AutoPropertyCannotBeRefReturning, location, this); - } - } - - string fieldName = GeneratedNames.MakeBackingFieldName(_sourceName); - BackingField = new SynthesizedBackingFieldSymbol(this, - fieldName, - isReadOnly: isGetterOnly || isInitOnly, - this.IsStatic, - hasInitializer); - } - - if (isAutoProperty) - { - Binder.CheckFeatureAvailability( - syntax, - isGetterOnly ? MessageID.IDS_FeatureReadonlyAutoImplementedProperties : MessageID.IDS_FeatureAutoImplementedProperties, - diagnostics, - location); - } + string fieldName = GeneratedNames.MakeBackingFieldName(_sourceName); + BackingField = new SynthesizedBackingFieldSymbol(this, + fieldName, + isReadOnly: (hasGetAccessor && !hasSetAccessor) || isInitOnly, + this.IsStatic, + hasInitializer); } + } + private void EnsureSignatureGuarded(DiagnosticBag diagnostics) + { PropertySymbol? explicitlyImplementedProperty = null; - _refCustomModifiers = ImmutableArray.Empty; + _lazyRefCustomModifiers = ImmutableArray.Empty; + + TypeWithAnnotations type; + (type, _lazyParameters) = MakeParametersAndBindType(diagnostics); + _lazyType = new TypeWithAnnotations.Boxed(type); // The runtime will not treat the accessors of this property as overrides or implementations // of those of another property unless both the signatures and the custom modifiers match. @@ -223,16 +197,9 @@ protected SourcePropertySymbolBase( // Note: we're checking if the syntax indicates explicit implementation rather, // than if explicitInterfaceType is null because we don't want to look for an // overridden property if this is supposed to be an explicit implementation. + bool isExplicitInterfaceImplementation = IsExplicitInterfaceImplementation; if (isExplicitInterfaceImplementation || this.IsOverride) { - // Type and parameters for overrides and explicit implementations cannot be bound - // lazily since the property name depends on the metadata name of the base property, - // and the property name is required to add the property to the containing type, and - // the type and parameters are required to determine the override or implementation. - var type = typeOpt.HasType ? typeOpt : this.ComputeType(binder, syntax, diagnostics); - _lazyType = new TypeWithAnnotations.Boxed(type); - _lazyParameters = !hasParameters ? ImmutableArray.Empty : this.ComputeParameters(binder, syntax, diagnostics); - bool isOverride = false; PropertySymbol? overriddenOrImplementedProperty; @@ -247,15 +214,16 @@ protected SourcePropertySymbolBase( } else { - string interfacePropertyName = isIndexer ? WellKnownMemberNames.Indexer : name; - explicitlyImplementedProperty = this.FindExplicitlyImplementedProperty(_explicitInterfaceType, interfacePropertyName, interfaceSpecifier, diagnostics); + CSharpSyntaxNode syntax = CSharpSyntaxNode; + string interfacePropertyName = IsIndexer ? WellKnownMemberNames.Indexer : ((PropertyDeclarationSyntax)syntax).Identifier.ValueText; + explicitlyImplementedProperty = this.FindExplicitlyImplementedProperty(_explicitInterfaceType, interfacePropertyName, GetExplicitInterfaceSpecifier(syntax), diagnostics); this.FindExplicitlyImplementedMemberVerification(explicitlyImplementedProperty, diagnostics); overriddenOrImplementedProperty = explicitlyImplementedProperty; } if ((object)overriddenOrImplementedProperty != null) { - _refCustomModifiers = _refKind != RefKind.None ? overriddenOrImplementedProperty.RefCustomModifiers : ImmutableArray.Empty; + _lazyRefCustomModifiers = _refKind != RefKind.None ? overriddenOrImplementedProperty.RefCustomModifiers : ImmutableArray.Empty; TypeWithAnnotations overriddenPropertyType = overriddenOrImplementedProperty.TypeWithAnnotations; @@ -278,151 +246,18 @@ protected SourcePropertySymbolBase( { var modifierType = Binder.GetWellKnownType(DeclaringCompilation, WellKnownType.System_Runtime_InteropServices_InAttribute, diagnostics, TypeLocation); - _refCustomModifiers = ImmutableArray.Create(CSharpCustomModifier.CreateRequired(modifierType)); + _lazyRefCustomModifiers = ImmutableArray.Create(CSharpCustomModifier.CreateRequired(modifierType)); } - if (!hasAccessorList && arrowExpression != null) - { - Debug.Assert(arrowExpression is object); - _propertyFlags |= Flags.IsExpressionBodied; - _getMethod = CreateExpressionBodiedAccessor( - arrowExpression, - explicitlyImplementedProperty, - aliasQualifierOpt, - isExplicitInterfaceImplementation, - diagnostics); - _setMethod = null; - } - else - { - _getMethod = CreateAccessorSymbol(isGet: true, getSyntax, explicitlyImplementedProperty, aliasQualifierOpt, isAutoProperty, isExplicitInterfaceImplementation, diagnostics); - _setMethod = CreateAccessorSymbol(isGet: false, setSyntax, explicitlyImplementedProperty, aliasQualifierOpt, isAutoProperty, isExplicitInterfaceImplementation, diagnostics); - - if (!hasGetAccessor || !hasSetAccessor) - { - if (!hasGetAccessor && !hasSetAccessor) - { - diagnostics.Add(ErrorCode.ERR_PropertyWithNoAccessors, location, this); - } - else if (_refKind != RefKind.None) - { - if (!hasGetAccessor) - { - diagnostics.Add(ErrorCode.ERR_RefPropertyMustHaveGetAccessor, location, this); - } - } - else if (isAutoProperty) - { - var accessor = _getMethod ?? _setMethod; - if (!hasGetAccessor) - { - diagnostics.Add(ErrorCode.ERR_AutoPropertyMustHaveGetAccessor, accessor!.Locations[0], accessor); - } - } - } - - // Check accessor accessibility is more restrictive than property accessibility. - CheckAccessibilityMoreRestrictive(_getMethod, diagnostics); - CheckAccessibilityMoreRestrictive(_setMethod, diagnostics); - - if ((_getMethod is object) && (_setMethod is object)) - { - if (_refKind != RefKind.None) - { - diagnostics.Add(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, _setMethod.Locations[0], _setMethod); - } - else if ((_getMethod.LocalAccessibility != Accessibility.NotApplicable) && - (_setMethod.LocalAccessibility != Accessibility.NotApplicable)) - { - // Check accessibility is set on at most one accessor. - diagnostics.Add(ErrorCode.ERR_DuplicatePropertyAccessMods, location, this); - } - else if (_getMethod.LocalDeclaredReadOnly && _setMethod.LocalDeclaredReadOnly) - { - diagnostics.Add(ErrorCode.ERR_DuplicatePropertyReadOnlyMods, location, this); - } - else if (this.IsAbstract) - { - // Check abstract property accessors are not private. - CheckAbstractPropertyAccessorNotPrivate(_getMethod, diagnostics); - CheckAbstractPropertyAccessorNotPrivate(_setMethod, diagnostics); - } - } - else - { - if (!this.IsOverride) - { - var accessor = _getMethod ?? _setMethod; - if (accessor is object) - { - // Check accessibility is not set on the one accessor. - if (accessor.LocalAccessibility != Accessibility.NotApplicable) - { - diagnostics.Add(ErrorCode.ERR_AccessModMissingAccessor, location, this); - } - - // Check that 'readonly' is not set on the one accessor. - if (accessor.LocalDeclaredReadOnly) - { - diagnostics.Add(ErrorCode.ERR_ReadOnlyModMissingAccessor, location, this); - } - } - } - } - } - - if (explicitlyImplementedProperty is object) - { - CheckExplicitImplementationAccessor(_getMethod, explicitlyImplementedProperty.GetMethod, explicitlyImplementedProperty, diagnostics); - CheckExplicitImplementationAccessor(_setMethod, explicitlyImplementedProperty.SetMethod, explicitlyImplementedProperty, diagnostics); - } - - _explicitInterfaceImplementations = + Debug.Assert(isExplicitInterfaceImplementation || _lazyExplicitInterfaceImplementations.IsEmpty); + _lazyExplicitInterfaceImplementations = explicitlyImplementedProperty is null ? ImmutableArray.Empty : ImmutableArray.Create(explicitlyImplementedProperty); - - // get-only auto property should not override settable properties - if ((_propertyFlags & Flags.IsAutoProperty) != 0) - { - if (_setMethod is null && !this.IsReadOnly) - { - diagnostics.Add(ErrorCode.ERR_AutoPropertyMustOverrideSet, location, this); - } - - CheckForFieldTargetedAttribute(diagnostics); - } - - CheckForBlockAndExpressionBody(syntax, diagnostics); } protected abstract Location TypeLocation { get; } - protected abstract SyntaxTokenList GetModifierTokens(SyntaxNode syntax); - - private void CheckForFieldTargetedAttribute(DiagnosticBag diagnostics) - { - var languageVersion = this.DeclaringCompilation.LanguageVersion; - if (languageVersion.AllowAttributesOnBackingFields()) - { - return; - } - - foreach (var attribute in AttributeDeclarationSyntaxList) - { - if (attribute.Target?.GetAttributeLocation() == AttributeLocation.Field) - { - diagnostics.Add( - new CSDiagnosticInfo(ErrorCode.WRN_AttributesOnBackingFieldsNotAvailable, - languageVersion.ToDisplayString(), - new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureAttributesOnBackingFields.RequiredVersion())), - attribute.Target.Location); - } - } - } - - protected abstract void CheckForBlockAndExpressionBody(CSharpSyntaxNode syntax, DiagnosticBag diagnostics); - #nullable disable internal sealed override ImmutableArray NotNullMembers => @@ -454,7 +289,7 @@ private void CheckInitializer( } } - public override RefKind RefKind + public sealed override RefKind RefKind { get { @@ -462,25 +297,85 @@ public override RefKind RefKind } } - public override TypeWithAnnotations TypeWithAnnotations + public sealed override TypeWithAnnotations TypeWithAnnotations { get { - if (_lazyType == null) + EnsureSignature(); + return _lazyType.Value; + } + } + +#nullable enable + + private void EnsureSignature() + { + if (!_state.HasComplete(CompletionPart.FinishPropertyEnsureSignature)) + { + // If this lock ever encloses a potential call to Debugger.NotifyOfCrossThreadDependency, + // then we should call DebuggerUtilities.CallBeforeAcquiringLock() (see method comment for more + // details). + + lock (_syntaxRef) { - var diagnostics = DiagnosticBag.GetInstance(); - var result = this.ComputeType(binder: null, CSharpSyntaxNode, diagnostics); - if (Interlocked.CompareExchange(ref _lazyType, new TypeWithAnnotations.Boxed(result), null) == null) + if (_state.NotePartComplete(CompletionPart.StartPropertyEnsureSignature)) + { + // By setting StartPropertyEnsureSignature, we've committed to doing the work and setting + // FinishPropertyEnsureSignature. So there is no cancellation supported between one and the other. + var diagnostics = DiagnosticBag.GetInstance(); + try + { + EnsureSignatureGuarded(diagnostics); + AddDiagnostics(diagnostics); + } + finally + { + _state.NotePartComplete(CompletionPart.FinishPropertyEnsureSignature); + diagnostics.Free(); + } + } + else { - this.AddDeclarationDiagnostics(diagnostics); + // Either (1) this thread is in the process of completing the method, + // or (2) some other thread has beat us to the punch and completed the method. + // We can distinguish the two cases here by checking for the FinishPropertyEnsureSignature + // part to be complete, which would only occur if another thread completed this + // method. + // + // The other case, in which this thread is in the process of completing the method, + // requires that we return here even though the work is not complete. That's because + // signature is processed by first populating the return type and parameters by binding + // the syntax from source. Those values are visible to the same thread for the purpose + // of computing which methods are implemented and overridden. But then those values + // may be rewritten (by the same thread) to copy down custom modifiers. In order to + // allow the same thread to see the return type and parameters from the syntax (though + // they do not yet take on their final values), we return here. + + // Due to the fact that this method is potentially reentrant, we must use a + // reentrant lock to avoid deadlock and cannot assert that at this point the work + // has completed (_state.HasComplete(CompletionPart.FinishPropertyEnsureSignature)). } - diagnostics.Free(); } + } + } - return _lazyType.Value; + private void AddDiagnostics(DiagnosticBag diagnostics) + { + if (!diagnostics.IsEmptyWithoutResolution) + { + DiagnosticBag? destination = _lazyDiagnosticBag; + if (destination is null) + { + var newBag = new DiagnosticBag(); + destination = Interlocked.CompareExchange(ref _lazyDiagnosticBag, newBag, null!) ?? newBag; + } + + destination.AddRange(diagnostics); } } +#nullable disable + internal bool HasPointerType { get @@ -613,36 +508,79 @@ internal bool IsNew internal bool HasReadOnlyModifier => (_modifiers & DeclarationModifiers.ReadOnly) != 0; - public override MethodSymbol GetMethod - { - get { return _getMethod; } - } +#nullable enable + protected abstract SourcePropertyAccessorSymbol CreateGetAccessorSymbol( + bool isAutoPropertyAccessor, + bool isExplicitInterfaceImplementation, + PropertySymbol? explicitlyImplementedPropertyOpt, + DiagnosticBag diagnostics); - public override MethodSymbol SetMethod - { - get { return _setMethod; } - } + protected abstract SourcePropertyAccessorSymbol CreateSetAccessorSymbol( + bool isAutoPropertyAccessor, + bool isExplicitInterfaceImplementation, + PropertySymbol? explicitlyImplementedPropertyOpt, + DiagnosticBag diagnostics); - internal override Microsoft.Cci.CallingConvention CallingConvention + public sealed override MethodSymbol? GetMethod { - get { return (IsStatic ? 0 : Microsoft.Cci.CallingConvention.HasThis); } + get + { + if (_lazyGetMethod is null && (_propertyFlags & Flags.HasGetAccessor) != 0) + { + var diagnostics = DiagnosticBag.GetInstance(); + bool isExplicitInterfaceImplementation = IsExplicitInterfaceImplementation; + var result = CreateGetAccessorSymbol(isAutoPropertyAccessor: IsAutoProperty, isExplicitInterfaceImplementation, + explicitlyImplementedPropertyOpt: isExplicitInterfaceImplementation ? ExplicitInterfaceImplementations.FirstOrDefault() : null, + diagnostics); + if (Interlocked.CompareExchange(ref _lazyGetMethod, result, null) == null) + { + AddDiagnostics(diagnostics); + } + + diagnostics.Free(); + } + + Debug.Assert((_lazyGetMethod is object) == ((_propertyFlags & Flags.HasGetAccessor) != 0)); + return _lazyGetMethod; + } } - public override ImmutableArray Parameters + public sealed override MethodSymbol? SetMethod { get { - if (_lazyParameters.IsDefault) + if (_lazySetMethod is null && (_propertyFlags & Flags.HasSetAccessor) != 0) { var diagnostics = DiagnosticBag.GetInstance(); - var result = this.ComputeParameters(binder: null, CSharpSyntaxNode, diagnostics); - if (ImmutableInterlocked.InterlockedInitialize(ref _lazyParameters, result)) + bool isExplicitInterfaceImplementation = IsExplicitInterfaceImplementation; + var result = CreateSetAccessorSymbol(isAutoPropertyAccessor: IsAutoProperty, isExplicitInterfaceImplementation, + explicitlyImplementedPropertyOpt: isExplicitInterfaceImplementation ? ExplicitInterfaceImplementations.FirstOrDefault() : null, + diagnostics); + if (Interlocked.CompareExchange(ref _lazySetMethod, result, null) == null) { - this.AddDeclarationDiagnostics(diagnostics); + AddDiagnostics(diagnostics); } + diagnostics.Free(); } + Debug.Assert((_lazySetMethod is object) == ((_propertyFlags & Flags.HasSetAccessor) != 0)); + return _lazySetMethod; + } + } + +#nullable disable + + internal override Microsoft.Cci.CallingConvention CallingConvention + { + get { return (IsStatic ? 0 : Microsoft.Cci.CallingConvention.HasThis); } + } + + public sealed override ImmutableArray Parameters + { + get + { + EnsureSignature(); return _lazyParameters; } } @@ -650,14 +588,30 @@ public override ImmutableArray Parameters internal override bool IsExplicitInterfaceImplementation => (_propertyFlags & Flags.IsExplicitInterfaceImplementation) != 0; - public override ImmutableArray ExplicitInterfaceImplementations + public sealed override ImmutableArray ExplicitInterfaceImplementations { - get { return _explicitInterfaceImplementations; } + get + { + if (IsExplicitInterfaceImplementation) + { + EnsureSignature(); + } + else + { + Debug.Assert(_lazyExplicitInterfaceImplementations.IsEmpty); + } + + return _lazyExplicitInterfaceImplementations; + } } - public override ImmutableArray RefCustomModifiers + public sealed override ImmutableArray RefCustomModifiers { - get { return _refCustomModifiers; } + get + { + EnsureSignature(); + return _lazyRefCustomModifiers; + } } public override Accessibility DeclaredAccessibility @@ -677,7 +631,10 @@ public bool HasSkipLocalsInitAttribute } } - internal bool IsAutoProperty + internal bool IsAutoPropertyWithGetAccessor + => (_propertyFlags & Flags.IsAutoPropertyWithGetAccessor) == Flags.IsAutoPropertyWithGetAccessor; + + protected bool IsAutoProperty => (_propertyFlags & Flags.IsAutoProperty) != 0; /// @@ -717,6 +674,133 @@ internal SyntaxTree SyntaxTree internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, DiagnosticBag diagnostics) { +#nullable enable + bool isExplicitInterfaceImplementation = IsExplicitInterfaceImplementation; + this.CheckAccessibility(Location, diagnostics, isExplicitInterfaceImplementation); + this.CheckModifiers(isExplicitInterfaceImplementation, Location, IsIndexer, diagnostics); + + bool hasInitializer = (_propertyFlags & Flags.HasInitializer) != 0; + if (hasInitializer) + { + CheckInitializer(IsAutoProperty, ContainingType.IsInterface, IsStatic, Location, diagnostics); + } + + if (IsAutoPropertyWithGetAccessor) + { + Debug.Assert(GetMethod is object); + + if (!IsStatic && SetMethod is { IsInitOnly: false }) + { + if (ContainingType.IsReadOnly) + { + diagnostics.Add(ErrorCode.ERR_AutoPropsInRoStruct, Location); + } + else if (HasReadOnlyModifier) + { + diagnostics.Add(ErrorCode.ERR_AutoPropertyWithSetterCantBeReadOnly, Location, this); + } + } + + //issue a diagnostic if the compiler generated attribute ctor is not found. + Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(DeclaringCompilation, + WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor, diagnostics, location: Location); + + if (this.RefKind != RefKind.None) + { + diagnostics.Add(ErrorCode.ERR_AutoPropertyCannotBeRefReturning, Location, this); + } + + // get-only auto property should not override settable properties + if (SetMethod is null && !this.IsReadOnly) + { + diagnostics.Add(ErrorCode.ERR_AutoPropertyMustOverrideSet, Location, this); + } + } + + if (!IsExpressionBodied) + { + bool hasGetAccessor = GetMethod is object; + bool hasSetAccessor = SetMethod is object; + + if (hasGetAccessor && hasSetAccessor) + { + Debug.Assert(_lazyGetMethod is object); + Debug.Assert(_lazySetMethod is object); + + if (_refKind != RefKind.None) + { + diagnostics.Add(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, _lazySetMethod.Locations[0], _lazySetMethod); + } + else if ((_lazyGetMethod.LocalAccessibility != Accessibility.NotApplicable) && + (_lazySetMethod.LocalAccessibility != Accessibility.NotApplicable)) + { + // Check accessibility is set on at most one accessor. + diagnostics.Add(ErrorCode.ERR_DuplicatePropertyAccessMods, Location, this); + } + else if (_lazyGetMethod.LocalDeclaredReadOnly && _lazySetMethod.LocalDeclaredReadOnly) + { + diagnostics.Add(ErrorCode.ERR_DuplicatePropertyReadOnlyMods, Location, this); + } + else if (this.IsAbstract) + { + // Check abstract property accessors are not private. + CheckAbstractPropertyAccessorNotPrivate(_lazyGetMethod, diagnostics); + CheckAbstractPropertyAccessorNotPrivate(_lazySetMethod, diagnostics); + } + } + else + { + if (!hasGetAccessor && !hasSetAccessor) + { + diagnostics.Add(ErrorCode.ERR_PropertyWithNoAccessors, Location, this); + } + else if (RefKind != RefKind.None) + { + if (!hasGetAccessor) + { + diagnostics.Add(ErrorCode.ERR_RefPropertyMustHaveGetAccessor, Location, this); + } + } + else if (!hasGetAccessor && IsAutoProperty) + { + diagnostics.Add(ErrorCode.ERR_AutoPropertyMustHaveGetAccessor, _lazySetMethod!.Locations[0], _lazySetMethod); + } + + if (!this.IsOverride) + { + var accessor = _lazyGetMethod ?? _lazySetMethod; + if (accessor is object) + { + // Check accessibility is not set on the one accessor. + if (accessor.LocalAccessibility != Accessibility.NotApplicable) + { + diagnostics.Add(ErrorCode.ERR_AccessModMissingAccessor, Location, this); + } + + // Check that 'readonly' is not set on the one accessor. + if (accessor.LocalDeclaredReadOnly) + { + diagnostics.Add(ErrorCode.ERR_ReadOnlyModMissingAccessor, Location, this); + } + } + } + } + + // Check accessor accessibility is more restrictive than property accessibility. + CheckAccessibilityMoreRestrictive(_lazyGetMethod, diagnostics); + CheckAccessibilityMoreRestrictive(_lazySetMethod, diagnostics); + } + + PropertySymbol? explicitlyImplementedProperty = ExplicitInterfaceImplementations.FirstOrDefault(); + + if (explicitlyImplementedProperty is object) + { + CheckExplicitImplementationAccessor(GetMethod, explicitlyImplementedProperty.GetMethod, explicitlyImplementedProperty, diagnostics); + CheckExplicitImplementationAccessor(SetMethod, explicitlyImplementedProperty.SetMethod, explicitlyImplementedProperty, diagnostics); + } + +#nullable disable + Location location = TypeLocation; var compilation = DeclaringCompilation; @@ -733,9 +817,9 @@ internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, _explicitInterfaceType.CheckAllConstraints(compilation, conversions, new SourceLocation(explicitInterfaceSpecifier.Name), diagnostics); // Note: we delayed nullable-related checks that could pull on NonNullTypes - if (!_explicitInterfaceImplementations.IsEmpty) + if (explicitlyImplementedProperty is object) { - TypeSymbol.CheckNullableReferenceTypeMismatchOnImplementingMember(this.ContainingType, this, _explicitInterfaceImplementations[0], isExplicit: true, diagnostics); + TypeSymbol.CheckNullableReferenceTypeMismatchOnImplementingMember(this.ContainingType, this, explicitlyImplementedProperty, isExplicit: true, diagnostics); } } @@ -832,24 +916,6 @@ private void CheckModifiers(bool isExplicitInterfaceImplementation, Location loc } } -#nullable enable - protected abstract SourcePropertyAccessorSymbol? CreateAccessorSymbol( - bool isGet, - CSharpSyntaxNode? syntaxOpt, - PropertySymbol? explicitlyImplementedPropertyOpt, - string? aliasQualifierOpt, - bool isAutoPropertyAccessor, - bool isExplicitInterfaceImplementation, - DiagnosticBag diagnostics); - - protected abstract SourcePropertyAccessorSymbol CreateExpressionBodiedAccessor( - ArrowExpressionClauseSyntax syntax, - PropertySymbol? explicitlyImplementedPropertyOpt, - string? aliasQualifierOpt, - bool isExplicitInterfaceImplementation, - DiagnosticBag diagnostics); -#nullable disable - private void CheckAccessibilityMoreRestrictive(SourcePropertyAccessorSymbol accessor, DiagnosticBag diagnostics) { if (((object)accessor != null) && @@ -929,8 +995,8 @@ internal SynthesizedSealedPropertyAccessor SynthesizedSealedAccessorOpt { get { - bool hasGetter = (object)_getMethod != null; - bool hasSetter = (object)_setMethod != null; + bool hasGetter = GetMethod is object; + bool hasSetter = SetMethod is object; if (!this.IsSealed || (hasGetter && hasSetter)) { return null; @@ -952,15 +1018,15 @@ internal SynthesizedSealedPropertyAccessor SynthesizedSealedAccessorOpt /// private SynthesizedSealedPropertyAccessor MakeSynthesizedSealedAccessor() { - Debug.Assert(this.IsSealed && ((object)_getMethod == null || (object)_setMethod == null)); + Debug.Assert(this.IsSealed && (GetMethod is null || SetMethod is null)); - if ((object)_getMethod != null) + if (GetMethod is object) { // need to synthesize setter MethodSymbol overriddenAccessor = this.GetOwnOrInheritedSetMethod(); return (object)overriddenAccessor == null ? null : new SynthesizedSealedPropertyAccessor(this, overriddenAccessor); } - else if ((object)_setMethod != null) + else if (SetMethod is object) { // need to synthesize getter MethodSymbol overriddenAccessor = this.GetOwnOrInheritedGetMethod(); @@ -986,7 +1052,7 @@ private SynthesizedSealedPropertyAccessor MakeSynthesizedSealedAccessor() AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation => AttributeLocation.Property; AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations - => (_propertyFlags & Flags.IsAutoProperty) != 0 + => IsAutoPropertyWithGetAccessor ? AttributeLocation.Property | AttributeLocation.Field : AttributeLocation.Property; @@ -1349,6 +1415,12 @@ internal override void ForceComplete(SourceLocation locationOpt, CancellationTok GetAttributes(); break; + case CompletionPart.StartPropertyEnsureSignature: + case CompletionPart.FinishPropertyEnsureSignature: + EnsureSignature(); + Debug.Assert(_state.HasComplete(CompletionPart.FinishPropertyEnsureSignature)); + break; + case CompletionPart.StartPropertyParameters: case CompletionPart.FinishPropertyParameters: { @@ -1405,6 +1477,30 @@ internal override void ForceComplete(SourceLocation locationOpt, CancellationTok } break; + case CompletionPart.StartPropertyFinalCompletion: + case CompletionPart.FinishPropertyFinalCompletion: + { + if (_state.NotePartComplete(CompletionPart.StartPropertyFinalCompletion)) + { + DiagnosticBag diagnostic = _lazyDiagnosticBag; + if (diagnostic is object) + { + Debug.Assert(!diagnostic.IsEmptyWithoutResolution); + this.AddDeclarationDiagnostics(diagnostic); + _lazyDiagnosticBag = null; + } + + var completedOnThisThread = _state.NotePartComplete(CompletionPart.FinishPropertyFinalCompletion); + Debug.Assert(completedOnThisThread); + } + else + { + // StartPropertyFinalCompletion was completed by another thread. Wait for it to finish the work. + _state.SpinWaitComplete(CompletionPart.FinishPropertyFinalCompletion, cancellationToken); + } + } + break; + case CompletionPart.None: return; @@ -1425,7 +1521,7 @@ protected virtual void ValidatePropertyType(DiagnosticBag diagnostics) { diagnostics.Add(ErrorCode.ERR_FieldCantBeRefAny, TypeLocation, type); } - else if (this.IsAutoProperty && type.IsRefLikeType && (this.IsStatic || !this.ContainingType.IsRefLikeType)) + else if (this.IsAutoPropertyWithGetAccessor && type.IsRefLikeType && (this.IsStatic || !this.ContainingType.IsRefLikeType)) { diagnostics.Add(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, TypeLocation, type); } @@ -1434,9 +1530,8 @@ protected virtual void ValidatePropertyType(DiagnosticBag diagnostics) #endregion #nullable enable - protected abstract ImmutableArray ComputeParameters(Binder? binder, CSharpSyntaxNode syntax, DiagnosticBag diagnostics); - protected abstract TypeWithAnnotations ComputeType(Binder? binder, SyntaxNode syntax, DiagnosticBag diagnostics); + protected abstract (TypeWithAnnotations Type, ImmutableArray Parameters) MakeParametersAndBindType(DiagnosticBag diagnostics); protected static ExplicitInterfaceSpecifierSyntax? GetExplicitInterfaceSpecifier(SyntaxNode syntax) => (syntax as BasePropertyDeclarationSyntax)?.ExplicitInterfaceSpecifier; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceTypeParameterSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceTypeParameterSymbol.cs index be48267a75b48..ff8f1bfd7ff52 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceTypeParameterSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceTypeParameterSymbol.cs @@ -88,27 +88,27 @@ public override string Name } } - internal override ImmutableArray GetConstraintTypes(ConsList inProgress, bool canIgnoreNullableContext) + internal override ImmutableArray GetConstraintTypes(ConsList inProgress) { - var bounds = this.GetBounds(inProgress, canIgnoreNullableContext); + var bounds = this.GetBounds(inProgress); return (bounds != null) ? bounds.ConstraintTypes : ImmutableArray.Empty; } internal override ImmutableArray GetInterfaces(ConsList inProgress) { - var bounds = this.GetBounds(inProgress, canIgnoreNullableContext: false); + var bounds = this.GetBounds(inProgress); return (bounds != null) ? bounds.Interfaces : ImmutableArray.Empty; } internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList inProgress) { - var bounds = this.GetBounds(inProgress, canIgnoreNullableContext: false); + var bounds = this.GetBounds(inProgress); return (bounds != null) ? bounds.EffectiveBaseClass : this.GetDefaultBaseType(); } internal override TypeSymbol GetDeducedBaseType(ConsList inProgress) { - var bounds = this.GetBounds(inProgress, canIgnoreNullableContext: false); + var bounds = this.GetBounds(inProgress); return (bounds != null) ? bounds.DeducedBaseType : this.GetDefaultBaseType(); } @@ -204,11 +204,11 @@ internal virtual CustomAttributesBag GetAttributesBag() return _lazyCustomAttributesBag; } - internal override void EnsureAllConstraintsAreResolved(bool canIgnoreNullableContext) + internal override void EnsureAllConstraintsAreResolved() { - if (!_lazyBounds.HasValue(canIgnoreNullableContext)) + if (!_lazyBounds.IsSet()) { - EnsureAllConstraintsAreResolved(this.ContainerTypeParameters, canIgnoreNullableContext); + EnsureAllConstraintsAreResolved(this.ContainerTypeParameters); } } @@ -217,18 +217,17 @@ protected abstract ImmutableArray ContainerTypeParameters get; } - private TypeParameterBounds GetBounds(ConsList inProgress, bool canIgnoreNullableContext) + private TypeParameterBounds GetBounds(ConsList inProgress) { Debug.Assert(!inProgress.ContainsReference(this)); Debug.Assert(!inProgress.Any() || ReferenceEquals(inProgress.Head.ContainingSymbol, this.ContainingSymbol)); - if (!_lazyBounds.HasValue(canIgnoreNullableContext)) + if (!_lazyBounds.IsSet()) { var diagnostics = DiagnosticBag.GetInstance(); - var bounds = this.ResolveBounds(inProgress, canIgnoreNullableContext, diagnostics); + var bounds = this.ResolveBounds(inProgress, diagnostics); - if (TypeParameterBoundsExtensions.InterlockedUpdate(ref _lazyBounds, bounds) && - _lazyBounds.HasValue(canIgnoreNullableContext: false)) + if (ReferenceEquals(Interlocked.CompareExchange(ref _lazyBounds, bounds, TypeParameterBounds.Unset), TypeParameterBounds.Unset)) { this.CheckConstraintTypeConstraints(diagnostics); this.CheckUnmanagedConstraint(diagnostics); @@ -243,7 +242,7 @@ private TypeParameterBounds GetBounds(ConsList inProgress, return _lazyBounds; } - protected abstract TypeParameterBounds ResolveBounds(ConsList inProgress, bool canIgnoreNullableContext, DiagnosticBag diagnostics); + protected abstract TypeParameterBounds ResolveBounds(ConsList inProgress, DiagnosticBag diagnostics); /// /// Check constraints of generic types referenced in constraint types. For instance, @@ -489,7 +488,7 @@ public override bool HasConstructorConstraint { get { - var constraints = this.GetDeclaredConstraints(canIgnoreNullableContext: true); + var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.Constructor) != 0; } } @@ -498,25 +497,44 @@ public override bool HasValueTypeConstraint { get { - var constraints = this.GetDeclaredConstraints(canIgnoreNullableContext: true); + var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.AllValueTypeKinds) != 0; } } + public override bool IsValueTypeFromConstraintTypes + { + get + { + Debug.Assert(!HasValueTypeConstraint); + var constraints = this.GetConstraintKinds(); + return (constraints & TypeParameterConstraintKind.ValueTypeFromConstraintTypes) != 0; + } + } + public override bool HasReferenceTypeConstraint { get { - var constraints = this.GetDeclaredConstraints(canIgnoreNullableContext: true); + var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ReferenceType) != 0; } } + public override bool IsReferenceTypeFromConstraintTypes + { + get + { + var constraints = this.GetConstraintKinds(); + return (constraints & TypeParameterConstraintKind.ReferenceTypeFromConstraintTypes) != 0; + } + } + internal override bool? ReferenceTypeConstraintIsNullable { get { - return CalculateReferenceTypeConstraintIsNullable(this.GetDeclaredConstraints(canIgnoreNullableContext: false)); + return CalculateReferenceTypeConstraintIsNullable(this.GetConstraintKinds()); } } @@ -524,7 +542,7 @@ public override bool HasNotNullConstraint { get { - var constraints = this.GetDeclaredConstraints(canIgnoreNullableContext: false); + var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.NotNull) != 0; } } @@ -533,7 +551,7 @@ internal override bool? IsNotNullable { get { - if ((this.GetDeclaredConstraints(canIgnoreNullableContext: false) & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) != 0) + if ((this.GetConstraintKinds() & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) != 0) { return null; } @@ -546,7 +564,7 @@ public override bool HasUnmanagedTypeConstraint { get { - var constraints = this.GetDeclaredConstraints(canIgnoreNullableContext: true); + var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.Unmanaged) != 0; } } @@ -556,27 +574,20 @@ protected override ImmutableArray ContainerTypeParameters get { return _owner.TypeParameters; } } - private TypeParameterConstraintClause GetTypeParameterConstraintClause(bool canIgnoreNullableContext) - { - return _owner.GetTypeParameterConstraintClause(canIgnoreNullableContext, this.Ordinal); - } - - protected override TypeParameterBounds ResolveBounds(ConsList inProgress, bool canIgnoreNullableContext, DiagnosticBag diagnostics) + protected override TypeParameterBounds ResolveBounds(ConsList inProgress, DiagnosticBag diagnostics) { - var constraintClause = GetTypeParameterConstraintClause(canIgnoreNullableContext); - if (constraintClause.IsEmpty) + var constraintTypes = _owner.GetTypeParameterConstraintTypes(this.Ordinal); + if (constraintTypes.IsEmpty && GetConstraintKinds() == TypeParameterConstraintKind.None) { return null; } - var constraintTypes = constraintClause.ConstraintTypes; - return this.ResolveBounds(this.ContainingAssembly.CorLibrary, inProgress.Prepend(this), constraintTypes, inherited: false, ignoresNullableContext: constraintClause.IgnoresNullableContext, this.DeclaringCompilation, diagnostics); + return this.ResolveBounds(this.ContainingAssembly.CorLibrary, inProgress.Prepend(this), constraintTypes, inherited: false, this.DeclaringCompilation, diagnostics); } - private TypeParameterConstraintKind GetDeclaredConstraints(bool canIgnoreNullableContext) + private TypeParameterConstraintKind GetConstraintKinds() { - var constraintClause = GetTypeParameterConstraintClause(canIgnoreNullableContext); - return constraintClause.Constraints; + return _owner.GetTypeParameterConstraintKind(this.Ordinal); } } @@ -610,7 +621,7 @@ public override bool HasConstructorConstraint { get { - var constraints = this.GetDeclaredConstraints(canIgnoreNullableContext: true); + var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.Constructor) != 0; } } @@ -619,25 +630,44 @@ public override bool HasValueTypeConstraint { get { - var constraints = this.GetDeclaredConstraints(canIgnoreNullableContext: true); + var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.AllValueTypeKinds) != 0; } } + public override bool IsValueTypeFromConstraintTypes + { + get + { + Debug.Assert(!HasValueTypeConstraint); + var constraints = this.GetConstraintKinds(); + return (constraints & TypeParameterConstraintKind.ValueTypeFromConstraintTypes) != 0; + } + } + public override bool HasReferenceTypeConstraint { get { - var constraints = this.GetDeclaredConstraints(canIgnoreNullableContext: true); + var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ReferenceType) != 0; } } + public override bool IsReferenceTypeFromConstraintTypes + { + get + { + var constraints = this.GetConstraintKinds(); + return (constraints & TypeParameterConstraintKind.ReferenceTypeFromConstraintTypes) != 0; + } + } + public override bool HasNotNullConstraint { get { - var constraints = this.GetDeclaredConstraints(canIgnoreNullableContext: false); + var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.NotNull) != 0; } } @@ -646,7 +676,7 @@ internal override bool? ReferenceTypeConstraintIsNullable { get { - return CalculateReferenceTypeConstraintIsNullable(this.GetDeclaredConstraints(canIgnoreNullableContext: false)); + return CalculateReferenceTypeConstraintIsNullable(this.GetConstraintKinds()); } } @@ -654,7 +684,7 @@ internal override bool? IsNotNullable { get { - if ((this.GetDeclaredConstraints(canIgnoreNullableContext: false) & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) != 0) + if ((this.GetConstraintKinds() & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) != 0) { return null; } @@ -667,7 +697,7 @@ public override bool HasUnmanagedTypeConstraint { get { - var constraints = this.GetDeclaredConstraints(canIgnoreNullableContext: true); + var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.Unmanaged) != 0; } } @@ -677,28 +707,23 @@ protected override ImmutableArray ContainerTypeParameters get { return _owner.TypeParameters; } } - private TypeParameterConstraintClause GetTypeParameterConstraintClause(bool canIgnoreNullableContext) + protected override TypeParameterBounds ResolveBounds(ConsList inProgress, DiagnosticBag diagnostics) { - var constraintClauses = _owner.GetTypeParameterConstraintClauses(canIgnoreNullableContext); - return constraintClauses.IsEmpty ? TypeParameterConstraintClause.Empty : constraintClauses[Ordinal]; - } + var constraints = _owner.GetTypeParameterConstraintTypes(); + var constraintTypes = constraints.IsEmpty ? ImmutableArray.Empty : constraints[Ordinal]; - protected override TypeParameterBounds ResolveBounds(ConsList inProgress, bool canIgnoreNullableContext, DiagnosticBag diagnostics) - { - var constraintClause = GetTypeParameterConstraintClause(canIgnoreNullableContext); - if (constraintClause.IsEmpty) + if (constraintTypes.IsEmpty && GetConstraintKinds() == TypeParameterConstraintKind.None) { return null; } - var constraintTypes = constraintClause.ConstraintTypes; - return this.ResolveBounds(this.ContainingAssembly.CorLibrary, inProgress.Prepend(this), constraintTypes, inherited: false, ignoresNullableContext: constraintClause.IgnoresNullableContext, this.DeclaringCompilation, diagnostics); + return this.ResolveBounds(this.ContainingAssembly.CorLibrary, inProgress.Prepend(this), constraintTypes, inherited: false, this.DeclaringCompilation, diagnostics); } - internal TypeParameterConstraintKind GetDeclaredConstraints(bool canIgnoreNullableContext) + private TypeParameterConstraintKind GetConstraintKinds() { - var constraintClause = GetTypeParameterConstraintClause(canIgnoreNullableContext); - return constraintClause.Constraints; + var constraintKinds = _owner.GetTypeParameterConstraintKinds(); + return constraintKinds.IsEmpty ? TypeParameterConstraintKind.None : constraintKinds[Ordinal]; } } @@ -864,6 +889,15 @@ public override bool HasValueTypeConstraint } } + public override bool IsValueTypeFromConstraintTypes + { + get + { + var typeParameter = this.OverriddenTypeParameter; + return ((object)typeParameter != null) && (typeParameter.IsValueTypeFromConstraintTypes || CalculateIsValueTypeFromConstraintTypes(ConstraintTypesNoUseSiteDiagnostics)); + } + } + public override bool HasReferenceTypeConstraint { get @@ -873,6 +907,15 @@ public override bool HasReferenceTypeConstraint } } + public override bool IsReferenceTypeFromConstraintTypes + { + get + { + var typeParameter = this.OverriddenTypeParameter; + return ((object)typeParameter != null) && (typeParameter.IsReferenceTypeFromConstraintTypes || CalculateIsReferenceTypeFromConstraintTypes(ConstraintTypesNoUseSiteDiagnostics)); + } + } + internal override bool? ReferenceTypeConstraintIsNullable { get @@ -912,7 +955,7 @@ protected override ImmutableArray ContainerTypeParameters get { return this.Owner.TypeParameters; } } - protected override TypeParameterBounds ResolveBounds(ConsList inProgress, bool canIgnoreNullableContext, DiagnosticBag diagnostics) + protected override TypeParameterBounds ResolveBounds(ConsList inProgress, DiagnosticBag diagnostics) { var typeParameter = this.OverriddenTypeParameter; if ((object)typeParameter == null) @@ -923,7 +966,7 @@ protected override TypeParameterBounds ResolveBounds(ConsList diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceUserDefinedOperatorSymbolBase.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceUserDefinedOperatorSymbolBase.cs index a984d38e911e1..47a5b148584c2 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceUserDefinedOperatorSymbolBase.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceUserDefinedOperatorSymbolBase.cs @@ -645,8 +645,11 @@ public sealed override ImmutableArray TypeParameters get { return ImmutableArray.Empty; } } - public sealed override ImmutableArray GetTypeParameterConstraintClauses(bool canIgnoreNullableContext) - => ImmutableArray.Empty; + public sealed override ImmutableArray> GetTypeParameterConstraintTypes() + => ImmutableArray>.Empty; + + public sealed override ImmutableArray GetTypeParameterConstraintKinds() + => ImmutableArray.Empty; public sealed override RefKind RefKind { diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/TypeParameterConstraintClause.cs b/src/Compilers/CSharp/Portable/Symbols/Source/TypeParameterConstraintClause.cs index 34feda2ecab28..930b231cf98b9 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/TypeParameterConstraintClause.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/TypeParameterConstraintClause.cs @@ -39,6 +39,13 @@ internal enum TypeParameterConstraintKind NotNull = 0x80, Default = 0x100, + /// + /// mismatch is detected during merging process for partial type declarations. + /// + PartialMismatch = 0x200, + ValueTypeFromConstraintTypes = 0x400, // Not set if any flag from AllValueTypeKinds is set + ReferenceTypeFromConstraintTypes = 0x800, + /// /// All bits involved into describing various aspects of 'class' constraint. /// @@ -63,21 +70,18 @@ internal sealed class TypeParameterConstraintClause { internal static readonly TypeParameterConstraintClause Empty = new TypeParameterConstraintClause( TypeParameterConstraintKind.None, - ImmutableArray.Empty, - ignoresNullableContext: false); + ImmutableArray.Empty); internal static readonly TypeParameterConstraintClause ObliviousNullabilityIfReferenceType = new TypeParameterConstraintClause( TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType, - ImmutableArray.Empty, - ignoresNullableContext: false); + ImmutableArray.Empty); internal static TypeParameterConstraintClause Create( TypeParameterConstraintKind constraints, - ImmutableArray constraintTypes, - bool ignoresNullableContext) + ImmutableArray constraintTypes) { Debug.Assert(!constraintTypes.IsDefault); - if (!ignoresNullableContext && constraintTypes.IsEmpty) + if (constraintTypes.IsEmpty) { switch (constraints) { @@ -89,13 +93,12 @@ internal static TypeParameterConstraintClause Create( } } - return new TypeParameterConstraintClause(constraints, constraintTypes, ignoresNullableContext); + return new TypeParameterConstraintClause(constraints, constraintTypes); } private TypeParameterConstraintClause( TypeParameterConstraintKind constraints, - ImmutableArray constraintTypes, - bool ignoresNullableContext) + ImmutableArray constraintTypes) { #if DEBUG switch (constraints & TypeParameterConstraintKind.AllReferenceTypeKinds) @@ -111,55 +114,38 @@ private TypeParameterConstraintClause( } Debug.Assert((constraints & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) == 0 || - (constraints & ~(TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType | TypeParameterConstraintKind.Constructor | TypeParameterConstraintKind.Default)) == 0); + (constraints & ~(TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType | TypeParameterConstraintKind.Constructor | TypeParameterConstraintKind.Default | + TypeParameterConstraintKind.PartialMismatch | TypeParameterConstraintKind.ValueTypeFromConstraintTypes | TypeParameterConstraintKind.ReferenceTypeFromConstraintTypes)) == 0); #endif this.Constraints = constraints; this.ConstraintTypes = constraintTypes; - this.IgnoresNullableContext = ignoresNullableContext; } public readonly TypeParameterConstraintKind Constraints; public readonly ImmutableArray ConstraintTypes; - public readonly bool IgnoresNullableContext; - - internal bool IsEmpty => Constraints == TypeParameterConstraintKind.None && ConstraintTypes.IsEmpty; - /// - /// Adjust unresolved instances of which represent nullable type parameters - /// of the within constraint types according to the IsValueType state inferred - /// from the constraint types. - /// - internal static void AdjustConstraintTypes(Symbol container, ImmutableArray typeParameters, - ArrayBuilder constraintClauses, - ref IReadOnlyDictionary isValueTypeOverride) + internal static SmallDictionary BuildIsValueTypeMap(Symbol container, ImmutableArray typeParameters, + ImmutableArray constraintClauses) { - Debug.Assert(constraintClauses.Count == typeParameters.Length); + Debug.Assert(constraintClauses.Length == typeParameters.Length); - if (isValueTypeOverride == null) - { - var isValueTypeOverrideBuilder = new Dictionary(typeParameters.Length, ReferenceEqualityComparer.Instance); + var isValueTypeMap = new SmallDictionary(ReferenceEqualityComparer.Instance); - foreach (TypeParameterSymbol typeParameter in typeParameters) - { - isValueType(typeParameter, constraintClauses, isValueTypeOverrideBuilder, ConsList.Empty); - } - - isValueTypeOverride = new ReadOnlyDictionary(isValueTypeOverrideBuilder); - } - - foreach (TypeParameterConstraintClause constraintClause in constraintClauses) + foreach (TypeParameterSymbol typeParameter in typeParameters) { - adjustConstraintTypes(container, constraintClause.ConstraintTypes, isValueTypeOverride); + isValueType(typeParameter, constraintClauses, isValueTypeMap, ConsList.Empty); } - static bool isValueType(TypeParameterSymbol thisTypeParameter, ArrayBuilder constraintClauses, Dictionary isValueTypeOverrideBuilder, ConsList inProgress) + return isValueTypeMap; + + static bool isValueType(TypeParameterSymbol thisTypeParameter, ImmutableArray constraintClauses, SmallDictionary isValueTypeMap, ConsList inProgress) { if (inProgress.ContainsReference(thisTypeParameter)) { return false; } - if (isValueTypeOverrideBuilder.TryGetValue(thisTypeParameter, out bool knownIsValueType)) + if (isValueTypeMap.TryGetValue(thisTypeParameter, out bool knownIsValueType)) { return knownIsValueType; } @@ -183,7 +169,7 @@ static bool isValueType(TypeParameterSymbol thisTypeParameter, ArrayBuilder constraintTypes, IReadOnlyDictionary isValueTypeOverride) - { - foreach (var constraintType in constraintTypes) - { - constraintType.VisitType(null, (type, args, unused2) => - { - if (type.DefaultType is TypeParameterSymbol typeParameterSymbol && typeParameterSymbol.ContainingSymbol == (object)args.container) - { - type.TryForceResolve(args.isValueTypeOverride[typeParameterSymbol]); - } - return false; - }, typePredicate: null, arg: (container, isValueTypeOverride), canDigThroughNullable: false, useDefaultType: true); - } - } } - } - internal static class TypeParameterConstraintClauseExtensions - { - internal static bool HasValue(this ImmutableArray constraintClauses, bool canIgnoreNullableContext) + internal static SmallDictionary BuildIsReferenceTypeFromConstraintTypesMap(Symbol container, ImmutableArray typeParameters, + ImmutableArray constraintClauses) { - if (constraintClauses.IsDefault) + Debug.Assert(constraintClauses.Length == typeParameters.Length); + + var isReferenceTypeFromConstraintTypesMap = new SmallDictionary(ReferenceEqualityComparer.Instance); + + foreach (TypeParameterSymbol typeParameter in typeParameters) { - return false; + isReferenceTypeFromConstraintTypes(typeParameter, constraintClauses, isReferenceTypeFromConstraintTypesMap, ConsList.Empty); } - return canIgnoreNullableContext || !constraintClauses.IgnoresNullableContext(); - } - internal static bool IgnoresNullableContext(this ImmutableArray constraintClauses) - { - return constraintClauses.Any(clause => clause.IgnoresNullableContext); - } + return isReferenceTypeFromConstraintTypesMap; - internal static bool ContainsOnlyEmptyConstraintClauses(this ImmutableArray constraintClauses) - { - return constraintClauses.All(clause => clause.IsEmpty); - } - - // Returns true if constraintClauses was updated with value. - // Returns false if constraintClauses already had a value with sufficient 'IgnoresNullableContext' - // or was updated to a value with sufficient 'IgnoresNullableContext' on another thread. - internal static bool InterlockedUpdate(ref ImmutableArray constraintClauses, ImmutableArray value) - { - bool canIgnoreNullableContext = value.IgnoresNullableContext(); - while (true) + static bool isReferenceTypeFromConstraintTypes(TypeParameterSymbol thisTypeParameter, ImmutableArray constraintClauses, + SmallDictionary isReferenceTypeFromConstraintTypesMap, ConsList inProgress) { - var comparand = constraintClauses; - if (comparand.HasValue(canIgnoreNullableContext)) + if (inProgress.ContainsReference(thisTypeParameter)) { return false; } - if (ImmutableInterlocked.InterlockedCompareExchange(ref constraintClauses, value, comparand) == comparand) + + if (isReferenceTypeFromConstraintTypesMap.TryGetValue(thisTypeParameter, out bool knownIsReferenceTypeFromConstraintTypes)) { - return true; + return knownIsReferenceTypeFromConstraintTypes; } + + TypeParameterConstraintClause constraintClause = constraintClauses[thisTypeParameter.Ordinal]; + + bool result = false; + + Symbol container = thisTypeParameter.ContainingSymbol; + inProgress = inProgress.Prepend(thisTypeParameter); + + foreach (TypeWithAnnotations constraintType in constraintClause.ConstraintTypes) + { + TypeSymbol type = constraintType.IsResolved ? constraintType.Type : constraintType.DefaultType; + + if (type is TypeParameterSymbol typeParameter) + { + if ((object)typeParameter.ContainingSymbol == (object)container) + { + if (isReferenceTypeFromConstraintTypes(typeParameter, constraintClauses, isReferenceTypeFromConstraintTypesMap, inProgress)) + { + result = true; + break; + } + } + else if (typeParameter.IsReferenceTypeFromConstraintTypes) + { + result = true; + break; + } + } + else if (TypeParameterSymbol.NonTypeParameterConstraintImpliesReferenceType(type)) + { + result = true; + break; + } + } + + isReferenceTypeFromConstraintTypesMap.Add(thisTypeParameter, result); + return result; } } } diff --git a/src/Compilers/CSharp/Portable/Symbols/SubstitutedTypeParameterSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/SubstitutedTypeParameterSymbol.cs index 884fd877f90a7..829ec2092306b 100644 --- a/src/Compilers/CSharp/Portable/Symbols/SubstitutedTypeParameterSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/SubstitutedTypeParameterSymbol.cs @@ -96,10 +96,10 @@ public override string Name } } - internal override ImmutableArray GetConstraintTypes(ConsList inProgress, bool canIgnoreNullableContext) + internal override ImmutableArray GetConstraintTypes(ConsList inProgress) { var constraintTypes = ArrayBuilder.GetInstance(); - _map.SubstituteConstraintTypesDistinctWithoutModifiers(_underlyingTypeParameter, _underlyingTypeParameter.GetConstraintTypes(inProgress, canIgnoreNullableContext), constraintTypes, null); + _map.SubstituteConstraintTypesDistinctWithoutModifiers(_underlyingTypeParameter, _underlyingTypeParameter.GetConstraintTypes(inProgress), constraintTypes, null); TypeWithAnnotations bestObjectConstraint = default; @@ -116,7 +116,7 @@ internal override ImmutableArray GetConstraintTypes(ConsLis if (bestObjectConstraint.HasType) { // See if we need to put Object! or Object~ back in order to preserve nullability information for the type parameter. - if (!canIgnoreNullableContext && ConstraintsHelper.IsObjectConstraintSignificant(CalculateIsNotNullableFromNonTypeConstraints(), bestObjectConstraint)) + if (ConstraintsHelper.IsObjectConstraintSignificant(CalculateIsNotNullableFromNonTypeConstraints(), bestObjectConstraint)) { Debug.Assert(!HasNotNullConstraint && !HasValueTypeConstraint); if (constraintTypes.Count == 0) @@ -159,7 +159,7 @@ internal override bool? IsNotNullable else if (!HasNotNullConstraint && !HasValueTypeConstraint && !HasReferenceTypeConstraint) { var constraintTypes = ArrayBuilder.GetInstance(); - _map.SubstituteConstraintTypesDistinctWithoutModifiers(_underlyingTypeParameter, _underlyingTypeParameter.GetConstraintTypes(ConsList.Empty, canIgnoreNullableContext: false), constraintTypes, null); + _map.SubstituteConstraintTypesDistinctWithoutModifiers(_underlyingTypeParameter, _underlyingTypeParameter.GetConstraintTypes(ConsList.Empty), constraintTypes, null); return IsNotNullableFromConstraintTypes(constraintTypes.ToImmutableAndFree()); } diff --git a/src/Compilers/CSharp/Portable/Symbols/Symbol.cs b/src/Compilers/CSharp/Portable/Symbols/Symbol.cs index ec741991e73b1..e063f8227ea6c 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Symbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Symbol.cs @@ -1020,7 +1020,7 @@ private DiagnosticInfo GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo() internal bool DeriveUseSiteDiagnosticFromType(ref DiagnosticInfo result, TypeWithAnnotations type, AllowedRequiredModifierType allowedRequiredModifierType) { - return (type.DefaultType.TypeKind != TypeKind.TypeParameter && DeriveUseSiteDiagnosticFromType(ref result, type.Type)) || + return DeriveUseSiteDiagnosticFromType(ref result, type.Type) || DeriveUseSiteDiagnosticFromCustomModifiers(ref result, type.CustomModifiers, allowedRequiredModifierType); } diff --git a/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordEqualityContractProperty.cs b/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordEqualityContractProperty.cs index 805ae55024e5f..c412dde69ec17 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordEqualityContractProperty.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordEqualityContractProperty.cs @@ -17,34 +17,29 @@ internal sealed class SynthesizedRecordEqualityContractProperty : SourceProperty { internal const string PropertyName = "EqualityContract"; - public SynthesizedRecordEqualityContractProperty( - SourceMemberContainerTypeSymbol containingType, - DiagnosticBag diagnostics) + public SynthesizedRecordEqualityContractProperty(SourceMemberContainerTypeSymbol containingType) : base( containingType, - binder: null, syntax: (CSharpSyntaxNode)containingType.SyntaxReferences[0].GetSyntax(), - getSyntax: (CSharpSyntaxNode)containingType.SyntaxReferences[0].GetSyntax(), - setSyntax: null, - arrowExpression: null, - interfaceSpecifier: null, + hasGetAccessor: true, + hasSetAccessor: false, + isExplicitInterfaceImplementation: false, + explicitInterfaceType: null, + aliasQualifierOpt: null, modifiers: (containingType.IsSealed, containingType.BaseTypeNoUseSiteDiagnostics.IsObjectType()) switch { (true, true) => DeclarationModifiers.Private, (false, true) => DeclarationModifiers.Protected | DeclarationModifiers.Virtual, (_, false) => DeclarationModifiers.Protected | DeclarationModifiers.Override }, - isIndexer: false, hasInitializer: false, isAutoProperty: false, - hasAccessorList: false, + isExpressionBodied: false, isInitOnly: false, RefKind.None, PropertyName, - containingType.Locations[0], - typeOpt: TypeWithAnnotations.Create(Binder.GetWellKnownType(containingType.DeclaringCompilation, WellKnownType.System_Type, diagnostics, containingType.Locations[0]), NullableAnnotation.NotAnnotated), - hasParameters: false, - diagnostics) + indexerNameAttributeLists: new SyntaxList(), + containingType.Locations[0]) { } @@ -60,59 +55,26 @@ public override SyntaxList AttributeDeclarationSyntaxList protected override Location TypeLocation => ContainingType.Locations[0]; - protected override SyntaxTokenList GetModifierTokens(SyntaxNode syntax) - => new SyntaxTokenList(); - - protected override void CheckForBlockAndExpressionBody(CSharpSyntaxNode syntax, DiagnosticBag diagnostics) - { - // Nothing to do here - } - - protected override SourcePropertyAccessorSymbol? CreateAccessorSymbol( - bool isGet, - CSharpSyntaxNode? syntax, - PropertySymbol? explicitlyImplementedPropertyOpt, - string? aliasQualifierOpt, - bool isAutoPropertyAccessor, - bool isExplicitInterfaceImplementation, - DiagnosticBag diagnostics) + protected override SourcePropertyAccessorSymbol CreateGetAccessorSymbol(bool isAutoPropertyAccessor, bool isExplicitInterfaceImplementation, PropertySymbol? explicitlyImplementedPropertyOpt, DiagnosticBag diagnostics) { - if (!isGet) - { - return null; - } - - Debug.Assert(syntax is object); - return SourcePropertyAccessorSymbol.CreateAccessorSymbol( ContainingType, this, _modifiers, ContainingType.Locations[0], - syntax, + (CSharpSyntaxNode)((SourceMemberContainerTypeSymbol)ContainingType).SyntaxReferences[0].GetSyntax(), diagnostics); } - protected override SourcePropertyAccessorSymbol CreateExpressionBodiedAccessor( - ArrowExpressionClauseSyntax syntax, - PropertySymbol? explicitlyImplementedPropertyOpt, - string? aliasQualifierOpt, - bool isExplicitInterfaceImplementation, - DiagnosticBag diagnostics) + protected override SourcePropertyAccessorSymbol CreateSetAccessorSymbol(bool isAutoPropertyAccessor, bool isExplicitInterfaceImplementation, PropertySymbol? explicitlyImplementedPropertyOpt, DiagnosticBag diagnostics) { - // There should be no expression-bodied synthesized record properties throw ExceptionUtilities.Unreachable; } - protected override ImmutableArray ComputeParameters(Binder? binder, CSharpSyntaxNode syntax, DiagnosticBag diagnostics) - { - return ImmutableArray.Empty; - } - - protected override TypeWithAnnotations ComputeType(Binder? binder, SyntaxNode syntax, DiagnosticBag diagnostics) + protected override (TypeWithAnnotations Type, ImmutableArray Parameters) MakeParametersAndBindType(DiagnosticBag diagnostics) { - // No need to worry about reporting use-site diagnostics, we already did that in the constructor - return TypeWithAnnotations.Create(DeclaringCompilation.GetWellKnownType(WellKnownType.System_Type), NullableAnnotation.NotAnnotated); + return (TypeWithAnnotations.Create(Binder.GetWellKnownType(DeclaringCompilation, WellKnownType.System_Type, diagnostics, Location), NullableAnnotation.NotAnnotated), + ImmutableArray.Empty); } protected override bool HasPointerTypeSyntactically => false; diff --git a/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordOrdinaryMethod.cs b/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordOrdinaryMethod.cs index 2303d3fbcff73..f7677dfb6beae 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordOrdinaryMethod.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordOrdinaryMethod.cs @@ -38,7 +38,9 @@ protected SynthesizedRecordOrdinaryMethod(SourceMemberContainerTypeSymbol contai protected sealed override ImmutableArray MakeTypeParameters(CSharpSyntaxNode node, DiagnosticBag diagnostics) => ImmutableArray.Empty; - public sealed override ImmutableArray GetTypeParameterConstraintClauses(bool canIgnoreNullableContext) => ImmutableArray.Empty; + public sealed override ImmutableArray> GetTypeParameterConstraintTypes() => ImmutableArray>.Empty; + + public sealed override ImmutableArray GetTypeParameterConstraintKinds() => ImmutableArray.Empty; protected sealed override void PartialMethodChecks(DiagnosticBag diagnostics) { diff --git a/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordPropertySymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordPropertySymbol.cs index 983b439df057c..4b41d02033955 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordPropertySymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordPropertySymbol.cs @@ -17,61 +17,53 @@ public SynthesizedRecordPropertySymbol( SourceMemberContainerTypeSymbol containingType, CSharpSyntaxNode syntax, ParameterSymbol backingParameter, - bool isOverride, - DiagnosticBag diagnostics) + bool isOverride) : base( containingType, - binder: null, syntax: syntax, - getSyntax: syntax, - setSyntax: syntax, - arrowExpression: null, - interfaceSpecifier: null, + hasGetAccessor: true, + hasSetAccessor: true, + isExplicitInterfaceImplementation: false, + explicitInterfaceType: null, + aliasQualifierOpt: null, modifiers: DeclarationModifiers.Public | (isOverride ? DeclarationModifiers.Override : DeclarationModifiers.None), - isIndexer: false, hasInitializer: true, // Synthesized record properties always have a synthesized initializer isAutoProperty: true, - hasAccessorList: false, + isExpressionBodied: false, isInitOnly: true, RefKind.None, backingParameter.Name, - backingParameter.Locations[0], - typeOpt: backingParameter.TypeWithAnnotations, - hasParameters: false, - diagnostics) + indexerNameAttributeLists: new SyntaxList(), + backingParameter.Locations[0]) { BackingParameter = (SourceParameterSymbol)backingParameter; } - public override IAttributeTargetSymbol AttributesOwner => BackingParameter as IAttributeTargetSymbol ?? this; protected override Location TypeLocation => ((ParameterSyntax)CSharpSyntaxNode).Type!.Location; - protected override SyntaxTokenList GetModifierTokens(SyntaxNode syntax) - => new SyntaxTokenList(); - public override SyntaxList AttributeDeclarationSyntaxList => BackingParameter.AttributeDeclarationList; - protected override void CheckForBlockAndExpressionBody(CSharpSyntaxNode syntax, DiagnosticBag diagnostics) + protected override SourcePropertyAccessorSymbol CreateGetAccessorSymbol(bool isAutoPropertyAccessor, bool isExplicitInterfaceImplementation, PropertySymbol? explicitlyImplementedPropertyOpt, DiagnosticBag diagnostics) { - // Nothing to do here + Debug.Assert(isAutoPropertyAccessor); + return CreateAccessorSymbol(isGet: true, CSharpSyntaxNode, diagnostics); } - protected override SourcePropertyAccessorSymbol CreateAccessorSymbol( - bool isGet, - CSharpSyntaxNode? syntax, - PropertySymbol? explicitlyImplementedPropertyOpt, - string? aliasQualifierOpt, - bool isAutoPropertyAccessor, - bool isExplicitInterfaceImplementation, - DiagnosticBag diagnostics) + protected override SourcePropertyAccessorSymbol CreateSetAccessorSymbol(bool isAutoPropertyAccessor, bool isExplicitInterfaceImplementation, PropertySymbol? explicitlyImplementedPropertyOpt, DiagnosticBag diagnostics) { - Debug.Assert(syntax is object); Debug.Assert(isAutoPropertyAccessor); + return CreateAccessorSymbol(isGet: false, CSharpSyntaxNode, diagnostics); + } + private SourcePropertyAccessorSymbol CreateAccessorSymbol( + bool isGet, + CSharpSyntaxNode syntax, + DiagnosticBag diagnostics) + { return SourcePropertyAccessorSymbol.CreateAccessorSymbol( isGet, usesInit: !isGet, // the setter is always init-only @@ -83,25 +75,10 @@ protected override SourcePropertyAccessorSymbol CreateAccessorSymbol( diagnostics); } - protected override SourcePropertyAccessorSymbol CreateExpressionBodiedAccessor( - ArrowExpressionClauseSyntax syntax, - PropertySymbol? explicitlyImplementedPropertyOpt, - string? aliasQualifierOpt, - bool isExplicitInterfaceImplementation, - DiagnosticBag diagnostics) - { - // There should be no expression-bodied synthesized record properties - throw ExceptionUtilities.Unreachable; - } - - protected override ImmutableArray ComputeParameters(Binder? binder, CSharpSyntaxNode syntax, DiagnosticBag diagnostics) - { - return ImmutableArray.Empty; - } - - protected override TypeWithAnnotations ComputeType(Binder? binder, SyntaxNode syntax, DiagnosticBag diagnostics) + protected override (TypeWithAnnotations Type, ImmutableArray Parameters) MakeParametersAndBindType(DiagnosticBag diagnostics) { - return BackingParameter.TypeWithAnnotations; + return (BackingParameter.TypeWithAnnotations, + ImmutableArray.Empty); } protected override bool HasPointerTypeSyntactically diff --git a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedAccessorValueParameterSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedAccessorValueParameterSymbol.cs index bd83c36a4b721..e9c197d65e885 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedAccessorValueParameterSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedAccessorValueParameterSymbol.cs @@ -23,7 +23,6 @@ internal sealed class SynthesizedAccessorValueParameterSymbol : SourceComplexPar public SynthesizedAccessorValueParameterSymbol(SourceMemberMethodSymbol accessor, TypeWithAnnotations paramType, int ordinal) : base(accessor, ordinal, paramType, RefKind.None, ParameterSymbol.ValueParameterName, accessor.Locations, syntaxRef: null, - defaultSyntaxValue: ConstantValue.Unset, // the default value can be set via [param: DefaultParameterValue] applied on the accessor isParams: false, isExtensionMethodThis: false) { diff --git a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedBackingFieldSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedBackingFieldSymbol.cs index 3f87f1e205ee2..a61a3b0842982 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedBackingFieldSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedBackingFieldSymbol.cs @@ -120,5 +120,36 @@ internal override bool HasRuntimeSpecialName public override bool IsImplicitlyDeclared => true; + + internal override void PostDecodeWellKnownAttributes(ImmutableArray boundAttributes, ImmutableArray allAttributeSyntaxNodes, DiagnosticBag diagnostics, AttributeLocation symbolPart, WellKnownAttributeData decodedData) + { + base.PostDecodeWellKnownAttributes(boundAttributes, allAttributeSyntaxNodes, diagnostics, symbolPart, decodedData); + + if (!allAttributeSyntaxNodes.IsEmpty && _property.IsAutoPropertyWithGetAccessor) + { + CheckForFieldTargetedAttribute(diagnostics); + } + } + + private void CheckForFieldTargetedAttribute(DiagnosticBag diagnostics) + { + var languageVersion = this.DeclaringCompilation.LanguageVersion; + if (languageVersion.AllowAttributesOnBackingFields()) + { + return; + } + + foreach (var attribute in AttributeDeclarationSyntaxList) + { + if (attribute.Target?.GetAttributeLocation() == AttributeLocation.Field) + { + diagnostics.Add( + new CSDiagnosticInfo(ErrorCode.WRN_AttributesOnBackingFieldsNotAvailable, + languageVersion.ToDisplayString(), + new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureAttributesOnBackingFields.RequiredVersion())), + attribute.Target.Location); + } + } + } } } diff --git a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEntryPointSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEntryPointSymbol.cs index f1326fa9a7e7c..a6dd3d145b855 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEntryPointSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEntryPointSymbol.cs @@ -310,6 +310,7 @@ private static BoundCall CreateParameterlessCall(CSharpSyntaxNode syntax, BoundE expanded: false, invokedAsExtensionMethod: false, argsToParamsOpt: default(ImmutableArray), + defaultArguments: default(BitVector), resultKind: LookupResultKind.Viable, binderOpt: null, type: method.ReturnType) @@ -355,6 +356,7 @@ internal AsyncForwardEntryPoint(CSharpCompilation compilation, NamedTypeSymbol c expanded: false, invokedAsExtensionMethod: false, argsToParamsOpt: default(ImmutableArray), + defaultArguments: default(BitVector), resultKind: LookupResultKind.Viable, binderOpt: binder, type: userMain.ReturnType) @@ -583,6 +585,7 @@ internal override BoundBlock CreateBody(DiagnosticBag diagnostics) default(ImmutableArray), false, default(ImmutableArray), + default(BitVector), null, null, null, diff --git a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedSimpleProgramEntryPointSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedSimpleProgramEntryPointSymbol.cs index 8bef9bb6b8c53..9fd6eec32669d 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedSimpleProgramEntryPointSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedSimpleProgramEntryPointSymbol.cs @@ -175,8 +175,11 @@ protected override void MethodChecks(DiagnosticBag diagnostics) internal override bool IsExpressionBodied => false; - public override ImmutableArray GetTypeParameterConstraintClauses(bool canIgnoreNullableContext) - => ImmutableArray.Empty; + public override ImmutableArray> GetTypeParameterConstraintTypes() + => ImmutableArray>.Empty; + + public override ImmutableArray GetTypeParameterConstraintKinds() + => ImmutableArray.Empty; protected override object MethodChecksLockObject => _declaration; diff --git a/src/Compilers/CSharp/Portable/Symbols/TypeParameterBounds.cs b/src/Compilers/CSharp/Portable/Symbols/TypeParameterBounds.cs index 435d243321204..2fe750c23b8e8 100644 --- a/src/Compilers/CSharp/Portable/Symbols/TypeParameterBounds.cs +++ b/src/Compilers/CSharp/Portable/Symbols/TypeParameterBounds.cs @@ -4,7 +4,6 @@ using System.Collections.Immutable; using System.Diagnostics; -using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols { @@ -18,12 +17,14 @@ internal sealed class TypeParameterBounds { public static readonly TypeParameterBounds Unset = new TypeParameterBounds(); + /// + /// Creates a "late" bound instance with all fields set. + /// public TypeParameterBounds( ImmutableArray constraintTypes, ImmutableArray interfaces, NamedTypeSymbol effectiveBaseClass, - TypeSymbol deducedBaseType, - bool ignoresNullableContext) + TypeSymbol deducedBaseType) { Debug.Assert(!constraintTypes.IsDefault); Debug.Assert(!interfaces.IsDefault); @@ -34,15 +35,14 @@ public TypeParameterBounds( this.Interfaces = interfaces; this.EffectiveBaseClass = effectiveBaseClass; this.DeducedBaseType = deducedBaseType; - this.IgnoresNullableContext = ignoresNullableContext; } private TypeParameterBounds() { + EffectiveBaseClass = null!; + DeducedBaseType = null!; } - public readonly bool IgnoresNullableContext; - /// /// The type parameters, classes, and interfaces explicitly declared as /// constraint types on the containing type parameter, with cycles removed. @@ -59,7 +59,7 @@ private TypeParameterBounds() /// /// As defined in 10.1.5 of the specification. /// - public readonly NamedTypeSymbol? EffectiveBaseClass; + public readonly NamedTypeSymbol EffectiveBaseClass; /// /// The "exact" effective base type. @@ -77,42 +77,14 @@ private TypeParameterBounds() /// When computing the deduced type we don't perform this abstraction. We keep the original constraint T. /// Deduced base type is used to check that consistency rules are satisfied. /// - public readonly TypeSymbol? DeducedBaseType; + public readonly TypeSymbol DeducedBaseType; } internal static class TypeParameterBoundsExtensions { - internal static bool HasValue(this TypeParameterBounds? boundsOpt, bool canIgnoreNullableContext) - { - if (boundsOpt == TypeParameterBounds.Unset) - { - return false; - } - if (boundsOpt == null) - { - return true; - } - return canIgnoreNullableContext || !boundsOpt.IgnoresNullableContext; - } - - // Returns true if bounds was updated with value. - // Returns false if bounds already had a value with sufficient 'IgnoresNullableContext' - // or was updated to a value with sufficient 'IgnoresNullableContext' on another thread. - internal static bool InterlockedUpdate(ref TypeParameterBounds? bounds, TypeParameterBounds? value) + internal static bool IsSet(this TypeParameterBounds boundsOpt) { - bool canIgnoreNullableContext = (value?.IgnoresNullableContext == true); - while (true) - { - var comparand = bounds; - if (comparand != TypeParameterBounds.Unset && comparand.HasValue(canIgnoreNullableContext)) - { - return false; - } - if (Interlocked.CompareExchange(ref bounds, value, comparand) == comparand) - { - return true; - } - } + return boundsOpt != TypeParameterBounds.Unset; } } } diff --git a/src/Compilers/CSharp/Portable/Symbols/TypeParameterSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/TypeParameterSymbol.cs index 0ec53119e1f2a..3eaddba504b24 100644 --- a/src/Compilers/CSharp/Portable/Symbols/TypeParameterSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/TypeParameterSymbol.cs @@ -79,15 +79,15 @@ internal virtual DiagnosticInfo GetConstraintsUseSiteErrorInfo() /// Duplicates and cycles are removed, although the collection may include /// redundant constraints where one constraint is a base type of another. /// - internal ImmutableArray GetConstraintTypesNoUseSiteDiagnostics(bool canIgnoreNullableContext) + internal ImmutableArray ConstraintTypesNoUseSiteDiagnostics { - this.EnsureAllConstraintsAreResolved(canIgnoreNullableContext); - return this.GetConstraintTypes(ConsList.Empty, canIgnoreNullableContext); + get + { + this.EnsureAllConstraintsAreResolved(); + return this.GetConstraintTypes(ConsList.Empty); + } } - internal ImmutableArray ConstraintTypesNoUseSiteDiagnostics => - GetConstraintTypesNoUseSiteDiagnostics(canIgnoreNullableContext: false); - internal ImmutableArray ConstraintTypesWithDefinitionUseSiteDiagnostics(ref HashSet useSiteDiagnostics) { var result = ConstraintTypesNoUseSiteDiagnostics; @@ -270,7 +270,7 @@ internal NamedTypeSymbol EffectiveBaseClassNoUseSiteDiagnostics { get { - this.EnsureAllConstraintsAreResolved(canIgnoreNullableContext: false); + this.EnsureAllConstraintsAreResolved(); return this.GetEffectiveBaseClass(ConsList.Empty); } } @@ -295,7 +295,7 @@ internal ImmutableArray EffectiveInterfacesNoUseSiteDiagnostics { get { - this.EnsureAllConstraintsAreResolved(canIgnoreNullableContext: false); + this.EnsureAllConstraintsAreResolved(); return this.GetInterfaces(ConsList.Empty); } } @@ -307,7 +307,7 @@ internal TypeSymbol DeducedBaseTypeNoUseSiteDiagnostics { get { - this.EnsureAllConstraintsAreResolved(canIgnoreNullableContext: false); + this.EnsureAllConstraintsAreResolved(); return this.GetDeducedBaseType(ConsList.Empty); } } @@ -364,21 +364,21 @@ internal ImmutableArray AllEffectiveInterfacesWithDefinitionUse /// type or method are resolved in a consistent order, regardless of the /// order the callers query individual type parameters. /// - internal abstract void EnsureAllConstraintsAreResolved(bool canIgnoreNullableContext); + internal abstract void EnsureAllConstraintsAreResolved(); /// /// Helper method to force type parameter constraints to be resolved. /// - protected static void EnsureAllConstraintsAreResolved(ImmutableArray typeParameters, bool canIgnoreNullableContext) + protected static void EnsureAllConstraintsAreResolved(ImmutableArray typeParameters) { foreach (var typeParameter in typeParameters) { // Invoke any method that forces constraints to be resolved. - var unused = typeParameter.GetConstraintTypes(ConsList.Empty, canIgnoreNullableContext); + var unused = typeParameter.GetConstraintTypes(ConsList.Empty); } } - internal abstract ImmutableArray GetConstraintTypes(ConsList inProgress, bool canIgnoreNullableContext); + internal abstract ImmutableArray GetConstraintTypes(ConsList inProgress); internal abstract ImmutableArray GetInterfaces(ConsList inProgress); @@ -390,9 +390,17 @@ private static bool ConstraintImpliesReferenceType(TypeSymbol constraint) { if (constraint.TypeKind == TypeKind.TypeParameter) { - return IsReferenceTypeFromConstraintTypes(((TypeParameterSymbol)constraint).GetConstraintTypesNoUseSiteDiagnostics(canIgnoreNullableContext: true)); + return ((TypeParameterSymbol)constraint).IsReferenceTypeFromConstraintTypes; } - else if (!constraint.IsReferenceType) + + return NonTypeParameterConstraintImpliesReferenceType(constraint); + } + + internal static bool NonTypeParameterConstraintImpliesReferenceType(TypeSymbol constraint) + { + Debug.Assert(constraint.TypeKind != TypeKind.TypeParameter); + + if (!constraint.IsReferenceType) { return false; } @@ -423,7 +431,7 @@ private static bool ConstraintImpliesReferenceType(TypeSymbol constraint) // > Please note that we do not check the gpReferenceTypeConstraint special constraint here // > because this property does not propagate up the constraining hierarchy. // > (e.g. "class A where S : T, where T : class" does not guarantee that S is ObjRef) - internal static bool IsReferenceTypeFromConstraintTypes(ImmutableArray constraintTypes) + internal static bool CalculateIsReferenceTypeFromConstraintTypes(ImmutableArray constraintTypes) { foreach (var constraintType in constraintTypes) { @@ -493,7 +501,7 @@ internal static bool IsReferenceTypeFromConstraintTypes(ImmutableArray constraintTypes) + internal static bool CalculateIsValueTypeFromConstraintTypes(ImmutableArray constraintTypes) { foreach (var constraintType in constraintTypes) { @@ -514,7 +522,7 @@ public sealed override bool IsReferenceType return true; } - return IsReferenceTypeFromConstraintTypes(this.GetConstraintTypesNoUseSiteDiagnostics(canIgnoreNullableContext: true)); + return IsReferenceTypeFromConstraintTypes; } } @@ -572,7 +580,7 @@ public sealed override bool IsValueType return true; } - return IsValueTypeFromConstraintTypes(this.GetConstraintTypesNoUseSiteDiagnostics(canIgnoreNullableContext: true)); + return IsValueTypeFromConstraintTypes; } } @@ -606,6 +614,8 @@ internal sealed override ObsoleteAttributeData ObsoleteAttributeData public abstract bool HasReferenceTypeConstraint { get; } + public abstract bool IsReferenceTypeFromConstraintTypes { get; } + /// /// Returns whether the reference type constraint (the 'class' constraint) should also be treated as nullable ('class?') or non-nullable (class!). /// In some cases this aspect is unknown (null value is returned). For example, when 'class' constraint is specified in a NonNullTypes(false) context. @@ -617,6 +627,8 @@ internal sealed override ObsoleteAttributeData ObsoleteAttributeData public abstract bool HasValueTypeConstraint { get; } + public abstract bool IsValueTypeFromConstraintTypes { get; } + public abstract bool HasUnmanagedTypeConstraint { get; } public abstract VarianceKind Variance { get; } @@ -626,9 +638,9 @@ internal sealed override bool GetUnificationUseSiteDiagnosticRecursive(ref Diagn return false; } - internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison, IReadOnlyDictionary isValueTypeOverrideOpt = null) + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { - return this.Equals(t2 as TypeParameterSymbol, comparison, isValueTypeOverrideOpt); + return this.Equals(t2 as TypeParameterSymbol, comparison); } internal bool Equals(TypeParameterSymbol other) @@ -636,7 +648,7 @@ internal bool Equals(TypeParameterSymbol other) return Equals(other, TypeCompareKind.ConsiderEverything); } - private bool Equals(TypeParameterSymbol other, TypeCompareKind comparison, IReadOnlyDictionary isValueTypeOverrideOpt) + private bool Equals(TypeParameterSymbol other, TypeCompareKind comparison) { if (ReferenceEquals(this, other)) { @@ -649,7 +661,7 @@ private bool Equals(TypeParameterSymbol other, TypeCompareKind comparison, IRead } // Type parameters may be equal but not reference equal due to independent alpha renamings. - return other.ContainingSymbol.ContainingType.Equals(this.ContainingSymbol.ContainingType, comparison, isValueTypeOverrideOpt); + return other.ContainingSymbol.ContainingType.Equals(this.ContainingSymbol.ContainingType, comparison); } public override int GetHashCode() diff --git a/src/Compilers/CSharp/Portable/Symbols/TypeSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/TypeSymbol.cs index 3b57b44ba16b6..bd250bbd8df86 100644 --- a/src/Compilers/CSharp/Portable/Symbols/TypeSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/TypeSymbol.cs @@ -285,13 +285,8 @@ internal bool IsEqualToOrDerivedFrom(TypeSymbol type, TypeCompareKind comparison /// What kind of comparison to use? /// You can ignore custom modifiers, ignore the distinction between object and dynamic, or ignore tuple element names differences. /// - /// - /// A map from a type parameter symbol to a boolean value that should be used as a replacement for a value returned by - /// property. Used when accessing the property for a type parameter symbol - /// that has an entry in the map is not safe and can cause a cycle. - /// /// True if the types are equivalent. - internal virtual bool Equals(TypeSymbol t2, TypeCompareKind compareKind, IReadOnlyDictionary isValueTypeOverrideOpt = null) + internal virtual bool Equals(TypeSymbol t2, TypeCompareKind compareKind) { return ReferenceEquals(this, t2); } @@ -2194,14 +2189,14 @@ internal bool Equals(TypeWithAnnotations other) throw ExceptionUtilities.Unreachable; } - public static bool Equals(TypeSymbol left, TypeSymbol right, TypeCompareKind comparison, IReadOnlyDictionary isValueTypeOverrideOpt = null) + public static bool Equals(TypeSymbol left, TypeSymbol right, TypeCompareKind comparison) { if (left is null) { return right is null; } - return left.Equals(right, comparison, isValueTypeOverrideOpt); + return left.Equals(right, comparison); } [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] diff --git a/src/Compilers/CSharp/Portable/Symbols/TypeWithAnnotations.cs b/src/Compilers/CSharp/Portable/Symbols/TypeWithAnnotations.cs index d255004489de8..e7796d6cabd64 100644 --- a/src/Compilers/CSharp/Portable/Symbols/TypeWithAnnotations.cs +++ b/src/Compilers/CSharp/Portable/Symbols/TypeWithAnnotations.cs @@ -326,7 +326,7 @@ string IFormattable.ToString(string format, IFormatProvider formatProvider) return ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat); } - public bool Equals(TypeWithAnnotations other, TypeCompareKind comparison, IReadOnlyDictionary isValueTypeOverrideOpt = null) + public bool Equals(TypeWithAnnotations other, TypeCompareKind comparison) { if (this.IsSameAs(other)) { @@ -340,7 +340,7 @@ public bool Equals(TypeWithAnnotations other, TypeCompareKind comparison, IReadO return false; } } - else if (!other.HasType || !TypeSymbolEquals(other, comparison, isValueTypeOverrideOpt)) + else if (!other.HasType || !TypeSymbolEquals(other, comparison)) { return false; } @@ -366,12 +366,7 @@ public bool Equals(TypeWithAnnotations other, TypeCompareKind comparison, IReadO } TypeSymbol type = Type; - bool isValueType; - - if (isValueTypeOverrideOpt == null || !(type is TypeParameterSymbol typeParameter) || !isValueTypeOverrideOpt.TryGetValue(typeParameter, out isValueType)) - { - isValueType = type.IsValueType && !type.IsNullableType(); - } + bool isValueType = type.IsValueType && !type.IsNullableType(); if (!isValueType) { @@ -385,15 +380,14 @@ public bool Equals(TypeWithAnnotations other, TypeCompareKind comparison, IReadO internal sealed class EqualsComparer : EqualityComparer { - internal static readonly EqualsComparer ConsiderEverythingComparer = new EqualsComparer(TypeCompareKind.ConsiderEverything, isValueTypeOverrideOpt: null); + internal static readonly EqualsComparer ConsiderEverythingComparer = new EqualsComparer(TypeCompareKind.ConsiderEverything); + internal static readonly EqualsComparer IgnoreNullableModifiersForReferenceTypesComparer = new EqualsComparer(TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); private readonly TypeCompareKind _compareKind; - private readonly IReadOnlyDictionary _isValueTypeOverrideOpt; - public EqualsComparer(TypeCompareKind compareKind, IReadOnlyDictionary isValueTypeOverrideOpt) + public EqualsComparer(TypeCompareKind compareKind) { _compareKind = compareKind; - _isValueTypeOverrideOpt = isValueTypeOverrideOpt; } public override int GetHashCode(TypeWithAnnotations obj) @@ -411,12 +405,12 @@ public override bool Equals(TypeWithAnnotations x, TypeWithAnnotations y) { return !y.HasType; } - return x.Equals(y, _compareKind, _isValueTypeOverrideOpt); + return x.Equals(y, _compareKind); } } - internal bool TypeSymbolEquals(TypeWithAnnotations other, TypeCompareKind comparison, IReadOnlyDictionary isValueTypeOverrideOpt) => - _extensions.TypeSymbolEquals(this, other, comparison, isValueTypeOverrideOpt); + internal bool TypeSymbolEquals(TypeWithAnnotations other, TypeCompareKind comparison) => + _extensions.TypeSymbolEquals(this, other, comparison); public bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet checkedTypes) { @@ -468,20 +462,16 @@ internal TypeWithAnnotations SubstituteTypeCore(AbstractTypeMap typeMap) return newTypeWithModifiers; } + if (newTypeWithModifiers.Type is PlaceholderTypeArgumentSymbol) + { + return newTypeWithModifiers; + } + NullableAnnotation newAnnotation; - Debug.Assert(!IsIndexedTypeParameter(newTypeWithModifiers.DefaultType) || newTypeWithModifiers.NullableAnnotation.IsOblivious()); + Debug.Assert(!IsIndexedTypeParameter(newTypeWithModifiers.Type) || newTypeWithModifiers.NullableAnnotation.IsOblivious()); - if (newTypeWithModifiers.NullableAnnotation.IsAnnotated()) - { - if (newTypeWithModifiers._extensions is LazyNullableTypeParameter) - { - Debug.Assert(newCustomModifiers.IsEmpty); - return newTypeWithModifiers; - } - newAnnotation = NullableAnnotation.Annotated; - } - else if (NullableAnnotation.IsAnnotated()) + if (NullableAnnotation.IsAnnotated() || newTypeWithModifiers.NullableAnnotation.IsAnnotated()) { newAnnotation = NullableAnnotation.Annotated; } @@ -520,9 +510,9 @@ internal TypeWithAnnotations SubstituteTypeCore(AbstractTypeMap typeMap) public void ReportDiagnosticsIfObsolete(Binder binder, SyntaxNode syntax, DiagnosticBag diagnostics) => _extensions.ReportDiagnosticsIfObsolete(this, binder, syntax, diagnostics); - private bool TypeSymbolEqualsCore(TypeWithAnnotations other, TypeCompareKind comparison, IReadOnlyDictionary isValueTypeOverrideOpt) + private bool TypeSymbolEqualsCore(TypeWithAnnotations other, TypeCompareKind comparison) { - return Type.Equals(other.Type, comparison, isValueTypeOverrideOpt); + return Type.Equals(other.Type, comparison); } private void ReportDiagnosticsIfObsoleteCore(Binder binder, SyntaxNode syntax, DiagnosticBag diagnostics) @@ -853,7 +843,7 @@ internal static Extensions CreateLazy(CSharpCompilation compilation, TypeWithAnn internal abstract TypeWithAnnotations WithTypeAndModifiers(TypeWithAnnotations type, TypeSymbol typeSymbol, ImmutableArray customModifiers); - internal abstract bool TypeSymbolEquals(TypeWithAnnotations type, TypeWithAnnotations other, TypeCompareKind comparison, IReadOnlyDictionary isValueTypeOverrideOpt); + internal abstract bool TypeSymbolEquals(TypeWithAnnotations type, TypeWithAnnotations other, TypeCompareKind comparison); internal abstract TypeWithAnnotations SubstituteType(TypeWithAnnotations type, AbstractTypeMap typeMap); internal abstract void ReportDiagnosticsIfObsolete(TypeWithAnnotations type, Binder binder, SyntaxNode syntax, DiagnosticBag diagnostics); @@ -905,9 +895,9 @@ internal override TypeWithAnnotations AsNotNullableReferenceType(TypeWithAnnotat return CreateNonLazyType(defaultType, defaultType.IsNullableType() ? type.NullableAnnotation : NullableAnnotation.NotAnnotated, _customModifiers); } - internal override bool TypeSymbolEquals(TypeWithAnnotations type, TypeWithAnnotations other, TypeCompareKind comparison, IReadOnlyDictionary isValueTypeOverrideOpt) + internal override bool TypeSymbolEquals(TypeWithAnnotations type, TypeWithAnnotations other, TypeCompareKind comparison) { - return type.TypeSymbolEqualsCore(other, comparison, isValueTypeOverrideOpt); + return type.TypeSymbolEqualsCore(other, comparison); } internal override TypeWithAnnotations SubstituteType(TypeWithAnnotations type, AbstractTypeMap typeMap) @@ -1057,16 +1047,16 @@ internal override void ReportDiagnosticsIfObsolete(TypeWithAnnotations type, Bin } } - internal override bool TypeSymbolEquals(TypeWithAnnotations type, TypeWithAnnotations other, TypeCompareKind comparison, IReadOnlyDictionary isValueTypeOverrideOpt) + internal override bool TypeSymbolEquals(TypeWithAnnotations type, TypeWithAnnotations other, TypeCompareKind comparison) { var otherLazy = other._extensions as LazyNullableTypeParameter; if ((object)otherLazy != null) { - return _underlying.TypeSymbolEquals(otherLazy._underlying, comparison, isValueTypeOverrideOpt); + return _underlying.TypeSymbolEquals(otherLazy._underlying, comparison); } - return type.TypeSymbolEqualsCore(other, comparison, isValueTypeOverrideOpt); + return type.TypeSymbolEqualsCore(other, comparison); } internal override void TryForceResolve(bool asValueType) diff --git a/src/Compilers/CSharp/Portable/Symbols/UnboundGenericType.cs b/src/Compilers/CSharp/Portable/Symbols/UnboundGenericType.cs index ba4b3f729734c..30e4a67d87744 100644 --- a/src/Compilers/CSharp/Portable/Symbols/UnboundGenericType.cs +++ b/src/Compilers/CSharp/Portable/Symbols/UnboundGenericType.cs @@ -99,10 +99,8 @@ internal override DiagnosticInfo ErrorInfo } } - internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison, IReadOnlyDictionary? isValueTypeOverrideOpt = null) + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { - Debug.Assert(isValueTypeOverrideOpt == null); - if ((object)t2 == (object)this) { return true; diff --git a/src/Compilers/CSharp/Portable/Symbols/Wrapped/WrappedTypeParameterSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Wrapped/WrappedTypeParameterSymbol.cs index 41d27d889f2ec..f1bd03a8c40ea 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Wrapped/WrappedTypeParameterSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Wrapped/WrappedTypeParameterSymbol.cs @@ -77,6 +77,14 @@ public override bool HasReferenceTypeConstraint } } + public override bool IsReferenceTypeFromConstraintTypes + { + get + { + return _underlyingTypeParameter.IsReferenceTypeFromConstraintTypes || CalculateIsReferenceTypeFromConstraintTypes(ConstraintTypesNoUseSiteDiagnostics); + } + } + internal override bool? ReferenceTypeConstraintIsNullable { get @@ -109,6 +117,14 @@ public override bool HasValueTypeConstraint } } + public override bool IsValueTypeFromConstraintTypes + { + get + { + return _underlyingTypeParameter.IsValueTypeFromConstraintTypes || CalculateIsValueTypeFromConstraintTypes(ConstraintTypesNoUseSiteDiagnostics); + } + } + public override VarianceKind Variance { get @@ -146,9 +162,9 @@ public override string Name return _underlyingTypeParameter.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); } - internal override void EnsureAllConstraintsAreResolved(bool canIgnoreNullableContext) + internal override void EnsureAllConstraintsAreResolved() { - _underlyingTypeParameter.EnsureAllConstraintsAreResolved(canIgnoreNullableContext); + _underlyingTypeParameter.EnsureAllConstraintsAreResolved(); } public override ImmutableArray GetAttributes() diff --git a/src/Compilers/CSharp/Test/CommandLine/CommandLineTests.cs b/src/Compilers/CSharp/Test/CommandLine/CommandLineTests.cs index c59f2a2a10d9e..ec9d6162d20eb 100644 --- a/src/Compilers/CSharp/Test/CommandLine/CommandLineTests.cs +++ b/src/Compilers/CSharp/Test/CommandLine/CommandLineTests.cs @@ -12350,6 +12350,70 @@ public void TestWarnAsErrorMinusDoesNotEnableDisabledByDefaultAnalyzers(Diagnost } } + [WorkItem(49446, "https://github.com/dotnet/roslyn/issues/49446")] + [Theory] + // Verify '/warnaserror-:ID' prevents escalation to 'Error' when config file bumps severity to 'Warning' + [InlineData(false, DiagnosticSeverity.Info, DiagnosticSeverity.Warning, DiagnosticSeverity.Error)] + [InlineData(true, DiagnosticSeverity.Info, DiagnosticSeverity.Warning, DiagnosticSeverity.Warning)] + // Verify '/warnaserror-:ID' prevents escalation to 'Error' when default severity is 'Warning' and no config file setting is specified. + [InlineData(false, DiagnosticSeverity.Warning, null, DiagnosticSeverity.Error)] + [InlineData(true, DiagnosticSeverity.Warning, null, DiagnosticSeverity.Warning)] + // Verify '/warnaserror-:ID' prevents escalation to 'Error' when default severity is 'Warning' and config file bumps severity to 'Error' + [InlineData(false, DiagnosticSeverity.Warning, DiagnosticSeverity.Error, DiagnosticSeverity.Error)] + [InlineData(true, DiagnosticSeverity.Warning, DiagnosticSeverity.Error, DiagnosticSeverity.Warning)] + // Verify '/warnaserror-:ID' has no effect when default severity is 'Info' and config file bumps severity to 'Error' + [InlineData(false, DiagnosticSeverity.Info, DiagnosticSeverity.Error, DiagnosticSeverity.Error)] + [InlineData(true, DiagnosticSeverity.Info, DiagnosticSeverity.Error, DiagnosticSeverity.Error)] + public void TestWarnAsErrorMinusDoesNotNullifyEditorConfig( + bool warnAsErrorMinus, + DiagnosticSeverity defaultSeverity, + DiagnosticSeverity? severityInConfigFile, + DiagnosticSeverity expectedEffectiveSeverity) + { + var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: false); + var diagnosticId = analyzer.Descriptor.Id; + + var dir = Temp.CreateDirectory(); + var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); + var additionalFlags = new[] { "/warnaserror+" }; + + if (severityInConfigFile.HasValue) + { + var severityString = DiagnosticDescriptor.MapSeverityToReport(severityInConfigFile.Value).ToAnalyzerConfigString(); + var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@" +[*.cs] +dotnet_diagnostic.{diagnosticId}.severity = {severityString}"); + + additionalFlags = additionalFlags.Append($"/analyzerconfig:{analyzerConfig.Path}").ToArray(); + } + + if (warnAsErrorMinus) + { + additionalFlags = additionalFlags.Append($"/warnaserror-:{diagnosticId}").ToArray(); + } + + int expectedWarningCount = 0, expectedErrorCount = 0; + switch (expectedEffectiveSeverity) + { + case DiagnosticSeverity.Warning: + expectedWarningCount = 1; + break; + + case DiagnosticSeverity.Error: + expectedErrorCount = 1; + break; + + default: + throw ExceptionUtilities.UnexpectedValue(expectedEffectiveSeverity); + } + + VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, + expectedWarningCount: expectedWarningCount, + expectedErrorCount: expectedErrorCount, + additionalFlags: additionalFlags, + analyzers: new[] { analyzer }); + } + [Fact] public void SourceGenerators_EmbeddedSources() { @@ -13276,8 +13340,7 @@ private void TestCompilationOptionsOverrideAnalyzerConfigCore( } } - // can't load a coreclr targeting generator on net framework / mono - [ConditionalFact(typeof(CoreClrOnly))] + [ConditionalFact(typeof(CoreClrOnly), Reason = "Can't load a coreclr targeting generator on net framework / mono")] public void TestGeneratorsCantTargetNetFramework() { var directory = Temp.CreateDirectory(); @@ -13290,7 +13353,7 @@ class C var coreGenerator = emitGenerator(".NETCoreApp,Version=v5.0"); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + coreGenerator }); - //// netstandard + // netstandard var nsGenerator = emitGenerator(".NETStandard,Version=v2.0"); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + nsGenerator }); @@ -13307,7 +13370,6 @@ class C // framework, suppressed output = VerifyOutput(directory, src, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS8850", "/analyzer:" + frameworkGenerator }); Assert.Contains("CS8033", output); - VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS8850,CS8033", "/analyzer:" + frameworkGenerator }); string emitGenerator(string targetFramework) diff --git a/src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_CallerInfoAttributes.cs b/src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_CallerInfoAttributes.cs index 02257ebdaab85..1485e83a73bba 100644 --- a/src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_CallerInfoAttributes.cs +++ b/src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_CallerInfoAttributes.cs @@ -5,7 +5,9 @@ #nullable disable using System.Collections.Immutable; +using System.Linq; using System.Text; +using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; @@ -623,7 +625,7 @@ .maxstack 8 .method public hidebysig static void LogCallerLineNumber3([opt] string lineNumber) cil managed { - .param [1] = """" + .param [1] = ""hello"" .custom instance void [mscorlib]System.Runtime.CompilerServices.CallerLineNumberAttribute::.ctor() = ( 01 00 00 00 ) // Code size 19 (0x13) .maxstack 8 @@ -666,7 +668,7 @@ public static void Main() { var expected = @" line: 7 line: 42 -line: +line: hello "; MetadataReference libReference = CompileIL(iLSource); @@ -1881,7 +1883,7 @@ public void TestRecursiveAttribute() public class Goo: Attribute { - public Goo([Goo] int y = 0) {} + public Goo([Goo] int y = 1) {} } class Test @@ -1889,11 +1891,46 @@ class Test public static void Main() { } } "; + var compilation = CreateCompilationWithMscorlib45(source, references: new MetadataReference[] { SystemRef }, options: TestOptions.ReleaseExe); + CompileAndVerify(compilation, expectedOutput: ""); - var expected = @""; + var ctor = compilation.GetMember("Goo..ctor"); + Assert.Equal(MethodKind.Constructor, ctor.MethodKind); + var attr = ctor.Parameters.Single().GetAttributes().Single(); + Assert.Equal(ctor, attr.AttributeConstructor); + Assert.Equal(1, attr.CommonConstructorArguments.Length); + // We want to ensure that we don't accidentally use default(T) instead of the real default value for the parameter. + Assert.Equal(1, attr.CommonConstructorArguments[0].Value); + } + + [Fact] + public void TestRecursiveAttribute2() + { + string source = @" +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +public class Goo: Attribute +{ + public Goo([Goo, Optional, DefaultParameterValue(1)] int y) {} +} + +class Test +{ + public static void Main() { } +} +"; var compilation = CreateCompilationWithMscorlib45(source, references: new MetadataReference[] { SystemRef }, options: TestOptions.ReleaseExe); - CompileAndVerify(compilation, expectedOutput: expected); + CompileAndVerify(compilation, expectedOutput: ""); + + var ctor = compilation.GetMember("Goo..ctor"); + Assert.Equal(MethodKind.Constructor, ctor.MethodKind); + var attr = ctor.Parameters.Single().GetAttributes()[0]; + Assert.Equal(ctor, attr.AttributeConstructor); + Assert.Equal(1, attr.CommonConstructorArguments.Length); + // We want to ensure that we don't accidentally use default(T) instead of the real default value for the parameter. + Assert.Equal(1, attr.CommonConstructorArguments[0].Value); } @@ -2754,19 +2791,22 @@ static void Main(string[] args) var compilation = CreateCompilationWithMscorlib45(new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(source, options: TestOptions.Regular7, path: @"C:\filename") }).VerifyDiagnostics( // C:\filename(7,38): error CS4018: CallerFilePathAttribute cannot be applied because there are no standard conversions from type 'string' to type 'int' // static void M1([CallerLineNumber,CallerFilePath,CallerMemberName] int i = 0) { Console.WriteLine(); } - Diagnostic(ErrorCode.ERR_NoConversionForCallerFilePathParam, "CallerFilePath").WithArguments("string", "int"), + Diagnostic(ErrorCode.ERR_NoConversionForCallerFilePathParam, "CallerFilePath").WithArguments("string", "int").WithLocation(7, 38), // C:\filename(7,53): error CS4019: CallerMemberNameAttribute cannot be applied because there are no standard conversions from type 'string' to type 'int' // static void M1([CallerLineNumber,CallerFilePath,CallerMemberName] int i = 0) { Console.WriteLine(); } - Diagnostic(ErrorCode.ERR_NoConversionForCallerMemberNameParam, "CallerMemberName").WithArguments("string", "int"), + Diagnostic(ErrorCode.ERR_NoConversionForCallerMemberNameParam, "CallerMemberName").WithArguments("string", "int").WithLocation(7, 53), // C:\filename(8,21): error CS4017: CallerLineNumberAttribute cannot be applied because there are no standard conversions from type 'int' to type 'string' // static void M2([CallerLineNumber,CallerFilePath,CallerMemberName] string s = null) { Console.WriteLine(s); } - Diagnostic(ErrorCode.ERR_NoConversionForCallerLineNumberParam, "CallerLineNumber").WithArguments("int", "string"), - // C:\filename(8,38): warning CS7074: The CallerFilePathAttribute applied to parameter 's' will have no effect. It is overridden by the CallerLineNumberAttribute. + Diagnostic(ErrorCode.ERR_NoConversionForCallerLineNumberParam, "CallerLineNumber").WithArguments("int", "string").WithLocation(8, 21), + // C:\filename(8,38): warning CS7082: The CallerFilePathAttribute applied to parameter 's' will have no effect. It is overridden by the CallerLineNumberAttribute. // static void M2([CallerLineNumber,CallerFilePath,CallerMemberName] string s = null) { Console.WriteLine(s); } - Diagnostic(ErrorCode.WRN_CallerLineNumberPreferredOverCallerFilePath, "CallerFilePath").WithArguments("s"), - // C:\filename(8,53): warning CS7073: The CallerMemberNameAttribute applied to parameter 's' will have no effect. It is overridden by the CallerLineNumberAttribute. + Diagnostic(ErrorCode.WRN_CallerLineNumberPreferredOverCallerFilePath, "CallerFilePath").WithArguments("s").WithLocation(8, 38), + // C:\filename(8,53): warning CS7081: The CallerMemberNameAttribute applied to parameter 's' will have no effect. It is overridden by the CallerLineNumberAttribute. // static void M2([CallerLineNumber,CallerFilePath,CallerMemberName] string s = null) { Console.WriteLine(s); } - Diagnostic(ErrorCode.WRN_CallerLineNumberPreferredOverCallerMemberName, "CallerMemberName").WithArguments("s")); + Diagnostic(ErrorCode.WRN_CallerLineNumberPreferredOverCallerMemberName, "CallerMemberName").WithArguments("s").WithLocation(8, 53), + // C:\filename(13,9): error CS0029: Cannot implicitly convert type 'int' to 'string' + // M2(); + Diagnostic(ErrorCode.ERR_NoImplicitConv, "M2()").WithArguments("int", "string").WithLocation(13, 9)); } [WorkItem(604367, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/604367")] diff --git a/src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_WellKnownAttributes.cs b/src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_WellKnownAttributes.cs index ff00e6018820e..cd51a90fd556c 100644 --- a/src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_WellKnownAttributes.cs +++ b/src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_WellKnownAttributes.cs @@ -1846,13 +1846,13 @@ static void Goo([Optional][DefaultParameterValue(DayOfWeek.Monday)] Enum x) static void Main() { - Goo(); + Goo(); // 1 } }"; var comp = CreateCompilation(source); - comp.VerifyEmitDiagnostics( - // (13,9): error CS0029: Cannot implicitly convert type 'int' to 'Enum' - // Goo(); + comp.VerifyDiagnostics( + // (13,9): error CS0029: Cannot implicitly convert type 'int' to 'System.Enum' + // Goo(); // 1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "Goo()").WithArguments("int", "System.Enum").WithLocation(13, 9)); } @@ -10301,7 +10301,7 @@ public static int Main() #region SkipLocalsInitAttribute - private CompilationVerifier CompileAndVerifyWithSkipLocalsInit(string src, CSharpParseOptions parseOptions = null) + private CompilationVerifier CompileAndVerifyWithSkipLocalsInit(string src, CSharpCompilationOptions options, CSharpParseOptions parseOptions = null, Verification verify = Verification.Fails) { const string skipLocalsInitDef = @" namespace System.Runtime.CompilerServices @@ -10311,8 +10311,13 @@ public class SkipLocalsInitAttribute : System.Attribute } }"; - var comp = CreateCompilation(new[] { src, skipLocalsInitDef }, options: TestOptions.UnsafeReleaseDll, parseOptions: parseOptions); - return CompileAndVerify(comp, verify: Verification.Fails); + var comp = CreateCompilation(new[] { src, skipLocalsInitDef }, options: options, parseOptions: parseOptions); + return CompileAndVerify(comp, verify: verify); + } + + private CompilationVerifier CompileAndVerifyWithSkipLocalsInit(string src, CSharpParseOptions parseOptions = null, Verification verify = Verification.Fails) + { + return CompileAndVerifyWithSkipLocalsInit(src, TestOptions.UnsafeReleaseDll, parseOptions, verify); } [Fact] @@ -11216,6 +11221,48 @@ void local() Assert.False(verifier.HasLocalsInit("C.g__local|0_0")); } + [Fact, WorkItem(49434, "https://github.com/dotnet/roslyn/issues/49434")] + public void SkipLocalsInit_Module_TopLevelStatements() + { + var source = @" +using System.Runtime.CompilerServices; + +[module: SkipLocalsInit] + +var w = 1; +w = w + w + w; + +void local() +{ + var x = 1; + x = x + x + x; +} +"; + + var verifier = CompileAndVerifyWithSkipLocalsInit(source, TestOptions.UnsafeReleaseExe); + Assert.False(verifier.HasLocalsInit("")); + Assert.False(verifier.HasLocalsInit("$.<
$>g__local|0_0")); + } + + [Fact, WorkItem(49434, "https://github.com/dotnet/roslyn/issues/49434")] + public void SkipLocalsInit_Module_TopLevelStatements_WithoutAttribute() + { + var source = @" +var w = 1; +w = w + w + w; + +void local() +{ + var x = 1; + x = x + x + x; +} +"; + + var verifier = CompileAndVerifyWithSkipLocalsInit(source, TestOptions.UnsafeReleaseExe, verify: Verification.Passes); + Assert.True(verifier.HasLocalsInit("")); + Assert.True(verifier.HasLocalsInit("$.<
$>g__local|0_0")); + } + [Fact] public void SkipLocalsInit_BaseMethodWrapper() { diff --git a/src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenRefReadonlyReturnTests.cs b/src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenRefReadonlyReturnTests.cs index 4600a839406e5..06bc726ca1ada 100644 --- a/src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenRefReadonlyReturnTests.cs +++ b/src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenRefReadonlyReturnTests.cs @@ -1094,7 +1094,10 @@ ref readonly int Test() var comp = CreateCompilationWithMscorlib45(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( - // (6,20): error CS8521: Cannot use a result of 'Program.M(in int)' in this context because it may expose variables referenced by parameter 'x' outside of their declaration scope + // (6,20): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference + // return ref M(); + Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "M()").WithLocation(6, 20), + // (6,20): error CS8347: Cannot use a result of 'Program.M(in int)' in this context because it may expose variables referenced by parameter 'x' outside of their declaration scope // return ref M(); Diagnostic(ErrorCode.ERR_EscapeCall, "M()").WithArguments("Program.M(in int)", "x").WithLocation(6, 20) ); diff --git a/src/Compilers/CSharp/Test/Emit/CodeGen/IndexerTests.cs b/src/Compilers/CSharp/Test/Emit/CodeGen/IndexerTests.cs index d7e412621bced..962aad44400e0 100644 --- a/src/Compilers/CSharp/Test/Emit/CodeGen/IndexerTests.cs +++ b/src/Compilers/CSharp/Test/Emit/CodeGen/IndexerTests.cs @@ -1132,6 +1132,58 @@ .maxstack 5 "); } + [Fact] + public void IndexerOverrideNotAllAccessors_DefaultParameterValues() + { + var text = @" +using System; + +class Base +{ + public virtual int this[int x, int y = 1] + { + get + { + Console.WriteLine(""Base.get y: "" + y); + return y; + } + set { Console.WriteLine(""Base.set y: "" + y); } + } +} + +class Override : Base +{ + public override int this[int x, int y = 2] + { + set { Console.WriteLine(""Override.set y: "" + y); } + } +} + +class Program +{ + static void Main() + { + Base b = new Base(); + _ = b[0]; + b[0] = 0; + + Override o = new Override(); + _ = o[0]; + o[0] = 0; + o[0] += 0; + } +} +"; + CompileAndVerify(text, expectedOutput: +@"Base.get y: 1 +Base.set y: 1 +Base.get y: 1 +Override.set y: 2 +Base.get y: 1 +Override.set y: 1 +"); + } + #endregion Lowering } } diff --git a/src/Compilers/CSharp/Test/Emit/Emit/EmitMetadataTests.cs b/src/Compilers/CSharp/Test/Emit/Emit/EmitMetadataTests.cs index a38eb81dda40e..1853d88758217 100644 --- a/src/Compilers/CSharp/Test/Emit/Emit/EmitMetadataTests.cs +++ b/src/Compilers/CSharp/Test/Emit/Emit/EmitMetadataTests.cs @@ -1294,7 +1294,7 @@ private static void VerifyAutoProperty(PropertySymbol property, bool isFromSourc { if (property is SourcePropertySymbol sourceProperty) { - Assert.True(sourceProperty.IsAutoProperty); + Assert.True(sourceProperty.IsAutoPropertyWithGetAccessor); } } else diff --git a/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IArgument.cs b/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IArgument.cs index 58bf91d5150af..84f620363205f 100644 --- a/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IArgument.cs +++ b/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IArgument.cs @@ -1201,6 +1201,64 @@ static bool M2( VerifyOperationTreeAndDiagnosticsForTest(source, expectedOperationTree, TargetFramework.Mscorlib46, expectedDiagnostics); } + [Fact] + public void DefaultArgument_CallerInfo_BadParameterType() + { + var source0 = @" +using System.Runtime.CompilerServices; + +public class C0 +{ + public static void M0([CallerLineNumber] string s = ""hello"") { } // 1 +} +"; + + var source1 = @" +public class C1 +{ + public static void M1() + { + /**/C0.M0()/**/; // 2 + } +} +"; + var expectedOperationTree = @" +IInvocationOperation (void C0.M0([System.String s = ""hello""])) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'C0.M0()') + Instance Receiver: + null + Arguments(1): + IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'C0.M0()') + IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'C0.M0()') + Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + Operand: + ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6, IsInvalid, IsImplicit) (Syntax: 'C0.M0()') + InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) +"; + var expectedDiagnostics0And1 = new[] + { + // (6,28): error CS4017: CallerLineNumberAttribute cannot be applied because there are no standard conversions from type 'int' to type 'string' + // public static void M0([CallerLineNumber] string s = "hello") { } // 1 + Diagnostic(ErrorCode.ERR_NoConversionForCallerLineNumberParam, "CallerLineNumber").WithArguments("int", "string").WithLocation(6, 28), + // (6,19): error CS0029: Cannot implicitly convert type 'int' to 'string' + // /**/C0.M0()/**/; // 2 + Diagnostic(ErrorCode.ERR_NoImplicitConv, "C0.M0()").WithArguments("int", "string").WithLocation(6, 19), + }; + + VerifyOperationTreeAndDiagnosticsForTest(CreateCompilation(new[] { source1, source0 }), expectedOperationTree, expectedDiagnostics0And1); + + var expectedDiagnostics1 = new[] + { + // (6,19): error CS0029: Cannot implicitly convert type 'int' to 'string' + // /**/C0.M0()/**/; // 2 + Diagnostic(ErrorCode.ERR_NoImplicitConv, "C0.M0()").WithArguments("int", "string").WithLocation(6, 19) + }; + var lib0 = CreateCompilation(source0).ToMetadataReference(); + VerifyOperationTreeAndDiagnosticsForTest(CreateCompilation(new[] { source1 }, references: new[] { lib0 }), expectedOperationTree, expectedDiagnostics1); + + CreateCompilation(new[] { source1 }, references: new[] { lib0 }).VerifyEmitDiagnostics(expectedDiagnostics1); + } + [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ExtraArgument() @@ -1359,40 +1417,244 @@ void M() VerifyOperationTreeAndDiagnosticsForTest(source, expectedOperationTree, TargetFramework.Mscorlib45, expectedDiagnostics); } + /// + /// See for a similar scenario for involving a bad constant value from metadata. + /// [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void InvalidConversionForDefaultArgument_InSource() { - string source = @" -class P + var source0 = @" +public class C0 { - void M1() + public static void M0(int x = ""string"") { } // 1 +} +"; + var source1 = @" +public class C1 +{ + public static void M1() { - /**/M2()/**/; + /**/C0.M0()/**/; } - - void M2(int x = ""string"") - { } } "; - string expectedOperationTree = @" -IInvocationOperation ( void P.M2([System.Int32 x = default(System.Int32)])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2()') + // Parameter default values in source produce ConstantValue.Bad when they fail to convert to the parameter type, + // and when we use that to create a default argument, we just fall back to default(ParameterType). + // This has the effect of reducing cascading diagnostics when a parameter default value is bad in source. + + // On the other hand, if `void M2(int)` came from metadata (i.e. hand-written malformed IL), we would produce a string ConstantValue for it, + // and the operation tree would contain a bad conversion to int with an operand of type string. We also produce a compilation error for the bad conversion. + var expectedOperationTree0And1 = @" +IInvocationOperation (void C0.M0([System.Int32 x = default(System.Int32)])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'C0.M0()') Instance Receiver: - IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') + null Arguments(1): - IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') - IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'M2()') - Children(0) + IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'C0.M0()') + IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'C0.M0()') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; - var expectedDiagnostics = new DiagnosticDescription[] { - // CS1750: A value of type 'string' cannot be used as a default parameter because there are no standard conversions to type 'int' - // void M2(int x = "string") - Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "x").WithArguments("string", "int") + var expectedDiagnostics0 = new DiagnosticDescription[] + { + // (4,31): error CS1750: A value of type 'string' cannot be used as a default parameter because there are no standard conversions to type 'int' + // public static void M0(int x = "string") { } // 1 + Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "x").WithArguments("string", "int").WithLocation(4, 31) }; - VerifyOperationTreeAndDiagnosticsForTest(source, expectedOperationTree, expectedDiagnostics); + var comp = CreateCompilation(new[] { source1, source0 }); + VerifyOperationTreeAndDiagnosticsForTest(comp, expectedOperationTree0And1, expectedDiagnostics0); + comp.VerifyEmitDiagnostics(expectedDiagnostics0); + + var comp0 = CreateCompilation(source0); + comp0.VerifyEmitDiagnostics(expectedDiagnostics0); + + var comp1 = CreateCompilation(source1, references: new[] { comp0.ToMetadataReference() }); + VerifyOperationTreeAndDiagnosticsForTest(comp1, expectedOperationTree0And1, DiagnosticDescription.None); + comp1.VerifyEmitDiagnostics(DiagnosticDescription.None); + } + + [CompilerTrait(CompilerFeature.IOperation)] + [Fact] + public void ValidConversionForDefaultArgument_DateTime() + { + var source0 = @" +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +public class C0 +{ + public static void M0([Optional, DateTimeConstant(634953547672667479L)] DateTime x) { } +} +"; + var source1 = @" +public class C1 +{ + public static void M1() + { + /**/C0.M0()/**/; + } +} +"; + var expectedOperationTree0And1 = @" +IInvocationOperation (void C0.M0([System.DateTime x])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'C0.M0()') + Instance Receiver: + null + Arguments(1): + IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'C0.M0()') + ILiteralOperation (OperationKind.Literal, Type: System.DateTime, Constant: 02/01/2013 22:32:47, IsImplicit) (Syntax: 'C0.M0()') + InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) +"; + + var comp = CreateCompilation(new[] { source1, source0 }); + VerifyOperationTreeAndDiagnosticsForTest(comp, expectedOperationTree0And1, DiagnosticDescription.None); + comp.VerifyEmitDiagnostics(); + + var comp0 = CreateCompilation(source0); + comp0.VerifyEmitDiagnostics(); + + var comp1 = CreateCompilation(source1, references: new[] { comp0.ToMetadataReference() }); + VerifyOperationTreeAndDiagnosticsForTest(comp1, expectedOperationTree0And1, DiagnosticDescription.None); + comp1.VerifyEmitDiagnostics(DiagnosticDescription.None); + } + + [CompilerTrait(CompilerFeature.IOperation)] + [Fact] + public void InvalidConversionForDefaultArgument_DateTime() + { + var source0 = @" +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +public class C0 +{ + public static void M0([Optional, DateTimeConstant(634953547672667479L)] string x) { } +} +"; + var source1 = @" +public class C1 +{ + public static void M1() + { + /**/C0.M0()/**/; + } +} +"; + // Note that DateTime constants which fail to convert to the parameter type are silently replaced with default(T). + var expectedOperationTree0And1 = @" +IInvocationOperation (void C0.M0([System.String x])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'C0.M0()') + Instance Receiver: + null + Arguments(1): + IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'C0.M0()') + IDefaultValueOperation (OperationKind.DefaultValue, Type: System.String, Constant: null, IsImplicit) (Syntax: 'C0.M0()') + InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) +"; + + var comp = CreateCompilation(new[] { source1, source0 }); + VerifyOperationTreeAndDiagnosticsForTest(comp, expectedOperationTree0And1, DiagnosticDescription.None); + comp.VerifyEmitDiagnostics(); + + var comp0 = CreateCompilation(source0); + comp0.VerifyEmitDiagnostics(); + + var comp1 = CreateCompilation(source1, references: new[] { comp0.ToMetadataReference() }); + VerifyOperationTreeAndDiagnosticsForTest(comp1, expectedOperationTree0And1, DiagnosticDescription.None); + comp1.VerifyEmitDiagnostics(DiagnosticDescription.None); + } + + [CompilerTrait(CompilerFeature.IOperation)] + [Fact] + public void ValidConversionForDefaultArgument_Decimal() + { + var source0 = @" +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +public class C0 +{ + public static void M0([Optional, DecimalConstant(0, 0, 0, 0, 50)] decimal x) { } +} +"; + var source1 = @" +public class C1 +{ + public static void M1() + { + /**/C0.M0()/**/; + } +} +"; + var expectedOperationTree0And1 = @" +IInvocationOperation (void C0.M0([System.Decimal x = 50])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'C0.M0()') + Instance Receiver: + null + Arguments(1): + IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'C0.M0()') + ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 50, IsImplicit) (Syntax: 'C0.M0()') + InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) +"; + + var comp = CreateCompilation(new[] { source1, source0 }); + VerifyOperationTreeAndDiagnosticsForTest(comp, expectedOperationTree0And1, DiagnosticDescription.None); + comp.VerifyEmitDiagnostics(); + + var comp0 = CreateCompilation(source0); + comp0.VerifyEmitDiagnostics(); + + var comp1 = CreateCompilation(source1, references: new[] { comp0.ToMetadataReference() }); + VerifyOperationTreeAndDiagnosticsForTest(comp1, expectedOperationTree0And1, DiagnosticDescription.None); + comp1.VerifyEmitDiagnostics(DiagnosticDescription.None); + } + + [CompilerTrait(CompilerFeature.IOperation)] + [Fact] + public void InvalidConversionForDefaultArgument_Decimal() + { + var source0 = @" +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +public class C0 +{ + public static void M0([Optional, DecimalConstant(0, 0, 0, 0, 50)] string x) { } +} +"; + var source1 = @" +public class C1 +{ + public static void M1() + { + /**/C0.M0()/**/; + } +} +"; + // Note that decimal constants which fail to convert to the parameter type are silently replaced with default(T). + var expectedOperationTree0And1 = @" +IInvocationOperation (void C0.M0([System.String x = 50])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'C0.M0()') + Instance Receiver: + null + Arguments(1): + IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'C0.M0()') + IDefaultValueOperation (OperationKind.DefaultValue, Type: System.String, Constant: null, IsImplicit) (Syntax: 'C0.M0()') + InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) +"; + + var comp = CreateCompilation(new[] { source1, source0 }); + VerifyOperationTreeAndDiagnosticsForTest(comp, expectedOperationTree0And1, DiagnosticDescription.None); + comp.VerifyEmitDiagnostics(); + + var comp0 = CreateCompilation(source0); + comp0.VerifyEmitDiagnostics(); + + var comp1 = CreateCompilation(source1, references: new[] { comp0.ToMetadataReference() }); + VerifyOperationTreeAndDiagnosticsForTest(comp1, expectedOperationTree0And1, DiagnosticDescription.None); + comp1.VerifyEmitDiagnostics(DiagnosticDescription.None); } [CompilerTrait(CompilerFeature.IOperation)] @@ -1525,10 +1787,14 @@ void M1() } "; string expectedOperationTree = @" -IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[10]') - Children(2): - IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid) (Syntax: 'this') - ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') +IPropertyReferenceOperation: System.Int32 P.this[System.Int32 index] { set; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'this[10]') + Instance Receiver: + IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid) (Syntax: 'this') + Arguments(1): + IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: index) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '10') + ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') + InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(12,27): error CS0154: The property or indexer 'P.this[int]' cannot be used in this context because it lacks the get accessor @@ -1559,10 +1825,14 @@ void M1() } "; string expectedOperationTree = @" -IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[10]') - Children(2): - IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid) (Syntax: 'this') - ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') +IPropertyReferenceOperation: System.Int32 P.this[System.Int32 index] { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'this[10]') + Instance Receiver: + IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid) (Syntax: 'this') + Arguments(1): + IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: index) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '10') + ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') + InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = new DiagnosticDescription[] { @@ -2102,19 +2372,24 @@ public void M2() } "; string expectedOperationTree = @" -IInvocationOperation ( void P.M1([System.Int32 s = ""abc""])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'p.M1()') +IInvocationOperation ( void P.M1([System.Int32 s = ""abc""])) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'p.M1()') Instance Receiver: - ILocalReferenceOperation: p (OperationKind.LocalReference, Type: P) (Syntax: 'p') + ILocalReferenceOperation: p (OperationKind.LocalReference, Type: P, IsInvalid) (Syntax: 'p') Arguments(1): - IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'p.M1()') - IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'p.M1()') + IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'p.M1()') + IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'p.M1()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: - ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""abc"", IsImplicit) (Syntax: 'p.M1()') + ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""abc"", IsInvalid, IsImplicit) (Syntax: 'p.M1()') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; - var expectedDiagnostics = DiagnosticDescription.None; + var expectedDiagnostics = new[] + { + // file.cs(7,20): error CS0029: Cannot implicitly convert type 'string' to 'int' + // /**/p.M1()/**/; + Diagnostic(ErrorCode.ERR_NoImplicitConv, "p.M1()").WithArguments("string", "int").WithLocation(7, 20) + }; VerifyOperationTreeAndDiagnosticsForTestWithIL(csharp, il, expectedOperationTree, expectedDiagnostics); } @@ -2142,9 +2417,10 @@ static void M2(bool? x = true) null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'M2()') - IInvalidOperation (OperationKind.Invalid, Type: System.Boolean[missing]?, IsInvalid, IsImplicit) (Syntax: 'M2()') - Children(1): - ILiteralOperation (OperationKind.Literal, Type: System.Boolean[missing], Constant: True, IsInvalid, IsImplicit) (Syntax: 'M2()') + IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean[missing]?, IsInvalid, IsImplicit) (Syntax: 'M2()') + Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + Operand: + ILiteralOperation (OperationKind.Literal, Type: System.Boolean[missing], Constant: True, IsInvalid, IsImplicit) (Syntax: 'M2()') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; @@ -2201,9 +2477,10 @@ static P M1() IObjectCreationOperation (Constructor: P..ctor([System.Boolean[missing]? x = true])) (OperationKind.ObjectCreation, Type: P, IsInvalid) (Syntax: 'new P()') Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'new P()') - IInvalidOperation (OperationKind.Invalid, Type: System.Boolean[missing]?, IsInvalid, IsImplicit) (Syntax: 'new P()') - Children(1): - ILiteralOperation (OperationKind.Literal, Type: System.Boolean[missing], Constant: True, IsInvalid, IsImplicit) (Syntax: 'new P()') + IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean[missing]?, IsInvalid, IsImplicit) (Syntax: 'new P()') + Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + Operand: + ILiteralOperation (OperationKind.Literal, Type: System.Boolean[missing], Constant: True, IsInvalid, IsImplicit) (Syntax: 'new P()') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: @@ -2274,9 +2551,10 @@ void M1() InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'this[0]') - IInvalidOperation (OperationKind.Invalid, Type: System.Int32[missing]?, IsInvalid, IsImplicit) (Syntax: 'this[0]') - Children(1): - ILiteralOperation (OperationKind.Literal, Type: System.Int32[missing], Constant: 5, IsInvalid, IsImplicit) (Syntax: 'this[0]') + IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32[missing]?, IsInvalid, IsImplicit) (Syntax: 'this[0]') + Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + Operand: + ILiteralOperation (OperationKind.Literal, Type: System.Int32[missing], Constant: 5, IsInvalid, IsImplicit) (Syntax: 'this[0]') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; @@ -2550,8 +2828,7 @@ static void M2(int x, S s = 0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(1)') - IInvalidOperation (OperationKind.Invalid, Type: S, IsImplicit) (Syntax: 'M2(1)') - Children(0) + IDefaultValueOperation (OperationKind.DefaultValue, Type: S, IsImplicit) (Syntax: 'M2(1)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; @@ -2565,7 +2842,9 @@ static void M2(int x, S s = 0) Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "s").WithArguments("int", "S").WithLocation(9, 29) }; - VerifyOperationTreeAndDiagnosticsForTest(source, expectedOperationTree, expectedDiagnostics); + var comp = CreateCompilation(source); + VerifyOperationTreeForTest(comp, expectedOperationTree); + comp.VerifyEmitDiagnostics(expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] @@ -2593,8 +2872,7 @@ static P M1() InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'new P(1)') - IInvalidOperation (OperationKind.Invalid, Type: S, IsImplicit) (Syntax: 'new P(1)') - Children(0) + IDefaultValueOperation (OperationKind.DefaultValue, Type: S, IsImplicit) (Syntax: 'new P(1)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: @@ -2610,7 +2888,9 @@ static P M1() Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "s").WithArguments("int", "S").WithLocation(9, 16) }; - VerifyOperationTreeAndDiagnosticsForTest(source, expectedOperationTree, expectedDiagnostics); + var comp = CreateCompilation(source); + VerifyOperationTreeForTest(comp, expectedOperationTree); + comp.VerifyEmitDiagnostics(expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] @@ -2643,8 +2923,7 @@ void M1() InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'this[0]') - IInvalidOperation (OperationKind.Invalid, Type: S, IsImplicit) (Syntax: 'this[0]') - Children(0) + IDefaultValueOperation (OperationKind.DefaultValue, Type: S, IsImplicit) (Syntax: 'this[0]') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; @@ -2658,7 +2937,9 @@ void M1() Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "s").WithArguments("int", "S").WithLocation(5, 34) }; - VerifyOperationTreeAndDiagnosticsForTest(source, expectedOperationTree, expectedDiagnostics); + var comp = CreateCompilation(source); + VerifyOperationTreeForTest(comp, expectedOperationTree); + comp.VerifyEmitDiagnostics(expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] @@ -2695,7 +2976,7 @@ class G InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(1)') - ILiteralOperation (OperationKind.Literal, Type: G, Constant: null, IsImplicit) (Syntax: 'M2(1)') + IDefaultValueOperation (OperationKind.DefaultValue, Type: G, Constant: null, IsImplicit) (Syntax: 'M2(1)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; @@ -3339,14 +3620,41 @@ static void M2(int? x = 10) { } null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') - IObjectCreationOperation (Constructor: System.Int32?..ctor(System.Int32 value)) (OperationKind.ObjectCreation, Type: System.Int32?, IsImplicit) (Syntax: 'M2()') - Arguments(1): - IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') - ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: 'M2()') - InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) - OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) - Initializer: - null + IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'M2()') + Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + Operand: + ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: 'M2()') + InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) +"; + var expectedDiagnostics = DiagnosticDescription.None; + VerifyOperationTreeAndDiagnosticsForTest(source, expectedOperationTree, expectedDiagnostics, useLatestFrameworkReferences: true); + } + + [CompilerTrait(CompilerFeature.IOperation)] + [Theory] + [InlineData("null")] + [InlineData("default")] + [InlineData("default(int?)")] + public void NullDefaultValueForNullableParameterType(string defaultValue) + { + string source = @" +class P +{ + static void M1() + { + /**/M2()/**/; + } + static void M2(int? x = " + defaultValue + @") { } +} +"; + string expectedOperationTree = @" +IInvocationOperation (void P.M2([System.Int32? x = null])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2()') + Instance Receiver: + null + Arguments(1): + IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') + IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Int32?, IsImplicit) (Syntax: 'M2()') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; @@ -3477,9 +3785,10 @@ P M1() InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: '[0]') - IInvalidOperation (OperationKind.Invalid, Type: System.Int32[missing]?, IsInvalid, IsImplicit) (Syntax: '[0]') - Children(1): - ILiteralOperation (OperationKind.Literal, Type: System.Int32[missing], Constant: 0, IsInvalid, IsImplicit) (Syntax: '[0]') + IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32[missing]?, IsInvalid, IsImplicit) (Syntax: '[0]') + Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + Operand: + ILiteralOperation (OperationKind.Literal, Type: System.Int32[missing], Constant: 0, IsInvalid, IsImplicit) (Syntax: '[0]') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: @@ -3667,8 +3976,7 @@ P M1() InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '[0]') - IInvalidOperation (OperationKind.Invalid, Type: S, IsImplicit) (Syntax: '[0]') - Children(0) + IDefaultValueOperation (OperationKind.DefaultValue, Type: S, IsImplicit) (Syntax: '[0]') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: @@ -3684,7 +3992,9 @@ P M1() Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "s").WithArguments("int", "S").WithLocation(5, 30) }; - VerifyOperationTreeAndDiagnosticsForTest(source, expectedOperationTree, expectedDiagnostics); + var comp = CreateCompilation(source); + VerifyOperationTreeForTest(comp, expectedOperationTree); + comp.VerifyEmitDiagnostics(expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] @@ -3699,17 +4009,16 @@ public struct MyStruct static void M2() { /**/M1();/**/ } } "; - + // Note that we fall back to a literal 'null' argument here because it's our general handling for bad default parameter values in source. string expectedOperationTree = @" IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M1();') - Expression: + Expression: IInvocationOperation (void MyStruct.M1([MyStruct? s = null])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M1()') - Instance Receiver: + Instance Receiver: null - Arguments(1): - IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M1()') - IInvalidOperation (OperationKind.Invalid, Type: MyStruct?, IsImplicit) (Syntax: 'M1()') - Children(0) + Arguments(1): + IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M1()') + IDefaultValueOperation (OperationKind.DefaultValue, Type: MyStruct?, IsImplicit) (Syntax: 'M1()') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; @@ -3721,7 +4030,9 @@ public struct MyStruct Diagnostic(ErrorCode.ERR_NoConversionForNubDefaultParam, "s").WithArguments("MyStruct", "s").WithLocation(4, 30) }; - VerifyOperationTreeAndDiagnosticsForTest(source, expectedOperationTree, expectedDiagnostics); + var comp = CreateCompilation(source); + VerifyOperationTreeForTest(comp, expectedOperationTree); + comp.VerifyEmitDiagnostics(expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] diff --git a/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IInvocationOperation.cs b/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IInvocationOperation.cs index f1430b381b326..d8565db64e062 100644 --- a/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IInvocationOperation.cs +++ b/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IInvocationOperation.cs @@ -516,7 +516,7 @@ void M2(object o1, object o2, object o3 = null) { } InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: o3) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(o2: o3, ... ? o1 : o2)') - ILiteralOperation (OperationKind.Literal, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'M2(o2: o3, ... ? o1 : o2)') + IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'M2(o2: o3, ... ? o1 : o2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) diff --git a/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IObjectCreationExpression.cs b/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IObjectCreationExpression.cs index 5821ea97c0719..547831e7ad7ae 100644 --- a/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IObjectCreationExpression.cs +++ b/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IObjectCreationExpression.cs @@ -1230,7 +1230,7 @@ public void Add(int i, object o = null) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '1') - ILiteralOperation (OperationKind.Literal, Type: System.Object, Constant: null, IsImplicit) (Syntax: '1') + IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Object, Constant: null, IsImplicit) (Syntax: '1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IInvocationOperation ( void C.Add(System.Int32 i, [System.Object o = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '2') @@ -1242,7 +1242,7 @@ public void Add(int i, object o = null) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '2') - ILiteralOperation (OperationKind.Literal, Type: System.Object, Constant: null, IsImplicit) (Syntax: '2') + IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Object, Constant: null, IsImplicit) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IInvocationOperation ( void C.Add(System.Int32 i, [System.Object o = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '3') @@ -1254,7 +1254,7 @@ public void Add(int i, object o = null) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '3') - ILiteralOperation (OperationKind.Literal, Type: System.Object, Constant: null, IsImplicit) (Syntax: '3') + IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Object, Constant: null, IsImplicit) (Syntax: '3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; @@ -2610,7 +2610,7 @@ public void Add(int i, object o = null) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '1') - ILiteralOperation (OperationKind.Literal, Type: System.Object, Constant: null, IsImplicit) (Syntax: '1') + IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Object, Constant: null, IsImplicit) (Syntax: '1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IInvocationOperation ( void C.Add(System.Int32 i, [System.Object o = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '2') @@ -2622,7 +2622,7 @@ public void Add(int i, object o = null) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '2') - ILiteralOperation (OperationKind.Literal, Type: System.Object, Constant: null, IsImplicit) (Syntax: '2') + IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Object, Constant: null, IsImplicit) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IInvocationOperation ( void C.Add(System.Int32 i, [System.Object o = null])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '3') @@ -2634,7 +2634,7 @@ public void Add(int i, object o = null) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: o) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '3') - ILiteralOperation (OperationKind.Literal, Type: System.Object, Constant: null, IsImplicit) (Syntax: '3') + IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Object, Constant: null, IsImplicit) (Syntax: '3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; diff --git a/src/Compilers/CSharp/Test/Semantic/Diagnostics/OperationAnalyzerTests.cs b/src/Compilers/CSharp/Test/Semantic/Diagnostics/OperationAnalyzerTests.cs index 9dab97ae753bf..a9bc194f86d55 100644 --- a/src/Compilers/CSharp/Test/Semantic/Diagnostics/OperationAnalyzerTests.cs +++ b/src/Compilers/CSharp/Test/Semantic/Diagnostics/OperationAnalyzerTests.cs @@ -1828,7 +1828,6 @@ void M( Diagnostic("Literal", @"""hello""").WithArguments(@"""hello""").WithLocation(14, 22), Diagnostic("Literal", "null").WithArguments("null").WithLocation(15, 20), Diagnostic("Literal", "M()").WithArguments("M()").WithLocation(18, 9), - Diagnostic("Literal", "M()").WithArguments("M()").WithLocation(18, 9), Diagnostic("Literal", "M()").WithArguments("M()").WithLocation(18, 9)); } diff --git a/src/Compilers/CSharp/Test/Semantic/Semantics/ImplicitObjectCreationTests.cs b/src/Compilers/CSharp/Test/Semantic/Semantics/ImplicitObjectCreationTests.cs index 32574cf00b2ee..6064591f7d277 100644 --- a/src/Compilers/CSharp/Test/Semantic/Semantics/ImplicitObjectCreationTests.cs +++ b/src/Compilers/CSharp/Test/Semantic/Semantics/ImplicitObjectCreationTests.cs @@ -4388,5 +4388,39 @@ public void Test(A a) Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("A.M(B)", "A.M(string)").WithLocation(8, 11) ); } + + [Fact, WorkItem(49547, "https://github.com/dotnet/roslyn/issues/49547")] + public void CallerMemberNameAttributeWithImplicitObjectCreation() + { + string source = @" +using System; +using System.Runtime.CompilerServices; + +class Foo +{ + public string Caller { get; set; } + public Foo([CallerMemberName] string caller = ""?"") => Caller = caller; + public void PrintCaller() => Console.WriteLine(Caller); +} + +class Program +{ + static void Main() + { + Foo f1 = new Foo(); + f1.PrintCaller(); + + Foo f2 = new(); + f2.PrintCaller(); + } +} +"; + + var comp = CreateCompilation(source, options: TestOptions.DebugExe); + comp.VerifyDiagnostics(); + CompileAndVerify(comp, expectedOutput: +@"Main +Main"); + } } } diff --git a/src/Compilers/CSharp/Test/Semantic/Semantics/LocalFunctionTests.cs b/src/Compilers/CSharp/Test/Semantic/Semantics/LocalFunctionTests.cs index a6093aefccba3..cccfeaf746d39 100644 --- a/src/Compilers/CSharp/Test/Semantic/Semantics/LocalFunctionTests.cs +++ b/src/Compilers/CSharp/Test/Semantic/Semantics/LocalFunctionTests.cs @@ -2632,18 +2632,21 @@ class Program { static void Main(string[] args) { - void CallerMemberName([CallerMemberName] int s = 2) + void CallerMemberName([CallerMemberName] int s = 2) // 1 { Console.WriteLine(s); } - CallerMemberName(); + CallerMemberName(); // 2 } } "; CreateCompilationWithMscorlib45AndCSharp(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (9,32): error CS4019: CallerMemberNameAttribute cannot be applied because there are no standard conversions from type 'string' to type 'int' - // void CallerMemberName([CallerMemberName] int s = 2) - Diagnostic(ErrorCode.ERR_NoConversionForCallerMemberNameParam, "CallerMemberName").WithArguments("string", "int").WithLocation(9, 32)); + // void CallerMemberName([CallerMemberName] int s = 2) // 1 + Diagnostic(ErrorCode.ERR_NoConversionForCallerMemberNameParam, "CallerMemberName").WithArguments("string", "int").WithLocation(9, 32), + // (13,9): error CS0029: Cannot implicitly convert type 'string' to 'int' + // CallerMemberName(); // 2 + Diagnostic(ErrorCode.ERR_NoImplicitConv, "CallerMemberName()").WithArguments("string", "int").WithLocation(13, 9)); } [WorkItem(10708, "https://github.com/dotnet/roslyn/issues/10708")] diff --git a/src/Compilers/CSharp/Test/Semantic/Semantics/NamedAndOptionalTests.cs b/src/Compilers/CSharp/Test/Semantic/Semantics/NamedAndOptionalTests.cs index 1d3c3c2b7bfb9..1e693525e773c 100644 --- a/src/Compilers/CSharp/Test/Semantic/Semantics/NamedAndOptionalTests.cs +++ b/src/Compilers/CSharp/Test/Semantic/Semantics/NamedAndOptionalTests.cs @@ -1350,6 +1350,47 @@ static void Main() } } + [ConditionalFact(typeof(DesktopOnly))] + public void IUnknownConstant_MissingType() + { + var source = @" +using System.Runtime.InteropServices; +using System.Runtime.CompilerServices; + +class C +{ + static void M0([Optional, MarshalAs(UnmanagedType.Interface)] object param) { } + static void M1([Optional, IUnknownConstant] object param) { } + static void M2([Optional, IDispatchConstant] object param) { } + static void M3([Optional] object param) { } + + static void M() + { + M0(); + M1(); + M2(); + M3(); + } +} +"; + CompileAndVerify(source).VerifyDiagnostics(); + + var comp = CreateCompilation(source); + comp.MakeMemberMissing(WellKnownMember.System_Runtime_InteropServices_UnknownWrapper__ctor); + comp.MakeMemberMissing(WellKnownMember.System_Runtime_InteropServices_DispatchWrapper__ctor); + comp.MakeMemberMissing(WellKnownMember.System_Type__Missing); + comp.VerifyDiagnostics( + // (15,9): error CS0656: Missing compiler required member 'System.Runtime.InteropServices.UnknownWrapper..ctor' + // M1(); + Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "M1()").WithArguments("System.Runtime.InteropServices.UnknownWrapper", ".ctor").WithLocation(15, 9), + // (16,9): error CS0656: Missing compiler required member 'System.Runtime.InteropServices.DispatchWrapper..ctor' + // M2(); + Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "M2()").WithArguments("System.Runtime.InteropServices.DispatchWrapper", ".ctor").WithLocation(16, 9), + // (17,9): error CS0656: Missing compiler required member 'System.Type.Missing' + // M3(); + Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "M3()").WithArguments("System.Type", "Missing").WithLocation(17, 9)); + } + [WorkItem(545329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545329")] [Fact()] public void ComOptionalRefParameter() @@ -2354,5 +2395,97 @@ public void M0(DateTime p) { } // TODO: Guess - RefEmit doesn't like DateTime constants. CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false)); } + + [Fact] + public void InvalidConversionForDefaultArgument_InIL() + { + var il = @" +.class public auto ansi beforefieldinit P + extends [mscorlib]System.Object +{ + .method public hidebysig specialname rtspecialname + instance void .ctor() cil managed + { + // Code size 8 (0x8) + .maxstack 8 + IL_0000: ldarg.0 + IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0006: nop + IL_0007: ret + } // end of method P::.ctor + + .method public hidebysig instance int32 M1([opt] int32 s) cil managed + { + .param [1] = ""abc"" + // Code size 2 (0x2) + .maxstack 8 + + IL_0000: ldarg.1 + IL_0001: ret + } // end of method P::M1 +} // end of class P +"; + + var csharp = @" +class C +{ + public static void Main() + { + P p = new P(); + System.Console.Write(p.M1()); + } +} +"; + var comp = CreateCompilationWithIL(csharp, il, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (7,31): error CS0029: Cannot implicitly convert type 'string' to 'int' + // System.Console.Write(p.M1()); + Diagnostic(ErrorCode.ERR_NoImplicitConv, "p.M1()").WithArguments("string", "int").WithLocation(7, 31)); + } + + [Fact] + public void DefaultArgument_LoopInUsage() + { + var csharp = @" +class C +{ + static object F(object param = F()) => param; // 1 +} +"; + var comp = CreateCompilation(csharp); + comp.VerifyDiagnostics( + // (4,36): error CS1736: Default parameter value for 'param' must be a compile-time constant + // static object F(object param = F()) => param; // 1 + Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "F()").WithArguments("param").WithLocation(4, 36)); + + var method = comp.GetMember("C.F"); + var param = method.Parameters.Single(); + Assert.Equal(ConstantValue.Bad, param.ExplicitDefaultConstantValue); + } + + [Fact] + public void DefaultValue_Boxing() + { + var csharp = @" +class C +{ + void M1(object obj = 1) // 1 + { + } + + C(object obj = System.DayOfWeek.Monday) // 2 + { + } +} +"; + var comp = CreateCompilation(csharp); + comp.VerifyDiagnostics( + // (4,20): error CS1763: 'obj' is of type 'object'. A default parameter value of a reference type other than string can only be initialized with null + // void M1(object obj = 1) // 1 + Diagnostic(ErrorCode.ERR_NotNullRefDefaultParameter, "obj").WithArguments("obj", "object").WithLocation(4, 20), + // (8,14): error CS1763: 'obj' is of type 'object'. A default parameter value of a reference type other than string can only be initialized with null + // C(object obj = System.DayOfWeek.Monday) // 2 + Diagnostic(ErrorCode.ERR_NotNullRefDefaultParameter, "obj").WithArguments("obj", "object").WithLocation(8, 14)); + } } } diff --git a/src/Compilers/CSharp/Test/Semantic/Semantics/NullableReferenceTypesTests.cs b/src/Compilers/CSharp/Test/Semantic/Semantics/NullableReferenceTypesTests.cs index 2257b482d2d22..3aa77e69f5f7d 100644 --- a/src/Compilers/CSharp/Test/Semantic/Semantics/NullableReferenceTypesTests.cs +++ b/src/Compilers/CSharp/Test/Semantic/Semantics/NullableReferenceTypesTests.cs @@ -6640,9 +6640,9 @@ class E { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( - // (4,46): warning CS8600: Converting null literal or possible null value to non-nullable type. + // (4,46): warning CS8625: Cannot convert null literal to non-nullable reference type. // public MyAttribute(string s, string s2 = null) { } // 1 - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(4, 46), + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 46), // (10,21): warning CS8625: Cannot convert null literal to non-nullable reference type. // [MyAttribute("str", null)] // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 21) @@ -29937,8 +29937,8 @@ class C void M2() { - _ = M1().ToString(); - _ = M1(null).ToString(); // 2 + _ = M1().ToString(); // 2 + _ = M1(null).ToString(); // 3 _ = M1(""hello"").ToString(); } } @@ -29948,8 +29948,11 @@ void M2() // (7,24): error CS1750: A value of type 'object' cannot be used as a default parameter because there are no standard conversions to type 'string' // string? M1(string? s = default(object)) => s; // 1 Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "s").WithArguments("object", "string").WithLocation(7, 24), + // (11,13): warning CS8602: Dereference of a possibly null reference. + // _ = M1().ToString(); // 2 + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1()").WithLocation(11, 13), // (12,13): warning CS8602: Dereference of a possibly null reference. - // _ = M1(null).ToString(); // 2 + // _ = M1(null).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(null)").WithLocation(12, 13)); } @@ -60761,7 +60764,7 @@ static void G(A a2, B b2) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b2").WithArguments("B", "IOut").WithLocation(19, 13)); } - [Fact] + [Fact, WorkItem(29898, "https://github.com/dotnet/roslyn/issues/29898")] public void ImplicitConversions_07() { var source = @@ -60781,13 +60784,107 @@ static void Main(object? x) var y = F(x); G(y); if (x == null) return; - var z = F(x); + var z = F(x); G(z); // warning + + var z2 = F(x); + G(z2!); } }"; var comp = CreateCompilation(new[] { source }, options: WithNonNullTypesTrue()); - // https://github.com/dotnet/roslyn/issues/29898: Report warning for `G(z)`? - comp.VerifyDiagnostics(); + comp.VerifyDiagnostics( + // (18,11): warning CS8620: Argument of type 'B' cannot be used for parameter 'a' of type 'A' in 'void C.G(A a)' due to differences in the nullability of reference types. + // G(z); // warning + Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("B", "A", "a", "void C.G(A a)").WithLocation(18, 11) + ); + } + + [Fact] + public void ImplicitConversion_Params() + { + var source = +@"class A +{ +} +class B +{ + public static implicit operator A(B b) => throw null!; +} +class C +{ + static B F(T t) => throw null!; + static void G(params A[] a) => throw null!; + + static void Main(object? x) + { + var y = F(x); + G(y); // 1 + + if (x == null) return; + var z = F(x); + G(z); + } +}"; + var comp = CreateCompilation(source, options: WithNonNullTypesTrue()); + comp.VerifyDiagnostics( + // (16,11): warning CS8620: Argument of type 'B' cannot be used for parameter 'a' of type 'A' in 'void C.G(params A[] a)' due to differences in the nullability of reference types. + // G(y); // 1 + Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("B", "A", "a", "void C.G(params A[] a)").WithLocation(16, 11) + ); + } + + [Fact] + public void ImplicitConversion_Typeless() + { + var source = @" +public struct Optional +{ + public static implicit operator Optional(T value) => throw null!; +} + +class C +{ + static void G1(Optional a) => throw null!; + static void G2(Optional a) => throw null!; + + static void M() + { + G1(null); // 1 + G2(null); + } +}"; + var comp = CreateCompilation(source, options: WithNonNullTypesTrue()); + comp.VerifyDiagnostics( + // (14,12): warning CS8625: Cannot convert null literal to non-nullable reference type. + // G1(null); // 1 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 12) + ); + } + + [Fact] + public void ImplicitConversion_Typeless_WithConstraint() + { + var source = @" +public struct Optional where T : class +{ + public static implicit operator Optional(T value) => throw null!; +} + +class C +{ + static void G(Optional a) => throw null!; + + static void M() + { + G(null); + } +}"; + var comp = CreateCompilation(source, options: WithNonNullTypesTrue()); + comp.VerifyDiagnostics( + // (13,11): warning CS8625: Cannot convert null literal to non-nullable reference type. + // G(null); + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 11) + ); } [Fact, WorkItem(41763, "https://github.com/dotnet/roslyn/issues/41763")] @@ -67604,9 +67701,9 @@ public static void F(object o = null) new[] { source0 }, options: WithNonNullTypesTrue(), parseOptions: TestOptions.Regular8); comp0.VerifyDiagnostics( - // (3,37): warning CS8600: Converting null literal or possible null value to non-nullable type. + // (3,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // public static void F(object o = null) - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(3, 37) + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(3, 37) ); var ref0 = comp0.EmitToImageReference(); @@ -67653,13 +67750,15 @@ public void ParameterDefaultValue_01() const string? S0 = null; const string? S1 = """"; static string? F() => string.Empty; - static void F0(string s = null) { } - static void F1(string s = default) { } - static void F2(string s = default(string)) { } - static void F3(string x = (string)null, string y = (string?)null) { } - static void F4(string s = S0) { } - static void F5(string s = S1) { } - static void F6(string s = F()) { } + static void F0(string s = null) { } // 1 + static void F1(string s = default) { } // 2 + static void F2(string s = default(string)) { } // 3 + static void F3( + string x = (string)null, // 4, 5 + string y = (string?)null) { } // 6 + static void F4(string s = S0) { } // 7 + static void F5(string s = S1) { } // 8 + static void F6(string s = F()) { } // 9 static void M() { F0(); @@ -67669,36 +67768,42 @@ static void M() F4(); F5(); F6(); - F0(null); + F0(null); // 10 F0(string.Empty); } }"; var comp = CreateCompilation(new[] { source }, options: WithNonNullTypesTrue()); comp.VerifyDiagnostics( - // (6,31): warning CS8600: Converting null literal or possible null value to non-nullable type. - // static void F0(string s = null) { } - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(6, 31), - // (7,31): warning CS8600: Converting null literal or possible null value to non-nullable type. - // static void F1(string s = default) { } - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(7, 31), - // (8,31): warning CS8600: Converting null literal or possible null value to non-nullable type. - // static void F2(string s = default(string)) { } - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default(string)").WithLocation(8, 31), - // (9,31): warning CS8600: Converting null literal or possible null value to non-nullable type. - // static void F3(string x = (string)null, string y = (string?)null) { } - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(9, 31), - // (9,56): warning CS8600: Converting null literal or possible null value to non-nullable type. - // static void F3(string x = (string)null, string y = (string?)null) { } - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string?)null").WithLocation(9, 56), - // (10,31): warning CS8600: Converting null literal or possible null value to non-nullable type. - // static void F4(string s = S0) { } - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "S0").WithLocation(10, 31), - // (12,31): error CS1736: Default parameter value for 's' must be a compile-time constant - // static void F6(string s = F()) { } - Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "F()").WithArguments("s").WithLocation(12, 31), - // (22,12): warning CS8625: Cannot convert null literal to non-nullable reference type. - // F0(null); - Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(22, 12) + // (6,31): warning CS8625: Cannot convert null literal to non-nullable reference type. + // static void F0(string s = null) { } // 1 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 31), + // (7,31): warning CS8625: Cannot convert null literal to non-nullable reference type. + // static void F1(string s = default) { } // 2 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(7, 31), + // (8,31): warning CS8625: Cannot convert null literal to non-nullable reference type. + // static void F2(string s = default(string)) { } // 3 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default(string)").WithLocation(8, 31), + // (10,20): warning CS8600: Converting null literal or possible null value to non-nullable type. + // string x = (string)null, // 4, 5 + Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(10, 20), + // (10,20): warning CS8625: Cannot convert null literal to non-nullable reference type. + // string x = (string)null, // 4, 5 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "(string)null").WithLocation(10, 20), + // (11,20): warning CS8625: Cannot convert null literal to non-nullable reference type. + // string y = (string?)null) { } // 6 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "(string?)null").WithLocation(11, 20), + // (12,31): warning CS8625: Cannot convert null literal to non-nullable reference type. + // static void F4(string s = S0) { } // 7 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "S0").WithLocation(12, 31), + // (13,31): warning CS8601: Possible null reference assignment. + // static void F5(string s = S1) { } // 8 + Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "S1").WithLocation(13, 31), + // (14,31): error CS1736: Default parameter value for 's' must be a compile-time constant + // static void F6(string s = F()) { } // 9 + Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "F()").WithArguments("s").WithLocation(14, 31), + // (24,12): warning CS8625: Cannot convert null literal to non-nullable reference type. + // F0(null); // 10 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(24, 12) ); } @@ -67711,44 +67816,49 @@ public void ParameterDefaultValue_02() { const string? S0 = null; static void F0(string s = null!) { } - static void F1(string x = (string)null!, string y = ((string)null)!) { } - static void F2(string x = default!, string y = default(string)!) { } + static void F1( + string x = (string)null!, + string y = ((string)null)!) { } // 1 + static void F2( + string x = default!, + string y = default(string)!) { } static void F3(string s = S0!) { } - static void F4(string x = (string)null) { } - static void F5(string? y = (string)null) { } + static void F4(string x = (string)null) { } // 2, 3 + static void F5(string? y = (string)null) { } // 4 static void M() { F0(); F1(); F2(); F3(); - F1(x: null); - F1(y: null); - F2(null!, null); + F1(x: null); // 5 + F1(y: null); // 6 + F2(null!, null); // 7 } }"; - // we should warn on the conversion of `null` to `string` in `(string)null` - // we should also suppress the warning on (string)null! - // (although suppression isn't possible in metadata, and we'll fail to round trip such default values and have the right behavior in combination with certain flow analysis attributes) - // Tracked by https://github.com/dotnet/roslyn/issues/47821 - var comp = CreateCompilation(new[] { source }, options: WithNonNullTypesTrue()); comp.VerifyDiagnostics( - // (5,31): warning CS8600: Converting null literal or possible null value to non-nullable type. - // static void F1(string x = (string)null!, string y = ((string)null)!) { } - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null!").WithLocation(5, 31), - // (8,31): warning CS8600: Converting null literal or possible null value to non-nullable type. - // static void F4(string x = (string)null) { } - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(8, 31), - // (16,15): warning CS8625: Cannot convert null literal to non-nullable reference type. - // F1(x: null); - Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 15), - // (17,15): warning CS8625: Cannot convert null literal to non-nullable reference type. - // F1(y: null); - Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(17, 15), - // (18,19): warning CS8625: Cannot convert null literal to non-nullable reference type. - // F2(null!, null); - Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(18, 19) + // (7,21): warning CS8600: Converting null literal or possible null value to non-nullable type. + // string y = ((string)null)!) { } // 1 + Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(7, 21), + // (12,31): warning CS8600: Converting null literal or possible null value to non-nullable type. + // static void F4(string x = (string)null) { } // 2, 3 + Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(12, 31), + // (12,31): warning CS8625: Cannot convert null literal to non-nullable reference type. + // static void F4(string x = (string)null) { } // 2, 3 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "(string)null").WithLocation(12, 31), + // (13,32): warning CS8600: Converting null literal or possible null value to non-nullable type. + // static void F5(string? y = (string)null) { } // 4 + Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(13, 32), + // (20,15): warning CS8625: Cannot convert null literal to non-nullable reference type. + // F1(x: null); // 5 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(20, 15), + // (21,15): warning CS8625: Cannot convert null literal to non-nullable reference type. + // F1(y: null); // 6 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(21, 15), + // (22,19): warning CS8625: Cannot convert null literal to non-nullable reference type. + // F2(null!, null); // 7 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(22, 19) ); } @@ -67762,197 +67872,197 @@ public void ParameterDefaultValue_03() class C : I { } class P { - static void F0(T t = default) { } - static void F1(T t = null) where T : class { } + static void F0(T t = default) { } // 1 + static void F1(T t = null) where T : class { } // 2 static void F2(T t = default) where T : struct { } - static void F3(T t = default) where T : new() { } - static void F4(T t = null) where T : C { } - static void F5(T t = default) where T : I { } - static void F6(T t = default) where T : U { } + static void F3(T t = default) where T : new() { } // 3 + static void F4(T t = null) where T : C { } // 4 + static void F5(T t = default) where T : I { } // 5 + static void F6(T t = default) where T : U { } // 6 static void G0() { F0(); - F0(default); + F0(default); // 7 F0(new object()); F1(); - F1(default); + F1(default); // 8 F1(new object()); F2(); F2(default); F2(2); F3(); - F3(default); + F3(default); // 9 F3(new object()); F4(); - F4(default); + F4(default); // 10 F4(new C()); F5(); - F5(default); + F5(default); // 11 F5(new C()); F6(); - F6(default); + F6(default); // 12 F6(new object()); } static void G0() { - F0(); // 0 - F0(default); // 0 - F6(); // 0 - F6(default); // 0 + F0(); + F0(default); // 13 + F6(); + F6(default); // 14 } static void G1() where T : class { - F0(); // 1 - F0(default); // 1 - F1(); // 1 - F1(default); // 1 - F6(); // 1 - F6(default); // 1 + F0(); + F0(default); // 15 + F1(); + F1(default); // 16 + F6(); + F6(default); // 17 } static void G2() where T : struct { - F0(); // 2 - F0(default); // 2 - F2(); // 2 - F2(default); // 2 - F3(); // 2 - F3(default); // 2 - F6(); // 2 - F6(default); // 2 + F0(); + F0(default); + F2(); + F2(default); + F3(); + F3(default); + F6(); + F6(default); } static void G3() where T : new() { - F0(); // 3 - F0(default); // 3 - F0(new T()); // 3 - F3(); // 3 - F3(default); // 3 - F3(new T()); // 3 - F6(); // 3 - F6(default); // 3 - F6(new T()); // 3 + F0(); + F0(default); // 18 + F0(new T()); + F3(); + F3(default); // 19 + F3(new T()); + F6(); + F6(default); // 20 + F6(new T()); } static void G4() where T : C { - F0(); // 4 - F0(default); // 4 - F1(); // 4 - F1(default); // 4 - F4(); // 4 - F4(default); // 4 - F5(); // 4 - F5(default); // 4 - F6(); // 4 - F6(default); // 4 + F0(); + F0(default); // 21 + F1(); + F1(default); // 22 + F4(); + F4(default); // 23 + F5(); + F5(default); // 24 + F6(); + F6(default); // 25 } static void G5() where T : I { - F0(); // 5 - F0(default); // 5 - F5(); // 5 - F5(default); // 5 - F6(); // 5 - F6(default); // 5 + F0(); + F0(default); // 26 + F5(); + F5(default); // 27 + F6(); + F6(default); // 28 } static void G6() where T : U { - F0(); // 6 - F0(default); // 6 - F6(); // 6 - F6(default); // 6 + F0(); + F0(default); // 29 + F6(); + F6(default); // 30 } }"; var comp = CreateCompilation(new[] { source }, options: WithNonNullTypesTrue()); comp.VerifyDiagnostics( - // (5,29): warning CS8600: Converting null literal or possible null value to non-nullable type. - // static void F0(T t = default) { } - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(5, 29), - // (6,29): warning CS8600: Converting null literal or possible null value to non-nullable type. - // static void F1(T t = null) where T : class { } - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(6, 29), - // (8,29): warning CS8600: Converting null literal or possible null value to non-nullable type. - // static void F3(T t = default) where T : new() { } - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(8, 29), - // (9,29): warning CS8600: Converting null literal or possible null value to non-nullable type. - // static void F4(T t = null) where T : C { } - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(9, 29), - // (10,29): warning CS8600: Converting null literal or possible null value to non-nullable type. - // static void F5(T t = default) where T : I { } - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(10, 29), - // (11,32): warning CS8600: Converting null literal or possible null value to non-nullable type. - // static void F6(T t = default) where T : U { } - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(11, 32), + // (5,29): warning CS8601: Possible null reference assignment. + // static void F0(T t = default) { } // 1 + Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(5, 29), + // (6,29): warning CS8625: Cannot convert null literal to non-nullable reference type. + // static void F1(T t = null) where T : class { } // 2 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 29), + // (8,29): warning CS8601: Possible null reference assignment. + // static void F3(T t = default) where T : new() { } // 3 + Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(8, 29), + // (9,29): warning CS8625: Cannot convert null literal to non-nullable reference type. + // static void F4(T t = null) where T : C { } // 4 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(9, 29), + // (10,29): warning CS8601: Possible null reference assignment. + // static void F5(T t = default) where T : I { } // 5 + Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(10, 29), + // (11,32): warning CS8601: Possible null reference assignment. + // static void F6(T t = default) where T : U { } // 6 + Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(11, 32), // (15,20): warning CS8625: Cannot convert null literal to non-nullable reference type. - // F0(default); + // F0(default); // 7 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(15, 20), // (18,20): warning CS8625: Cannot convert null literal to non-nullable reference type. - // F1(default); + // F1(default); // 8 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(18, 20), // (24,20): warning CS8625: Cannot convert null literal to non-nullable reference type. - // F3(default); + // F3(default); // 9 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(24, 20), // (27,15): warning CS8625: Cannot convert null literal to non-nullable reference type. - // F4(default); + // F4(default); // 10 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(27, 15), // (30,15): warning CS8625: Cannot convert null literal to non-nullable reference type. - // F5(default); + // F5(default); // 11 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(30, 15), // (33,28): warning CS8625: Cannot convert null literal to non-nullable reference type. - // F6(default); + // F6(default); // 12 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(33, 28), // (39,15): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F0(T t = default(T))'. - // F0(default); // 0 + // F0(default); // 13 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F0(T t = default(T))").WithLocation(39, 15), // (41,18): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F6(T t = default(T))'. - // F6(default); // 0 + // F6(default); // 14 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F6(T t = default(T))").WithLocation(41, 18), // (46,15): warning CS8625: Cannot convert null literal to non-nullable reference type. - // F0(default); // 1 + // F0(default); // 15 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(46, 15), // (48,15): warning CS8625: Cannot convert null literal to non-nullable reference type. - // F1(default); // 1 + // F1(default); // 16 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(48, 15), // (50,18): warning CS8625: Cannot convert null literal to non-nullable reference type. - // F6(default); // 1 + // F6(default); // 17 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(50, 18), // (66,15): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F0(T t = default(T))'. - // F0(default); // 3 + // F0(default); // 18 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F0(T t = default(T))").WithLocation(66, 15), // (69,15): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F3(T t = default(T))'. - // F3(default); // 3 + // F3(default); // 19 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F3(T t = default(T))").WithLocation(69, 15), // (72,18): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F6(T t = default(T))'. - // F6(default); // 3 + // F6(default); // 20 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F6(T t = default(T))").WithLocation(72, 18), // (78,15): warning CS8625: Cannot convert null literal to non-nullable reference type. - // F0(default); // 4 + // F0(default); // 21 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(78, 15), // (80,15): warning CS8625: Cannot convert null literal to non-nullable reference type. - // F1(default); // 4 + // F1(default); // 22 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(80, 15), // (82,15): warning CS8625: Cannot convert null literal to non-nullable reference type. - // F4(default); // 4 + // F4(default); // 23 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(82, 15), // (84,15): warning CS8625: Cannot convert null literal to non-nullable reference type. - // F5(default); // 4 + // F5(default); // 24 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(84, 15), // (86,18): warning CS8625: Cannot convert null literal to non-nullable reference type. - // F6(default); // 4 + // F6(default); // 25 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(86, 18), // (91,15): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F0(T t = default(T))'. - // F0(default); // 5 + // F0(default); // 26 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F0(T t = default(T))").WithLocation(91, 15), // (93,15): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F5(T t = default(T))'. - // F5(default); // 5 + // F5(default); // 27 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F5(T t = default(T))").WithLocation(93, 15), // (95,18): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F6(T t = default(T))'. - // F6(default); // 5 + // F6(default); // 28 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F6(T t = default(T))").WithLocation(95, 18), // (100,15): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F0(T t = default(T))'. - // F0(default); // 6 + // F0(default); // 29 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F0(T t = default(T))").WithLocation(100, 15), // (102,18): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F6(T t = default(T))'. - // F6(default); // 6 + // F6(default); // 30 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F6(T t = default(T))").WithLocation(102, 18) ); @@ -68101,12 +68211,15 @@ static void M() // (6,34): warning CS1066: The default value specified for parameter 'x' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // static partial void G(object x = null, object? y = null) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "x").WithArguments("x").WithLocation(6, 34), + // (6,38): warning CS8625: Cannot convert null literal to non-nullable reference type. + // static partial void G(object x = null, object? y = null) { } + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 38), // (6,52): warning CS1066: The default value specified for parameter 'y' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // static partial void G(object x = null, object? y = null) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "y").WithArguments("y").WithLocation(6, 52), - // (3,56): warning CS8600: Converting null literal or possible null value to non-nullable type. + // (3,56): warning CS8625: Cannot convert null literal to non-nullable reference type. // static partial void F(object? x = null, object y = null); - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(3, 56), + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(3, 56), // (10,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'C.G(object, object?)' // G(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "G").WithArguments("x", "C.G(object, object?)").WithLocation(10, 9) @@ -68121,87 +68234,53 @@ public void ParameterDefaultValue_05() class C { T M1(T t = default) // 1 - => t; // 2 + => t; - T M2(T t = default) where T : class? // 3 - => t; // 4 + T M2(T t = default) where T : class? // 2 + => t; - T M3(T t = default) where T : class // 5 - => t; // 6 + T M3(T t = default) where T : class // 3 + => t; - T M4(T t = default) where T : notnull // 7 - => t; // 8 + T M4(T t = default) where T : notnull // 4 + => t; T M5(T? t = default) where T : struct - => t.Value; // 9 + => t.Value; // 5 - T M6(T? t = default(T)) where T : struct // 10 - => t.Value; // 11 + T M6(T? t = default(T)) where T : struct // 6 + => t.Value; // 7 }"; var comp = CreateCompilation(new[] { source }, options: WithNonNullTypesTrue(), parseOptions: TestOptions.Regular8); - comp.VerifyDiagnostics( - // (5,12): warning CS8603: Possible null reference return. - // => t; // 2 - Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(5, 12), - // (8,12): warning CS8603: Possible null reference return. - // => t; // 4 - Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(8, 12), - // (10,19): warning CS8600: Converting null literal or possible null value to non-nullable type. - // T M3(T t = default) where T : class // 5 - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(10, 19), - // (11,12): warning CS8603: Possible null reference return. - // => t; // 6 - Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(11, 12), - // (14,12): warning CS8603: Possible null reference return. - // => t; // 8 - Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(14, 12), + var expected = new[] + { + // (4,19): warning CS8601: Possible null reference assignment. + // T M1(T t = default) // 1 + Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(4, 19), + // (7,19): warning CS8625: Cannot convert null literal to non-nullable reference type. + // T M2(T t = default) where T : class? // 2 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(7, 19), + // (10,19): warning CS8625: Cannot convert null literal to non-nullable reference type. + // T M3(T t = default) where T : class // 3 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(10, 19), + // (13,19): warning CS8601: Possible null reference assignment. + // T M4(T t = default) where T : notnull // 4 + Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(13, 19), // (17,12): warning CS8629: Nullable value type may be null. - // => t.Value; // 9 + // => t.Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t").WithLocation(17, 12), // (19,16): error CS1770: A value of type 'T' cannot be used as default parameter for nullable parameter 't' because 'T' is not a simple type - // T M6(T? t = default(T)) where T : struct // 10 + // T M6(T? t = default(T)) where T : struct // 6 Diagnostic(ErrorCode.ERR_NoConversionForNubDefaultParam, "t").WithArguments("T", "t").WithLocation(19, 16), // (20,12): warning CS8629: Nullable value type may be null. - // => t.Value; // 11 + // => t.Value; // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t").WithLocation(20, 12) - ); + }; + + comp.VerifyDiagnostics(expected); comp = CreateCompilation(new[] { source }, options: WithNonNullTypesTrue()); - comp.VerifyDiagnostics( - // (4,19): warning CS8600: Converting null literal or possible null value to non-nullable type. - // T M1(T t = default) // 1 - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(4, 19), - // (5,12): warning CS8603: Possible null reference return. - // => t; // 2 - Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(5, 12), - // (7,19): warning CS8600: Converting null literal or possible null value to non-nullable type. - // T M2(T t = default) where T : class? // 3 - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(7, 19), - // (8,12): warning CS8603: Possible null reference return. - // => t; // 4 - Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(8, 12), - // (10,19): warning CS8600: Converting null literal or possible null value to non-nullable type. - // T M3(T t = default) where T : class // 5 - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(10, 19), - // (11,12): warning CS8603: Possible null reference return. - // => t; // 6 - Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(11, 12), - // (13,19): warning CS8600: Converting null literal or possible null value to non-nullable type. - // T M4(T t = default) where T : notnull // 7 - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(13, 19), - // (14,12): warning CS8603: Possible null reference return. - // => t; // 8 - Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(14, 12), - // (17,12): warning CS8629: Nullable value type may be null. - // => t.Value; // 9 - Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t").WithLocation(17, 12), - // (19,16): error CS1770: A value of type 'T' cannot be used as default parameter for nullable parameter 't' because 'T' is not a simple type - // T M6(T? t = default(T)) where T : struct // 10 - Diagnostic(ErrorCode.ERR_NoConversionForNubDefaultParam, "t").WithArguments("T", "t").WithLocation(19, 16), - // (20,12): warning CS8629: Nullable value type may be null. - // => t.Value; // 11 - Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t").WithLocation(20, 12) - ); + comp.VerifyDiagnostics(expected); } [WorkItem(40818, "https://github.com/dotnet/roslyn/issues/40818")] @@ -68233,7 +68312,7 @@ string M6([AllowNull] string s = ""a"") => s; // 6 int M7([DisallowNull] int? i = null) // 7 - => i.Value; // 8 + => i.Value; int M8([DisallowNull] int? i = 1) => i.Value; @@ -68260,10 +68339,7 @@ int M8([DisallowNull] int? i = 1) Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(22, 12), // (24,36): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // int M7([DisallowNull] int? i = null) // 7 - Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "null").WithLocation(24, 36), - // (25,12): warning CS8629: Nullable value type may be null. - // => i.Value; // 8 - Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "i").WithLocation(25, 12) + Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "null").WithLocation(24, 36) ); } @@ -68275,63 +68351,81 @@ record Rec1(T t = default) // 1, 2 { } -record Rec2(T t = default) // 3 +record Rec2(T t = default) // 2 { - T t { get; } = t; // 4 + T t { get; } = t; } -record Rec3(T t = default) // 5 +record Rec3(T t = default) // 3, 4 { T t { get; } = default!; } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, options: WithNonNullTypesTrue()); comp.VerifyDiagnostics( - // (2,16): warning CS8601: Possible null reference assignment. - // record Rec1(T t = default) // 1, 2 - Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "T t = default").WithLocation(2, 16), - // (2,22): warning CS8600: Converting null literal or possible null value to non-nullable type. - // record Rec1(T t = default) // 1, 2 - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(2, 22), - // (6,22): warning CS8600: Converting null literal or possible null value to non-nullable type. - // record Rec2(T t = default) // 3 - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(6, 22), - // (8,19): warning CS8601: Possible null reference assignment. - // T t { get; } = t; // 4 - Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t").WithLocation(8, 19), + // (2,22): warning CS8601: Possible null reference assignment. + // record Rec1(T t = default) // 1 + Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(2, 22), + // (6,22): warning CS8601: Possible null reference assignment. + // record Rec2(T t = default) // 2 + Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(6, 22), // (11,18): warning CS8907: Parameter 't' is unread. Did you forget to use it to initialize the property with that name? - // record Rec3(T t = default) // 5 + // record Rec3(T t = default) // 3, 4 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "t").WithArguments("t").WithLocation(11, 18), - // (11,22): warning CS8600: Converting null literal or possible null value to non-nullable type. - // record Rec3(T t = default) // 5 - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(11, 22)); + // (11,22): warning CS8601: Possible null reference assignment. + // record Rec3(T t = default) // 3, 4 + Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(11, 22) + ); } [Fact, WorkItem(43399, "https://github.com/dotnet/roslyn/issues/43399")] public void ParameterDefaultValue_08() { var source = @" +using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; -public class C { +public class C +{ public void M1([Optional, DefaultParameterValue(null)] object obj) // 1 { - obj.ToString(); // 2 + obj.ToString(); + } + public void M2([Optional, DefaultParameterValue(default(object))] object obj) // 2 + { + obj.ToString(); } public void M3([Optional, DefaultParameterValue(""a"")] object obj) { obj.ToString(); } + public void M4([AllowNull, Optional, DefaultParameterValue(null)] object obj) + { + obj.ToString(); // 3 + } + public void M5([Optional, DefaultParameterValue((object)null)] object obj) // 4, 5 + { + obj.ToString(); + } } "; - var comp = CreateCompilation(source, options: WithNonNullTypesTrue()); + var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }, options: WithNonNullTypesTrue()); comp.VerifyDiagnostics( - // (5,20): warning CS8600: Converting null literal or possible null value to non-nullable type. + // (7,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // public void M1([Optional, DefaultParameterValue(null)] object obj) // 1 - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "[Optional, DefaultParameterValue(null)] object obj").WithLocation(5, 20), - // (7,9): warning CS8602: Dereference of a possibly null reference. + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "[Optional, DefaultParameterValue(null)] object obj").WithLocation(7, 20), + // (11,20): warning CS8625: Cannot convert null literal to non-nullable reference type. + // public void M2([Optional, DefaultParameterValue(default(object))] object obj) // 1 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "[Optional, DefaultParameterValue(default(object))] object obj").WithLocation(11, 20), + // (21,9): warning CS8602: Dereference of a possibly null reference. // obj.ToString(); // 2 - Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(7, 9) + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(21, 9), + // (23,20): warning CS8625: Cannot convert null literal to non-nullable reference type. + // public void M5([Optional, DefaultParameterValue((object)null)] object obj) // 3, 4 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "[Optional, DefaultParameterValue((object)null)] object obj").WithLocation(23, 20), + // (23,53): warning CS8600: Converting null literal or possible null value to non-nullable type. + // public void M5([Optional, DefaultParameterValue((object)null)] object obj) // 3, 4 + Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)null").WithLocation(23, 53) ); } @@ -68346,9 +68440,17 @@ public void M1([Optional, DefaultParameterValue(null!)] object obj) { obj.ToString(); } + public void M2([Optional, DefaultParameterValue(default)] object obj) + { + obj.ToString(); + } + public void M3([Optional, DefaultParameterValue(null)] object obj = null) + { + obj.ToString(); + } } "; - // This doesn't seem like a scenario where an error or warning should be given. + // 'M1' doesn't seem like a scenario where an error or warning should be given. // However, we can't round trip the concept that the parameter default value was suppressed. // Therefore even if we fixed this, this usage could result in strange corner case behaviors when // emitting the method to metadata and calling it in source. @@ -68356,7 +68458,120 @@ public void M1([Optional, DefaultParameterValue(null!)] object obj) comp.VerifyDiagnostics( // (5,31): error CS8017: The parameter has multiple distinct default values. // public void M1([Optional, DefaultParameterValue(null!)] object obj) - Diagnostic(ErrorCode.ERR_ParamDefaultValueDiffersFromAttribute, "DefaultParameterValue(null!)").WithLocation(5, 31) + Diagnostic(ErrorCode.ERR_ParamDefaultValueDiffersFromAttribute, "DefaultParameterValue(null!)").WithLocation(5, 31), + // (9,31): error CS8017: The parameter has multiple distinct default values. + // public void M2([Optional, DefaultParameterValue(default)] object obj) + Diagnostic(ErrorCode.ERR_ParamDefaultValueDiffersFromAttribute, "DefaultParameterValue(default)").WithLocation(9, 31), + // (13,21): error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute + // public void M3([Optional, DefaultParameterValue(null)] object obj = null) + Diagnostic(ErrorCode.ERR_DefaultValueUsedWithAttributes, "Optional").WithLocation(13, 21), + // (13,31): error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute + // public void M3([Optional, DefaultParameterValue(null)] object obj = null) + Diagnostic(ErrorCode.ERR_DefaultValueUsedWithAttributes, "DefaultParameterValue").WithLocation(13, 31), + // (13,73): warning CS8625: Cannot convert null literal to non-nullable reference type. + // public void M3([Optional, DefaultParameterValue(null)] object obj = null) + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 73), + // (13,73): error CS8017: The parameter has multiple distinct default values. + // public void M3([Optional, DefaultParameterValue(null)] object obj = null) + Diagnostic(ErrorCode.ERR_ParamDefaultValueDiffersFromAttribute, "null").WithLocation(13, 73) + ); + } + + [Fact, WorkItem(48847, "https://github.com/dotnet/roslyn/issues/48847")] + public void ParameterDefaultValue_10() + { + var source = @" +public abstract class C1 +{ + public abstract void M1(string s = null); // 1 + public abstract void M2(string? s = null); +} + +public interface I1 +{ + void M1(string s = null); // 2 + void M2(string? s = null); +} + +public delegate void D1(string s = null); // 3 +public delegate void D2(string? s = null); +"; + var comp = CreateCompilation(source, options: WithNonNullTypesTrue()); + comp.VerifyDiagnostics( + // (4,40): warning CS8625: Cannot convert null literal to non-nullable reference type. + // public abstract void M1(string s = null); // 1 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 40), + // (10,24): warning CS8625: Cannot convert null literal to non-nullable reference type. + // void M1(string s = null); // 2 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 24), + // (14,36): warning CS8625: Cannot convert null literal to non-nullable reference type. + // public delegate void D1(string s = null); // 3 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 36) + ); + } + + [Fact, WorkItem(48844, "https://github.com/dotnet/roslyn/issues/48844")] + public void ParameterDefaultValue_11() + { + var source = @" +delegate void D1(T t = default); // 1 +delegate void D2(T? t = default); + +class C +{ + void M() + { + D1 d1 = str => str.ToString(); + d1(); + + D2 d2 = str => str.ToString(); // 2 + d2(); + } +} +"; + var comp = CreateCompilation(source, options: WithNonNullTypesTrue()); + comp.VerifyDiagnostics( + // (2,27): warning CS8601: Possible null reference assignment. + // delegate void D1(T t = default); // 1 + Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(2, 27), + // (12,32): warning CS8602: Dereference of a possibly null reference. + // D2 d2 = str => str.ToString(); // 2 + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "str").WithLocation(12, 32) + ); + } + + [Fact, WorkItem(48848, "https://github.com/dotnet/roslyn/issues/48848")] + public void ParameterDefaultValue_12() + { + var source = @" +public class Base1 +{ + public virtual void M(T t = default) { } // 1 +} + +public class Override1 : Base1 +{ + public override void M(string s) { } +} + +public class Base2 +{ + public virtual void M(T? t = default) { } +} + +public class Override2 : Base2 +{ + public override void M(string s) { } // 2 +} +"; + var comp = CreateCompilation(source, options: WithNonNullTypesTrue()); + comp.VerifyDiagnostics( + // (4,33): warning CS8601: Possible null reference assignment. + // public virtual void M(T t = default) { } // 1 + Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(4, 33), + // (19,26): warning CS8765: Nullability of type of parameter 's' doesn't match overridden member (possibly because of nullability attributes). + // public override void M(string s) { } // 2 + Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M").WithArguments("s").WithLocation(19, 26) ); } @@ -82539,10 +82754,11 @@ static void F3((B?, B) t) }"; var comp = CreateCompilation(source, options: WithNonNullTypesTrue()); // https://github.com/dotnet/roslyn/issues/32599: Handle tuple element conversions. + // Diagnostics on user-defined conversions need improvement: https://github.com/dotnet/roslyn/issues/31798 comp.VerifyDiagnostics( - // (16,12): warning CS8620: Argument of type '(A?, A)?' cannot be used for parameter 't' of type '(A, A?)?' in 'void Program.F2((A, A?)? t)' due to differences in the nullability of reference types. + // (16,12): warning CS8620: Argument of type 'S' cannot be used for parameter 't' of type '(A, A?)?' in 'void Program.F2((A, A?)? t)' due to differences in the nullability of reference types. // F2(s); // 1 - Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s").WithArguments("(A?, A)?", "(A, A?)?", "t", "void Program.F2((A, A?)? t)").WithLocation(16, 12)); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s").WithArguments("S", "(A, A?)?", "t", "void Program.F2((A, A?)? t)").WithLocation(16, 12)); } [Fact] @@ -96060,9 +96276,6 @@ class C // (16,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static U?[] F2() where T : class where U : T => throw null!; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(16, 12), - // (17,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. - // static U?[] F3() where T : struct where U : T => throw null!; - Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(17, 12), // (8,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static T? F4() where T : new() => throw null!; // error Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(8, 12), @@ -96072,9 +96285,6 @@ class C // (10,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static T? F6() where T : I => throw null!; // error Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(10, 12), - // (19,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. - // static U?[] F5() where T : unmanaged where U : T => throw null!; - Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(19, 12), // (20,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static U?[] F6() where T : I where U : T => throw null!; // error Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(20, 12), @@ -116974,9 +117184,9 @@ static void Main() // (12,15): warning CS8619: Nullability of reference types in value of type 'A' doesn't match target type 'A'. // B b = a; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a").WithArguments("A", "A").WithLocation(12, 15), - // (13,11): warning CS8620: Nullability of reference types in argument of type 'A' doesn't match target type 'A' for parameter 'b' in 'void Program.F(B b)'. + // (13,11): warning CS8620: Argument of type 'A' cannot be used for parameter 'b' of type 'B' in 'void Program.F(B b)' due to differences in the nullability of reference types. // F(a); // 2 - Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "a").WithArguments("A", "A", "b", "void Program.F(B b)").WithLocation(13, 11)); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "a").WithArguments("A", "B", "b", "void Program.F(B b)").WithLocation(13, 11)); } [Fact] @@ -117004,9 +117214,9 @@ static void Main() // (12,24): warning CS8619: Nullability of reference types in value of type 'A' doesn't match target type 'A'. // A a = b; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b").WithArguments("A", "A").WithLocation(12, 24), - // (13,11): warning CS8620: Nullability of reference types in argument of type 'A' doesn't match target type 'A' for parameter 'a' in 'void Program.F(A a)'. + // (13,11): warning CS8620: Argument of type 'B' cannot be used for parameter 'a' of type 'A' in 'void Program.F(A a)' due to differences in the nullability of reference types. // F(b); // 2 - Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "b").WithArguments("A", "A", "a", "void Program.F(A a)").WithLocation(13, 11)); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "b").WithArguments("B", "A", "a", "void Program.F(A a)").WithLocation(13, 11)); } [WorkItem(31864, "https://github.com/dotnet/roslyn/issues/31864")] @@ -126852,14 +127062,12 @@ static void M(C c1) { if (c1.Equals()) { - // technically the arg to Equals was 'null' so this should be analyzed as maybe-null - // however this scenario seems like such an anti-pattern that we shouldn't be concerned about it. - _ = c1.ToString(); + _ = c1.ToString(); // 2 } if (c1.Equals(null)) { - _ = c1.ToString(); // 2 + _ = c1.ToString(); // 3 } } @@ -126870,9 +127078,12 @@ static void M(C c1) // (3,7): warning CS0659: 'C' overrides Object.Equals(object o) but does not override Object.GetHashCode() // class C // 1 Diagnostic(ErrorCode.WRN_EqualsWithoutGetHashCode, "C").WithArguments("C").WithLocation(3, 7), - // (16,17): warning CS8602: Dereference of a possibly null reference. + // (9,17): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 2 - Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(16, 17)); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(9, 17), + // (14,17): warning CS8602: Dereference of a possibly null reference. + // _ = c1.ToString(); // 3 + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(14, 17)); } [Fact] @@ -126887,14 +127098,12 @@ static void M(C c1) { if (c1.Equals()) { - // technically the arg to Equals was 'null' so this should be analyzed as maybe-null - // however this scenario seems like such an anti-pattern that we shouldn't be concerned about it. - _ = c1.ToString(); + _ = c1.ToString(); // 1 } if (c1.Equals(null)) { - _ = c1.ToString(); // 1 + _ = c1.ToString(); // 2 } } @@ -126902,9 +127111,12 @@ static void M(C c1) }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( - // (16,17): warning CS8602: Dereference of a possibly null reference. + // (9,17): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 1 - Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(16, 17)); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(9, 17), + // (14,17): warning CS8602: Dereference of a possibly null reference. + // _ = c1.ToString(); // 2 + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(14, 17)); } [Theory] @@ -129756,12 +129968,12 @@ static void F(object target, object value) }"; var comp = CreateCompilation(source, options: WithNonNullTypesTrue()); comp.VerifyDiagnostics( - // (8,84): warning CS8600: Converting null literal or possible null value to non-nullable type. - // public static T CompareExchange(ref T location1, T value, T comparand = default) where T : class => value; - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(8, 84), - // (15,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'Interlocked.CompareExchange(ref T, T, T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. - // Interlocked.CompareExchange(value: value, location1: ref target); - Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "Interlocked.CompareExchange").WithArguments("System.Threading.Interlocked.CompareExchange(ref T, T, T)", "T", "object?").WithLocation(15, 9)); + // (8,84): warning CS8625: Cannot convert null literal to non-nullable reference type. + // public static T CompareExchange(ref T location1, T value, T comparand = default) where T : class => value; + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(8, 84), + // (15,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'Interlocked.CompareExchange(ref T, T, T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. + // Interlocked.CompareExchange(value: value, location1: ref target); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "Interlocked.CompareExchange").WithArguments("System.Threading.Interlocked.CompareExchange(ref T, T, T)", "T", "object?").WithLocation(15, 9)); } [Fact] @@ -132174,17 +132386,74 @@ static async Task Main() await foreach (var o in Create(x)) // 2 { } - await foreach (var o in Create(y)) + await foreach (var o in Create(y)) // 3 + { + } + } +}"; + var comp = CreateCompilationWithTasksExtensions(new[] { s_IAsyncEnumerable, source }); + comp.VerifyDiagnostics( + // (24,20): warning CS8600: Converting null literal or possible null value to non-nullable type. + // object y = null; // 1 + Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(24, 20), + // (25,33): warning CS8620: Argument of type 'StructAwaitable1' cannot be used for parameter 's' of type 'StructAwaitable1' in 'TaskAwaiter Program.GetAwaiter(StructAwaitable1 s)' due to differences in the nullability of reference types. + // await foreach (var o in Create(x)) // 2 + Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "Create(x)").WithArguments("StructAwaitable1", "StructAwaitable1", "s", "TaskAwaiter Program.GetAwaiter(StructAwaitable1 s)").WithLocation(25, 33), + // (28,33): warning CS8620: Argument of type 'StructAwaitable2' cannot be used for parameter 's' of type 'StructAwaitable2' in 'TaskAwaiter Program.GetAwaiter(StructAwaitable2 s)' due to differences in the nullability of reference types. + // await foreach (var o in Create(y)) // 3 + Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "Create(y)").WithArguments("StructAwaitable2", "StructAwaitable2", "s", "TaskAwaiter Program.GetAwaiter(StructAwaitable2 s)").WithLocation(28, 33) + ); + } + + [Fact] + [WorkItem(30956, "https://github.com/dotnet/roslyn/issues/30956")] + public void GetAwaiterExtensionMethod_AwaitForEach_InverseAnnotations() + { + var source = +@"#nullable enable +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +struct StructAwaitable1 { } +struct StructAwaitable2 { } +class Enumerable +{ + public Enumerator GetAsyncEnumerator() => new Enumerator(); +} +class Enumerator +{ + public object Current => null!; + public StructAwaitable1 MoveNextAsync() => new StructAwaitable1(); + public StructAwaitable2 DisposeAsync() => new StructAwaitable2(); +} +static class Program +{ + static TaskAwaiter GetAwaiter(this StructAwaitable1 s) => default; + static TaskAwaiter GetAwaiter(this StructAwaitable2 s) => default; + static Enumerable Create(T t) => new Enumerable(); + static async Task Main() + { + object? x = new object(); + object y = null; // 1 + await foreach (var o in Create(x)) // 2 + { + } + await foreach (var o in Create(y)) // 3 { } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { s_IAsyncEnumerable, source }); - // Should report warning for GetAwaiter(). comp.VerifyDiagnostics( // (24,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = null; // 1 - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(24, 20)); + Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(24, 20), + // (25,33): warning CS8620: Argument of type 'StructAwaitable2' cannot be used for parameter 's' of type 'StructAwaitable2' in 'TaskAwaiter Program.GetAwaiter(StructAwaitable2 s)' due to differences in the nullability of reference types. + // await foreach (var o in Create(x)) // 2 + Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "Create(x)").WithArguments("StructAwaitable2", "StructAwaitable2", "s", "TaskAwaiter Program.GetAwaiter(StructAwaitable2 s)").WithLocation(25, 33), + // (28,33): warning CS8620: Argument of type 'StructAwaitable1' cannot be used for parameter 's' of type 'StructAwaitable1' in 'TaskAwaiter Program.GetAwaiter(StructAwaitable1 s)' due to differences in the nullability of reference types. + // await foreach (var o in Create(y)) // 3 + Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "Create(y)").WithArguments("StructAwaitable1", "StructAwaitable1", "s", "TaskAwaiter Program.GetAwaiter(StructAwaitable1 s)").WithLocation(28, 33) + ); } [Fact] diff --git a/src/Compilers/CSharp/Test/Semantic/Semantics/RecordTests.cs b/src/Compilers/CSharp/Test/Semantic/Semantics/RecordTests.cs index 4566738df97bb..e5ef840d1d695 100644 --- a/src/Compilers/CSharp/Test/Semantic/Semantics/RecordTests.cs +++ b/src/Compilers/CSharp/Test/Semantic/Semantics/RecordTests.cs @@ -18159,7 +18159,7 @@ static void Main() var equalityContractGet = equalityContract.GetMethod; Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); - Assert.Equal(Accessibility.Protected, equalityContractGet.DeclaredAccessibility); + Assert.Equal(Accessibility.Protected, equalityContractGet!.DeclaredAccessibility); Assert.False(equalityContractGet.IsAbstract); Assert.False(equalityContractGet.IsVirtual); Assert.True(equalityContractGet.IsOverride); @@ -18275,7 +18275,7 @@ static void Main() var equalityContractGet = equalityContract.GetMethod; Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); - Assert.Equal(Accessibility.Protected, equalityContractGet.DeclaredAccessibility); + Assert.Equal(Accessibility.Protected, equalityContractGet!.DeclaredAccessibility); Assert.False(equalityContractGet.IsAbstract); Assert.False(equalityContractGet.IsVirtual); Assert.True(equalityContractGet.IsOverride); @@ -18348,7 +18348,7 @@ static void Main() var equalityContractGet = equalityContract.GetMethod; Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); - Assert.Equal(modifiers == "sealed " ? Accessibility.Private : Accessibility.Protected, equalityContractGet.DeclaredAccessibility); + Assert.Equal(modifiers == "sealed " ? Accessibility.Private : Accessibility.Protected, equalityContractGet!.DeclaredAccessibility); Assert.False(equalityContractGet.IsAbstract); Assert.Equal(modifiers != "sealed ", equalityContractGet.IsVirtual); Assert.False(equalityContractGet.IsOverride); diff --git a/src/Compilers/CSharp/Test/Semantic/Semantics/SemanticErrorTests.cs b/src/Compilers/CSharp/Test/Semantic/Semantics/SemanticErrorTests.cs index bfbe4e846074a..175443ef4f74a 100644 --- a/src/Compilers/CSharp/Test/Semantic/Semantics/SemanticErrorTests.cs +++ b/src/Compilers/CSharp/Test/Semantic/Semantics/SemanticErrorTests.cs @@ -12974,6 +12974,36 @@ static void M(A a, B b) Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "b[4, 5] = null").WithLocation(26, 20)); } + [Fact] + public void CS0854ERR_ExpressionTreeContainsOptionalArgument03() + { + var text = +@"using System; +using System.Collections; +using System.Linq.Expressions; + +public class Collection : IEnumerable +{ + public void Add(int i, int j = 0) { } + + public IEnumerator GetEnumerator() + { + throw new NotImplementedException(); + } +} + +public class C { + public void M() { + Expression> expr = + () => new Collection { 1 }; // 1 + } +}"; + CreateCompilation(text).VerifyDiagnostics( + // (18,36): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments + // () => new Collection { 1 }; // 1 + Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, "1").WithLocation(18, 36)); + } + [Fact] public void CS0855ERR_ExpressionTreeContainsIndexedProperty() { @@ -13070,9 +13100,10 @@ static void M(I i) compilation2.VerifyOperationTree(node, expectedOperationTree: @" IInvalidOperation (OperationKind.Invalid, Type: System.Object, IsInvalid) (Syntax: 'i.R[1]') - Children(2): + Children(3): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: I, IsInvalid) (Syntax: 'i') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') + ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid, IsImplicit) (Syntax: 'i.R[1]') "); } diff --git a/src/Compilers/CSharp/Test/Semantic/SourceGeneration/AdditionalSourcesCollectionTests.cs b/src/Compilers/CSharp/Test/Semantic/SourceGeneration/AdditionalSourcesCollectionTests.cs index 45dc947fe47e9..2c37b04314415 100644 --- a/src/Compilers/CSharp/Test/Semantic/SourceGeneration/AdditionalSourcesCollectionTests.cs +++ b/src/Compilers/CSharp/Test/Semantic/SourceGeneration/AdditionalSourcesCollectionTests.cs @@ -34,15 +34,31 @@ public class AdditionalSourcesCollectionTests [InlineData("abc{1}.cs")] public void HintName_ValidValues(string hintName) { - AdditionalSourcesCollection asc = new AdditionalSourcesCollection(); + AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add(hintName, SourceText.From("public class D{}", Encoding.UTF8)); Assert.True(asc.Contains(hintName)); var sources = asc.ToImmutableAndFree(); + Assert.Single(sources); Assert.True(sources[0].HintName.EndsWith(".cs")); } + [Theory] + [InlineData("abc")] // abc.vb + [InlineData("abc.cs")] //abc.cs.vb + [InlineData("abc.vb")] // abc.vb + public void HintName_WithExtension(string hintName) + { + AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".vb"); + asc.Add(hintName, SourceText.From("public class D{}", Encoding.UTF8)); + Assert.True(asc.Contains(hintName)); + + var sources = asc.ToImmutableAndFree(); + Assert.Single(sources); + Assert.True(sources[0].HintName.EndsWith(".vb")); + } + [Theory] [InlineData("/abc/def.cs")] [InlineData("\\")] @@ -57,7 +73,7 @@ public void HintName_ValidValues(string hintName) [InlineData("abc\u00A0.cs")] // unicode non-breaking space public void HintName_InvalidValues(string hintName) { - AdditionalSourcesCollection asc = new AdditionalSourcesCollection(); + AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); Assert.Throws(nameof(hintName), () => asc.Add(hintName, SourceText.From("public class D{}", Encoding.UTF8))); } @@ -65,7 +81,7 @@ public void HintName_InvalidValues(string hintName) public void AddedSources_Are_Deterministic() { // a few manual simple ones - AdditionalSourcesCollection asc = new AdditionalSourcesCollection(); + AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add("file3.cs", SourceText.From("", Encoding.UTF8)); asc.Add("file1.cs", SourceText.From("", Encoding.UTF8)); asc.Add("file2.cs", SourceText.From("", Encoding.UTF8)); @@ -87,7 +103,7 @@ public void AddedSources_Are_Deterministic() // generate a long random list, remembering the order we added them Random r = new Random(); string[] names = new string[1000]; - asc = new AdditionalSourcesCollection(); + asc = new AdditionalSourcesCollection(".cs"); for (int i = 0; i < 1000; i++) { names[i] = r.NextDouble().ToString() + ".cs"; @@ -112,7 +128,7 @@ public void AddedSources_Are_Deterministic() [InlineData("file", "File")] public void Hint_Name_Must_Be_Unique(string hintName1, string hintName2) { - AdditionalSourcesCollection asc = new AdditionalSourcesCollection(); + AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add(hintName1, SourceText.From("", Encoding.UTF8)); Assert.Throws("hintName", () => asc.Add(hintName2, SourceText.From("", Encoding.UTF8))); } @@ -129,7 +145,7 @@ public void Hint_Name_Must_Be_Unique(string hintName1, string hintName2) [InlineData("File.cs", "file.CS")] public void Contains(string addHintName, string checkHintName) { - AdditionalSourcesCollection asc = new AdditionalSourcesCollection(); + AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add(addHintName, SourceText.From("", Encoding.UTF8)); Assert.True(asc.Contains(checkHintName)); } @@ -141,7 +157,7 @@ public void Contains(string addHintName, string checkHintName) [InlineData("file.cs", "file")] public void Remove(string addHintName, string removeHintName) { - AdditionalSourcesCollection asc = new AdditionalSourcesCollection(); + AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add(addHintName, SourceText.From("", Encoding.UTF8)); asc.RemoveSource(removeHintName); var sources = asc.ToImmutableAndFree(); @@ -151,7 +167,7 @@ public void Remove(string addHintName, string removeHintName) [Fact] public void SourceTextRequiresEncoding() { - AdditionalSourcesCollection asc = new AdditionalSourcesCollection(); + AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); // fine asc.Add("file1.cs", SourceText.From("", Encoding.UTF8)); diff --git a/src/Compilers/CSharp/Test/Semantic/SourceGeneration/GeneratorDriverTests.cs b/src/Compilers/CSharp/Test/Semantic/SourceGeneration/GeneratorDriverTests.cs index d1de1cc7c9643..71dc4cfd5a0b8 100644 --- a/src/Compilers/CSharp/Test/Semantic/SourceGeneration/GeneratorDriverTests.cs +++ b/src/Compilers/CSharp/Test/Semantic/SourceGeneration/GeneratorDriverTests.cs @@ -637,8 +637,9 @@ class C { } outputCompilation.VerifyDiagnostics(); - - Assert.EndsWith(exception.ToString() + "'.", generatorDiagnostics.Single().Descriptor.Description.ToString()); + // Since translated description strings can have punctuation that differs based on locale, simply ensure the + // exception message is contains in the diagnostic description. + Assert.Contains(exception.ToString(), generatorDiagnostics.Single().Descriptor.Description.ToString()); } [Fact] diff --git a/src/Compilers/CSharp/Test/Symbol/DocumentationComments/CrefTests.cs b/src/Compilers/CSharp/Test/Symbol/DocumentationComments/CrefTests.cs index e3cbda2d31a90..06521b5931c2d 100644 --- a/src/Compilers/CSharp/Test/Symbol/DocumentationComments/CrefTests.cs +++ b/src/Compilers/CSharp/Test/Symbol/DocumentationComments/CrefTests.cs @@ -1564,7 +1564,7 @@ class C AssertEx.None(actualTypeParameters, p => p.HasReferenceTypeConstraint); AssertEx.None(actualTypeParameters, p => p.HasConstructorConstraint); AssertEx.All(actualTypeParameters, p => p.ContainingSymbol == null); - AssertEx.All(actualTypeParameters, p => p.GetConstraintTypes(null, canIgnoreNullableContext: false).Length == 0); + AssertEx.All(actualTypeParameters, p => p.GetConstraintTypes(null).Length == 0); AssertEx.All(actualTypeParameters, p => p.GetInterfaces(null).Length == 0); foreach (var p in actualTypeParameters) diff --git a/src/Compilers/CSharp/Test/Symbol/Symbols/DefaultInterfaceImplementationTests.cs b/src/Compilers/CSharp/Test/Symbol/Symbols/DefaultInterfaceImplementationTests.cs index ff711d95762fe..a6434f9c9b5eb 100644 --- a/src/Compilers/CSharp/Test/Symbol/Symbols/DefaultInterfaceImplementationTests.cs +++ b/src/Compilers/CSharp/Test/Symbol/Symbols/DefaultInterfaceImplementationTests.cs @@ -60024,5 +60024,122 @@ public void IncompletePropertyImplementationSyntax_01() Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(3, 16) ); } + + [Fact, WorkItem(49341, "https://github.com/dotnet/roslyn/issues/49341")] + public void RefReturningAutoProperty_01() + { + var source1 = +@" +interface IA +{ + static ref int PA { get;} +} + +interface IB +{ + static ref int PB { get; set;} +} + +interface IC +{ + static ref int PC { set;} +} +"; + var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, + parseOptions: TestOptions.Regular, + targetFramework: TargetFramework.NetStandardLatest); + compilation1.VerifyDiagnostics( + // (4,20): error CS8145: Auto-implemented properties cannot return by reference + // static ref int PA { get;} + Diagnostic(ErrorCode.ERR_AutoPropertyCannotBeRefReturning, "PA").WithArguments("IA.PA").WithLocation(4, 20), + // (9,20): error CS8145: Auto-implemented properties cannot return by reference + // static ref int PB { get; set;} + Diagnostic(ErrorCode.ERR_AutoPropertyCannotBeRefReturning, "PB").WithArguments("IB.PB").WithLocation(9, 20), + // (9,30): error CS8147: Properties which return by reference cannot have set accessors + // static ref int PB { get; set;} + Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "set").WithArguments("IB.PB.set").WithLocation(9, 30), + // (14,20): error CS8146: Properties which return by reference must have a get accessor + // static ref int PC { set;} + Diagnostic(ErrorCode.ERR_RefPropertyMustHaveGetAccessor, "PC").WithArguments("IC.PC").WithLocation(14, 20) + ); + } + + [Fact, WorkItem(49341, "https://github.com/dotnet/roslyn/issues/49341")] + public void RefReturningAutoProperty_02() + { + var source1 = +@" +interface IA +{ + ref int PA { get;} +} + +interface IB +{ + ref int PB { get; set;} +} + +interface IC +{ + ref int PC { set;} +} +"; + var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, + parseOptions: TestOptions.Regular, + targetFramework: TargetFramework.NetStandardLatest); + compilation1.VerifyDiagnostics( + // (9,23): error CS8147: Properties which return by reference cannot have set accessors + // ref int PB { get; set;} + Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "set").WithArguments("IB.PB.set").WithLocation(9, 23), + // (14,13): error CS8146: Properties which return by reference must have a get accessor + // ref int PC { set;} + Diagnostic(ErrorCode.ERR_RefPropertyMustHaveGetAccessor, "PC").WithArguments("IC.PC").WithLocation(14, 13) + ); + } + + [Fact, WorkItem(49341, "https://github.com/dotnet/roslyn/issues/49341")] + public void RefReturningAutoProperty_03() + { + var source1 = +@" +interface IA +{ + sealed ref int PA { get;} +} + +interface IB +{ + sealed ref int PB { get; set;} +} + +interface IC +{ + sealed ref int PC { set;} +} +"; + var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, + parseOptions: TestOptions.Regular, + targetFramework: TargetFramework.NetStandardLatest); + compilation1.VerifyDiagnostics( + // (4,25): error CS0501: 'IA.PA.get' must declare a body because it is not marked abstract, extern, or partial + // sealed ref int PA { get;} + Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("IA.PA.get").WithLocation(4, 25), + // (9,25): error CS0501: 'IB.PB.get' must declare a body because it is not marked abstract, extern, or partial + // sealed ref int PB { get; set;} + Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("IB.PB.get").WithLocation(9, 25), + // (9,30): error CS8147: Properties which return by reference cannot have set accessors + // sealed ref int PB { get; set;} + Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "set").WithArguments("IB.PB.set").WithLocation(9, 30), + // (9,30): error CS0501: 'IB.PB.set' must declare a body because it is not marked abstract, extern, or partial + // sealed ref int PB { get; set;} + Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("IB.PB.set").WithLocation(9, 30), + // (14,20): error CS8146: Properties which return by reference must have a get accessor + // sealed ref int PC { set;} + Diagnostic(ErrorCode.ERR_RefPropertyMustHaveGetAccessor, "PC").WithArguments("IC.PC").WithLocation(14, 20), + // (14,25): error CS0501: 'IC.PC.set' must declare a body because it is not marked abstract, extern, or partial + // sealed ref int PC { set;} + Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("IC.PC.set").WithLocation(14, 25) + ); + } } } diff --git a/src/Compilers/CSharp/Test/Symbol/Symbols/FunctionPointerTypeSymbolTests.cs b/src/Compilers/CSharp/Test/Symbol/Symbols/FunctionPointerTypeSymbolTests.cs index 72e1f2e6eef52..a0bb24635155c 100644 --- a/src/Compilers/CSharp/Test/Symbol/Symbols/FunctionPointerTypeSymbolTests.cs +++ b/src/Compilers/CSharp/Test/Symbol/Symbols/FunctionPointerTypeSymbolTests.cs @@ -925,8 +925,7 @@ private void AssertEqualityAndHashCode(FunctionPointerTypeSymbol p1, FunctionPoi if (parameterEqualities[i] == Equality.Equal) { Assert.True(((FunctionPointerParameterSymbol)param1).MethodEqualityChecks((FunctionPointerParameterSymbol)param2, - TypeCompareKind.ConsiderEverything, - isValueTypeOverride: null)); + TypeCompareKind.ConsiderEverything)); } for (int j = 0; j < p1.Signature.ParameterCount; j++) diff --git a/src/Compilers/CSharp/Test/Symbol/Symbols/Source/NullablePublicAPITests.cs b/src/Compilers/CSharp/Test/Symbol/Symbols/Source/NullablePublicAPITests.cs index 587ab493c1d51..13da3ba1494c3 100644 --- a/src/Compilers/CSharp/Test/Symbol/Symbols/Source/NullablePublicAPITests.cs +++ b/src/Compilers/CSharp/Test/Symbol/Symbols/Source/NullablePublicAPITests.cs @@ -4173,6 +4173,68 @@ void M() {} Assert.Equal(SpecialType.System_String, ((IFieldSymbol)symbolInfo.Symbol).Type.SpecialType); } + [Fact] + public void ParameterDefaultValue() + { + var source = @" +class Test +{ + void M0(object obj = default) { } // 1 + void M1(int i = default) { } +} +"; + + var comp = CreateCompilation(source, options: WithNonNullTypesTrue()); + comp.VerifyDiagnostics( + // (4,26): warning CS8625: Cannot convert null literal to non-nullable reference type. + // void M0(object obj = default) { } // 1 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(4, 26)); + + var syntaxTree = comp.SyntaxTrees[0]; + var root = syntaxTree.GetRoot(); + var model = comp.GetSemanticModel(syntaxTree); + + var default0 = root.DescendantNodes().OfType().ElementAt(0).Value; + Assert.Equal(PublicNullableFlowState.MaybeNull, model.GetTypeInfo(default0).Nullability.FlowState); + + var default1 = root.DescendantNodes().OfType().ElementAt(1).Value; + Assert.Equal(PublicNullableFlowState.NotNull, model.GetTypeInfo(default1).Nullability.FlowState); + } + + [Fact] + public void AttributeDefaultValue() + { + var source = @" +using System; + +class Attr : Attribute +{ + public Attr(object obj, int i) { } +} + +[Attr(default, default)] // 1 +class Test +{ +} +"; + + var comp = CreateCompilation(source, options: WithNonNullTypesTrue()); + comp.VerifyDiagnostics( + // (9,7): warning CS8625: Cannot convert null literal to non-nullable reference type. + // [Attr(default, default)] // 1 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(9, 7)); + + var syntaxTree = comp.SyntaxTrees[0]; + var root = syntaxTree.GetRoot(); + var model = comp.GetSemanticModel(syntaxTree); + + var default0 = root.DescendantNodes().OfType().ElementAt(0).Expression; + Assert.Equal(PublicNullableFlowState.MaybeNull, model.GetTypeInfo(default0).Nullability.FlowState); + + var default1 = root.DescendantNodes().OfType().ElementAt(1).Expression; + Assert.Equal(PublicNullableFlowState.NotNull, model.GetTypeInfo(default1).Nullability.FlowState); + } + [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void TypeParameter_Default() diff --git a/src/Compilers/CSharp/Test/Symbol/Symbols/Source/RecordTests.cs b/src/Compilers/CSharp/Test/Symbol/Symbols/Source/RecordTests.cs index a57c3c59e78f4..81534c2b48141 100644 --- a/src/Compilers/CSharp/Test/Symbol/Symbols/Source/RecordTests.cs +++ b/src/Compilers/CSharp/Test/Symbol/Symbols/Source/RecordTests.cs @@ -150,7 +150,7 @@ public void GeneratedProperties() var x = (SourcePropertySymbolBase)c.GetProperty("x"); Assert.NotNull(x.GetMethod); - Assert.Equal(MethodKind.PropertyGet, x.GetMethod.MethodKind); + Assert.Equal(MethodKind.PropertyGet, x.GetMethod!.MethodKind); Assert.Equal(SpecialType.System_Int32, x.Type.SpecialType); Assert.False(x.IsReadOnly); Assert.False(x.IsWriteOnly); @@ -175,7 +175,7 @@ public void GeneratedProperties() Assert.Equal(Accessibility.Public, getAccessor.DeclaredAccessibility); var setAccessor = x.SetMethod; - Assert.Equal(x, setAccessor.AssociatedSymbol); + Assert.Equal(x, setAccessor!.AssociatedSymbol); Assert.True(setAccessor.IsImplicitlyDeclared); Assert.Equal(c, setAccessor.ContainingSymbol); Assert.Equal(c, setAccessor.ContainingType); @@ -184,7 +184,7 @@ public void GeneratedProperties() var y = (SourcePropertySymbolBase)c.GetProperty("y"); Assert.NotNull(y.GetMethod); - Assert.Equal(MethodKind.PropertyGet, y.GetMethod.MethodKind); + Assert.Equal(MethodKind.PropertyGet, y.GetMethod!.MethodKind); Assert.Equal(SpecialType.System_Int32, y.Type.SpecialType); Assert.False(y.IsReadOnly); Assert.False(y.IsWriteOnly); @@ -208,7 +208,7 @@ public void GeneratedProperties() Assert.Equal(c, getAccessor.ContainingType); setAccessor = y.SetMethod; - Assert.Equal(y, setAccessor.AssociatedSymbol); + Assert.Equal(y, setAccessor!.AssociatedSymbol); Assert.True(setAccessor.IsImplicitlyDeclared); Assert.Equal(c, setAccessor.ContainingSymbol); Assert.Equal(c, setAccessor.ContainingType); @@ -1566,5 +1566,71 @@ .maxstack 1 IL_001b: ret }"); } + + [Fact] + [WorkItem(49286, "https://github.com/dotnet/roslyn/issues/49286")] + public void RecordWithEventImplicitlyImplementingAnInterface() + { + var src = @" +using System; + +public interface I1 +{ + event Action E1; +} + +public record R1 : I1 +{ + public event Action E1 { add { } remove { } } +} +"; + + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + } + + [Fact] + [WorkItem(49286, "https://github.com/dotnet/roslyn/issues/49286")] + public void RecordWithPropertyImplicitlyImplementingAnInterface() + { + var src = @" +using System; + +public interface I1 +{ + Action P1 { get; set; } +} + +public record R1 : I1 +{ + public Action P1 { get; set; } +} +"; + + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + } + + [Fact] + [WorkItem(49286, "https://github.com/dotnet/roslyn/issues/49286")] + public void RecordWithMethodImplicitlyImplementingAnInterface() + { + var src = @" +using System; + +public interface I1 +{ + Action M1(); +} + +public record R1 : I1 +{ + public Action M1() => throw null; +} +"; + + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + } } } diff --git a/src/Compilers/CSharp/csc/Program.cs b/src/Compilers/CSharp/csc/Program.cs index c6fea380dac73..1051f25d7ed4b 100644 --- a/src/Compilers/CSharp/csc/Program.cs +++ b/src/Compilers/CSharp/csc/Program.cs @@ -33,7 +33,8 @@ private static int MainCore(string[] args) ExitingTraceListener.Install(); #endif - return BuildClient.Run(args, RequestLanguage.CSharpCompile, Csc.Run); + using var logger = new CompilerServerLogger(); + return BuildClient.Run(args, RequestLanguage.CSharpCompile, Csc.Run, logger); } public static int Run(string[] args, string clientDir, string workingDir, string sdkDir, string tempDir, TextWriter textWriter, IAnalyzerAssemblyLoader analyzerLoader) diff --git a/src/Compilers/Core/CodeAnalysisTest/Analyzers/AnalyzerFileReferenceTests.cs b/src/Compilers/Core/CodeAnalysisTest/Analyzers/AnalyzerFileReferenceTests.cs index 7452b4980fd94..40a732904aa5a 100644 --- a/src/Compilers/Core/CodeAnalysisTest/Analyzers/AnalyzerFileReferenceTests.cs +++ b/src/Compilers/Core/CodeAnalysisTest/Analyzers/AnalyzerFileReferenceTests.cs @@ -248,23 +248,74 @@ public void TestFailedLoadDoesntCauseNoAnalyzersWarning() Assert.Equal(AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToCreateAnalyzer, errors.First().ErrorCode); } - // can't load a framework targeting generator, which these are in desktop - [ConditionalFact(typeof(CoreClrOnly))] + [ConditionalFact(typeof(CoreClrOnly), Reason = "Can't load a framework targeting generator, which these are in desktop")] public void TestLoadGenerators() { AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location); - var generators = reference.GetGenerators(); - Assert.Equal(5, generators.Length); + var generators = reference.GetGeneratorsForAllLanguages(); + var typeNames = generators.Select(g => g.GetType().FullName); + + AssertEx.SetEqual(new[] + { + "Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestGenerator", + "Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedGenerator", + "Microsoft.CodeAnalysis.UnitTests.TestGenerator", + "Microsoft.CodeAnalysis.UnitTests.BaseGenerator", + "Microsoft.CodeAnalysis.UnitTests.SubClassedGenerator", + "Microsoft.CodeAnalysis.UnitTests.ExplicitCSharpOnlyGenerator", + "Microsoft.CodeAnalysis.UnitTests.VisualBasicOnlyGenerator", + "Microsoft.CodeAnalysis.UnitTests.CSharpAndVisualBasicGenerator", + "Microsoft.CodeAnalysis.UnitTests.VisualBasicAndCSharpGenerator", + "Microsoft.CodeAnalysis.UnitTests.FSharpGenerator" + }, typeNames); + } + + [ConditionalFact(typeof(CoreClrOnly))] + public void TestLoadGeneratorsWithoutArgumentOnlyLoadsCSharp() + { + AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location); + var generators = reference.GetGenerators(LanguageNames.CSharp); + +#pragma warning disable CS0618 // Type or member is obsolete + var generators2 = reference.GetGenerators(); +#pragma warning restore CS0618 // Type or member is obsolete + + Assert.Equal(generators, generators2); + } + + [ConditionalFact(typeof(CoreClrOnly))] + public void TestLoadCSharpGenerators() + { + AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location); + var generators = reference.GetGenerators(LanguageNames.CSharp); var typeNames = generators.Select(g => g.GetType().FullName); - Assert.Contains("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestGenerator", typeNames); - Assert.Contains("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedGenerator", typeNames); - Assert.Contains("Microsoft.CodeAnalysis.UnitTests.TestGenerator", typeNames); - Assert.Contains("Microsoft.CodeAnalysis.UnitTests.BaseGenerator", typeNames); - Assert.Contains("Microsoft.CodeAnalysis.UnitTests.SubClassedGenerator", typeNames); - Assert.DoesNotContain("Microsoft.CodeAnalysis.UnitTests.TestGeneratorNoAttrib", typeNames); - Assert.DoesNotContain("Microsoft.CodeAnalysis.UnitTests.Test.NotAGenerator", typeNames); - Assert.DoesNotContain("Microsoft.CodeAnalysis.UnitTests.NotAGenerator", typeNames); + AssertEx.SetEqual(new[] + { + "Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestGenerator", + "Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedGenerator", + "Microsoft.CodeAnalysis.UnitTests.TestGenerator", + "Microsoft.CodeAnalysis.UnitTests.BaseGenerator", + "Microsoft.CodeAnalysis.UnitTests.SubClassedGenerator", + "Microsoft.CodeAnalysis.UnitTests.ExplicitCSharpOnlyGenerator", + "Microsoft.CodeAnalysis.UnitTests.CSharpAndVisualBasicGenerator", + "Microsoft.CodeAnalysis.UnitTests.VisualBasicAndCSharpGenerator" + }, typeNames); + } + + [ConditionalFact(typeof(CoreClrOnly))] + public void TestLoadVisualBasicGenerators() + { + AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location); + var generators = reference.GetGenerators(LanguageNames.VisualBasic); + + var typeNames = generators.Select(g => g.GetType().FullName); + AssertEx.SetEqual(new[] + { + "Microsoft.CodeAnalysis.UnitTests.VisualBasicOnlyGenerator", + "Microsoft.CodeAnalysis.UnitTests.CSharpAndVisualBasicGenerator", + "Microsoft.CodeAnalysis.UnitTests.VisualBasicAndCSharpGenerator" + }, typeNames); } // can't load a coreclr targeting generator on net framework / mono @@ -455,4 +506,19 @@ public class SubClassedGenerator : BaseGenerator [Generator] public class NotAGenerator { } + + [Generator(LanguageNames.CSharp)] + public class ExplicitCSharpOnlyGenerator : TestGenerator { } + + [Generator(LanguageNames.VisualBasic)] + public class VisualBasicOnlyGenerator : TestGenerator { } + + [Generator(LanguageNames.CSharp, LanguageNames.VisualBasic)] + public class CSharpAndVisualBasicGenerator : TestGenerator { } + + [Generator(LanguageNames.CSharp, LanguageNames.VisualBasic)] + public class VisualBasicAndCSharpGenerator : TestGenerator { } + + [Generator(LanguageNames.FSharp)] + public class FSharpGenerator : TestGenerator { } } diff --git a/src/Compilers/Core/CommandLine/BuildProtocol.cs b/src/Compilers/Core/CommandLine/BuildProtocol.cs index 5a19bf47fea71..a15eef118b73d 100644 --- a/src/Compilers/Core/CommandLine/BuildProtocol.cs +++ b/src/Compilers/Core/CommandLine/BuildProtocol.cs @@ -80,13 +80,6 @@ public static BuildRequest Create(RequestLanguage language, { Debug.Assert(!string.IsNullOrWhiteSpace(compilerHash), "CompilerHash is required to send request to the build server"); - Log($@" -Creating BuildRequest - Working directory: {workingDirectory} - Temp directory: {tempDirectory} - Lib directory: {libDirectory ?? null} - Compiler hash: {compilerHash}"); - var requestLength = args.Count + 1 + (libDirectory == null ? 0 : 1); var requestArgs = new List(requestLength); diff --git a/src/Compilers/Core/CommandLine/CompilerServerLogger.cs b/src/Compilers/Core/CommandLine/CompilerServerLogger.cs index 1794e9e00bd65..82aef4886e3d2 100644 --- a/src/Compilers/Core/CommandLine/CompilerServerLogger.cs +++ b/src/Compilers/Core/CommandLine/CompilerServerLogger.cs @@ -8,11 +8,86 @@ using System.Diagnostics; using System.IO; using System.Linq; +using System.Runtime.InteropServices.WindowsRuntime; using System.Text; using System.Threading; namespace Microsoft.CodeAnalysis.CommandLine { + /// + /// Used to log information from within the compiler server + /// + /// + /// Implementations of this interface must assume they are used on multilpe threads without any form + /// of synchronization. + /// + internal interface ICompilerServerLogger + { + bool IsLogging { get; } + void Log(string message); + } + + internal static class CompilerServerLoggerExtensions + { + internal static void Log(this ICompilerServerLogger logger, string format, params object?[] arguments) + { + if (logger.IsLogging) + { + logger.Log(string.Format(format, arguments)); + } + } + + internal static void LogError(this ICompilerServerLogger logger, string message) + { + if (logger.IsLogging) + { + logger.Log($"Error: {message}"); + } + } + + internal static void LogError(this ICompilerServerLogger logger, string format, params object?[] arguments) + { + if (logger.IsLogging) + { + logger.Log($"Error: {format}", arguments); + } + } + + /// + /// Log an exception. Also logs information about inner exceptions. + /// + internal static void LogException(this ICompilerServerLogger logger, Exception exception, string reason) + { + if (!logger.IsLogging) + { + return; + } + + var builder = new StringBuilder(); + builder.Append("Error "); + AppendException(exception); + + int innerExceptionLevel = 0; + Exception? e = exception.InnerException; + while (e != null) + { + builder.Append($"Inner exception[{innerExceptionLevel}] "); + AppendException(e); + e = e.InnerException; + innerExceptionLevel += 1; + } + + logger.Log(builder.ToString()); + + void AppendException(Exception exception) + { + builder.AppendLine($"Error: '{exception.GetType().Name}' '{exception.Message}' occurred during '{reason}'"); + builder.AppendLine("Stack trace:"); + builder.AppendLine(exception.StackTrace); + } + } + } + /// /// Class for logging information about what happens in the server and client parts of the /// Roslyn command line compiler and build tasks. Useful for debugging what is going on. @@ -21,130 +96,83 @@ namespace Microsoft.CodeAnalysis.CommandLine /// To use the logging, set the environment variable RoslynCommandLineLogFile to the name /// of a file to log to. This file is logged to by both client and server components. /// - internal class CompilerServerLogger + internal sealed class CompilerServerLogger : ICompilerServerLogger, IDisposable { // Environment variable, if set, to enable logging and set the file to log to. - private const string environmentVariable = "RoslynCommandLineLogFile"; + internal const string EnvironmentVariableName = "RoslynCommandLineLogFile"; + internal const string LoggingPrefix = "---"; - private static readonly Stream? s_loggingStream; - private static string s_prefix = "---"; + private Stream? _loggingStream; + private readonly int _processId; + + public bool IsLogging => _loggingStream is object; /// /// Static class initializer that initializes logging. /// - static CompilerServerLogger() + public CompilerServerLogger() { - s_loggingStream = null; + _processId = Process.GetCurrentProcess().Id; try { // Check if the environment - string? loggingFileName = Environment.GetEnvironmentVariable(environmentVariable); - - if (loggingFileName != null) + if (Environment.GetEnvironmentVariable(EnvironmentVariableName) is string loggingFileName) { // If the environment variable contains the path of a currently existing directory, // then use a process-specific name for the log file and put it in that directory. // Otherwise, assume that the environment variable specifies the name of the log file. if (Directory.Exists(loggingFileName)) { - loggingFileName = Path.Combine(loggingFileName, $"server.{GetCurrentProcessId()}.log"); + loggingFileName = Path.Combine(loggingFileName, $"server.{_processId}.log"); } // Open allowing sharing. We allow multiple processes to log to the same file, so we use share mode to allow that. - s_loggingStream = new FileStream(loggingFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite); + _loggingStream = new FileStream(loggingFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite); } } catch (Exception e) { - LogException(e, "Failed to create logging stream"); - } - } - - /// - /// Set the logging prefix that describes our role. - /// Typically a 3-letter abbreviation. If logging happens before this, it's logged with "---". - /// - public static void Initialize(string outputPrefix) - { - s_prefix = outputPrefix; - } - - /// - /// Log an exception. Also logs information about inner exceptions. - /// - public static void LogException(Exception exception, string reason) - { - if (s_loggingStream != null) - { - LogError("'{0}' '{1}' occurred during '{2}'. Stack trace:\r\n{3}", exception.GetType().Name, exception.Message, reason, exception.StackTrace); - - int innerExceptionLevel = 0; - - Exception? e = exception.InnerException; - while (e != null) - { - Log("Inner exception[{0}] '{1}' '{2}'. Stack trace: \r\n{3}", innerExceptionLevel, e.GetType().Name, e.Message, e.StackTrace); - e = e.InnerException; - innerExceptionLevel += 1; - } + Debug.Assert(false, e.Message); } } - /// - /// Log a line of text to the logging file, with string.Format arguments. - /// - public static void Log(string format, params object?[] arguments) + public void Dispose() { - if (s_loggingStream != null) - { - Log(string.Format(format, arguments)); - } + _loggingStream?.Dispose(); + _loggingStream = null; } - /// - /// Log a line of text to the logging file. - /// - /// - public static void Log(string message) + public void Log(string message) { - if (s_loggingStream != null) + if (_loggingStream is object) { - string prefix = GetLoggingPrefix(); - - string output = prefix + message + "\r\n"; + var threadId = Thread.CurrentThread.ManagedThreadId; + var prefix = $"PID={_processId} TID={threadId} Ticks={Environment.TickCount} "; + string output = prefix + message + Environment.NewLine; byte[] bytes = Encoding.UTF8.GetBytes(output); // Because multiple processes might be logging to the same file, we always seek to the end, // write, and flush. - s_loggingStream.Seek(0, SeekOrigin.End); - s_loggingStream.Write(bytes, 0, bytes.Length); - s_loggingStream.Flush(); + _loggingStream.Seek(0, SeekOrigin.End); + _loggingStream.Write(bytes, 0, bytes.Length); + _loggingStream.Flush(); } } + } - public static void LogError(string message) => Log($"Error: {message}"); + internal sealed class EmptyCompilerServerLogger : ICompilerServerLogger + { + public static EmptyCompilerServerLogger Instance { get; } = new EmptyCompilerServerLogger(); - public static void LogError(string format, params object?[] arguments) => Log($"Error: {format}", arguments); + public bool IsLogging => false; - private static int GetCurrentProcessId() + private EmptyCompilerServerLogger() { - var process = Process.GetCurrentProcess(); - return process.Id; } - private static int GetCurrentThreadId() - { - var thread = Thread.CurrentThread; - return thread.ManagedThreadId; - } - - /// - /// Get the string that prefixes all log entries. Shows the process, thread, and time. - /// - private static string GetLoggingPrefix() + public void Log(string message) { - return string.Format("{0} PID={1} TID={2} Ticks={3}: ", s_prefix, GetCurrentProcessId(), GetCurrentThreadId(), Environment.TickCount); } } } diff --git a/src/Compilers/Core/MSBuildTask/ManagedCompiler.cs b/src/Compilers/Core/MSBuildTask/ManagedCompiler.cs index c14ab5be0c6b4..27947f3edcec0 100644 --- a/src/Compilers/Core/MSBuildTask/ManagedCompiler.cs +++ b/src/Compilers/Core/MSBuildTask/ManagedCompiler.cs @@ -486,11 +486,12 @@ protected override int ExecuteTool(string pathToTool, string responseFileCommand return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands); } + using var logger = new CompilerServerLogger(); using (_sharedCompileCts = new CancellationTokenSource()) { - CompilerServerLogger.Log($"CommandLine = '{commandLineCommands}'"); - CompilerServerLogger.Log($"BuildResponseFile = '{responseFileCommands}'"); + logger.Log($"CommandLine = '{commandLineCommands}'"); + logger.Log($"BuildResponseFile = '{responseFileCommands}'"); var clientDir = Path.GetDirectoryName(PathToManagedTool); if (clientDir is null || tempDir is null) @@ -520,6 +521,7 @@ protected override int ExecuteTool(string pathToTool, string responseFileCommand buildPaths, keepAlive: null, libEnvVariable: LibDirectoryToUse(), + logger: logger, cancellationToken: _sharedCompileCts.Token); responseTask.Wait(_sharedCompileCts.Token); @@ -527,11 +529,11 @@ protected override int ExecuteTool(string pathToTool, string responseFileCommand var response = responseTask.Result; if (response != null) { - ExitCode = HandleResponse(response, pathToTool, responseFileCommands, commandLineCommands); + ExitCode = HandleResponse(response, pathToTool, responseFileCommands, commandLineCommands, logger); } else { - CompilerServerLogger.LogError($"Server compilation failed, falling back to {pathToTool}"); + logger.LogError($"Server compilation failed, falling back to {pathToTool}"); Log.LogMessage(ErrorString.SharedCompilationFallback, pathToTool); ExitCode = base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands); @@ -615,7 +617,7 @@ private string CurrentDirectoryToUse() /// Handle a response from the server, reporting messages and returning /// the appropriate exit code. /// - private int HandleResponse(BuildResponse response, string pathToTool, string responseFileCommands, string commandLineCommands) + private int HandleResponse(BuildResponse response, string pathToTool, string responseFileCommands, string commandLineCommands, ICompilerServerLogger logger) { if (response.Type != BuildResponse.ResponseType.Completed) { @@ -640,28 +642,28 @@ private int HandleResponse(BuildResponse response, string pathToTool, string res return completedResponse.ReturnCode; case BuildResponse.ResponseType.MismatchedVersion: - LogError("Roslyn compiler server reports different protocol version than build task."); + logError("Roslyn compiler server reports different protocol version than build task."); return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands); case BuildResponse.ResponseType.IncorrectHash: - LogError("Roslyn compiler server reports different hash version than build task."); + logError("Roslyn compiler server reports different hash version than build task."); return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands); case BuildResponse.ResponseType.Rejected: case BuildResponse.ResponseType.AnalyzerInconsistency: - CompilerServerLogger.LogError($"Server rejected request {response.Type}"); + logger.LogError($"Server rejected request {response.Type}"); return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands); default: - LogError($"Received an unrecognized response from the server: {response.Type}"); + logError($"Received an unrecognized response from the server: {response.Type}"); return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands); } - } - internal void LogError(string message) - { - CompilerServerLogger.LogError(message); - Log.LogError(message); + void logError(string message) + { + logger.LogError(message); + Log.LogError(message); + } } private void LogErrorMultiline(string output) diff --git a/src/Compilers/Core/MSBuildTask/xlf/ErrorString.zh-Hans.xlf b/src/Compilers/Core/MSBuildTask/xlf/ErrorString.zh-Hans.xlf index 7a9e0b113eb87..8b664c2660bd9 100644 --- a/src/Compilers/Core/MSBuildTask/xlf/ErrorString.zh-Hans.xlf +++ b/src/Compilers/Core/MSBuildTask/xlf/ErrorString.zh-Hans.xlf @@ -1,6 +1,6 @@  - + MSB3883: Unexpected exception: diff --git a/src/Compilers/Core/MSBuildTask/xlf/ErrorString.zh-Hant.xlf b/src/Compilers/Core/MSBuildTask/xlf/ErrorString.zh-Hant.xlf index 8c211d4ea1480..6f9906cf92c8c 100644 --- a/src/Compilers/Core/MSBuildTask/xlf/ErrorString.zh-Hant.xlf +++ b/src/Compilers/Core/MSBuildTask/xlf/ErrorString.zh-Hant.xlf @@ -1,6 +1,6 @@  - + MSB3883: Unexpected exception: diff --git a/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerFileReference.cs b/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerFileReference.cs index 3d465669f6b92..46d1b3ed487f7 100644 --- a/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerFileReference.cs +++ b/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerFileReference.cs @@ -30,10 +30,6 @@ namespace Microsoft.CodeAnalysis.Diagnostics /// public sealed class AnalyzerFileReference : AnalyzerReference, IEquatable { - private static readonly string s_diagnosticAnalyzerAttributeNamespace = typeof(DiagnosticAnalyzerAttribute).Namespace!; - private static readonly string s_generatorAttributeNamespace = typeof(GeneratorAttribute).Namespace!; - - private delegate bool AttributePredicate(PEModule module, CustomAttributeHandle attribute); private delegate IEnumerable AttributeLanguagesFunc(PEModule module, CustomAttributeHandle attribute); public override string FullPath { get; } @@ -60,8 +56,8 @@ public AnalyzerFileReference(string fullPath, IAnalyzerAssemblyLoader assemblyLo FullPath = fullPath; _assemblyLoader = assemblyLoader ?? throw new ArgumentNullException(nameof(assemblyLoader)); - _diagnosticAnalyzers = new Extensions(this, IsDiagnosticAnalyzerAttribute, GetDiagnosticsAnalyzerSupportedLanguages, allowNetFramework: true); - _generators = new Extensions(this, IsGeneratorAttribute, GetGeneratorsSupportedLanguages, allowNetFramework: false); + _diagnosticAnalyzers = new(this, typeof(DiagnosticAnalyzerAttribute), GetDiagnosticsAnalyzerSupportedLanguages, allowNetFramework: true); + _generators = new(this, typeof(GeneratorAttribute), GetGeneratorSupportedLanguages, allowNetFramework: false); // Note this analyzer full path as a dependency location, so that the analyzer loader // can correctly load analyzer dependencies. @@ -111,7 +107,9 @@ public override int GetHashCode() public override ImmutableArray GetAnalyzersForAllLanguages() { - return _diagnosticAnalyzers.GetExtensionsForAllLanguages(); + // This API returns duplicates of analyzers that support multiple languages. + // We explicitly retain this behaviour to ensure back compat + return _diagnosticAnalyzers.GetExtensionsForAllLanguages(includeDuplicates: true); } public override ImmutableArray GetAnalyzers(string language) @@ -119,9 +117,20 @@ public override ImmutableArray GetAnalyzers(string language) return _diagnosticAnalyzers.GetExtensions(language); } + public override ImmutableArray GetGeneratorsForAllLanguages() + { + return _generators.GetExtensionsForAllLanguages(includeDuplicates: false); + } + + [Obsolete("Use GetGenerators(string language) or GetGeneratorsForAllLanguages()")] public override ImmutableArray GetGenerators() { - return _generators.GetExtensionsForAllLanguages(); + return _generators.GetExtensions(LanguageNames.CSharp); + } + + public override ImmutableArray GetGenerators(string language) + { + return _generators.GetExtensions(language); } public override string Display @@ -213,7 +222,7 @@ internal ImmutableDictionary> GetAnalyzerTypeNa /// The PE image format is invalid. /// IO error reading the metadata. [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30449")] - private static ImmutableDictionary> GetAnalyzerTypeNameMap(string fullPath, AttributePredicate attributePredicate, AttributeLanguagesFunc languagesFunc) + private static ImmutableDictionary> GetAnalyzerTypeNameMap(string fullPath, Type attributeType, AttributeLanguagesFunc languagesFunc) { using var assembly = AssemblyMetadata.CreateFromFile(fullPath); @@ -223,7 +232,7 @@ private static ImmutableDictionary> GetAnalyzer var typeNameMap = from module in assembly.GetModules() from typeDefHandle in module.MetadataReader.TypeDefinitions let typeDef = module.MetadataReader.GetTypeDefinition(typeDefHandle) - let supportedLanguages = GetSupportedLanguages(typeDef, module.Module, attributePredicate, languagesFunc) + let supportedLanguages = GetSupportedLanguages(typeDef, module.Module, attributeType, languagesFunc) where supportedLanguages.Any() let typeName = GetFullyQualifiedTypeName(typeDef, module.Module) from supportedLanguage in supportedLanguages @@ -232,29 +241,52 @@ from supportedLanguage in supportedLanguages return typeNameMap.ToImmutableDictionary(g => g.Key, g => g.ToImmutableHashSet()); } - private static IEnumerable GetSupportedLanguages(TypeDefinition typeDef, PEModule peModule, AttributePredicate attributePredicate, AttributeLanguagesFunc languagesFunc) - { - var attributeLanguagesList = from customAttrHandle in typeDef.GetCustomAttributes() - where attributePredicate(peModule, customAttrHandle) - let attributeSupportedLanguages = languagesFunc(peModule, customAttrHandle) - where attributeSupportedLanguages != null - select attributeSupportedLanguages; - - return attributeLanguagesList.SelectMany(x => x); - } - - private static bool IsDiagnosticAnalyzerAttribute(PEModule peModule, CustomAttributeHandle customAttrHandle) + private static IEnumerable GetSupportedLanguages(TypeDefinition typeDef, PEModule peModule, Type attributeType, AttributeLanguagesFunc languagesFunc) { - return peModule.IsTargetAttribute(customAttrHandle, s_diagnosticAnalyzerAttributeNamespace, nameof(DiagnosticAnalyzerAttribute), ctor: out _); + foreach (CustomAttributeHandle customAttrHandle in typeDef.GetCustomAttributes()) + { + if (peModule.IsTargetAttribute(customAttrHandle, attributeType.Namespace!, attributeType.Name, ctor: out _)) + { + IEnumerable? attributeSupportedLanguages = languagesFunc(peModule, customAttrHandle); + if (attributeSupportedLanguages != null) + { + foreach (string item in attributeSupportedLanguages) + { + yield return item; + } + } + } + } } private static IEnumerable GetDiagnosticsAnalyzerSupportedLanguages(PEModule peModule, CustomAttributeHandle customAttrHandle) { // The DiagnosticAnalyzerAttribute has one constructor, which has a string parameter for the - // first supported language and an array parameter for addition supported languages. + // first supported language and an array parameter for additional supported languages. // Parse the argument blob to extract the languages. BlobReader argsReader = peModule.GetMemoryReaderOrThrow(peModule.GetCustomAttributeValueOrThrow(customAttrHandle)); + return ReadLanguagesFromAttribute(ref argsReader); + } + + private static IEnumerable GetGeneratorSupportedLanguages(PEModule peModule, CustomAttributeHandle customAttrHandle) + { + // The GeneratorAttribute has two constructors: one default, and one with a string parameter for the + // first supported language and an array parameter for additional supported languages. + BlobReader argsReader = peModule.GetMemoryReaderOrThrow(peModule.GetCustomAttributeValueOrThrow(customAttrHandle)); + if (argsReader.Length == 4) + { + // default ctor + return ImmutableArray.Create(LanguageNames.CSharp); + } + else + { + // Parse the argument blob to extract the languages. + return ReadLanguagesFromAttribute(ref argsReader); + } + } + private static IEnumerable ReadLanguagesFromAttribute(ref BlobReader argsReader) + { if (argsReader.Length > 4) { // Arguments are present--check prologue. @@ -278,16 +310,9 @@ private static IEnumerable GetDiagnosticsAnalyzerSupportedLanguages(PEMo } } } - return SpecializedCollections.EmptyEnumerable(); } - private static bool IsGeneratorAttribute(PEModule peModule, CustomAttributeHandle customAttrHandle) - { - return peModule.IsTargetAttribute(customAttrHandle, s_generatorAttributeNamespace, nameof(GeneratorAttribute), ctor: out _); - } - - private static IEnumerable GetGeneratorsSupportedLanguages(PEModule peModule, CustomAttributeHandle customAttrHandle) => ImmutableArray.Create(LanguageNames.CSharp); private static string GetFullyQualifiedTypeName(TypeDefinition typeDef, PEModule peModule) { @@ -305,37 +330,38 @@ private static string GetFullyQualifiedTypeName(TypeDefinition typeDef, PEModule } } - private sealed class Extensions where TExtension : class + private sealed class Extensions + where TExtension : class { private readonly AnalyzerFileReference _reference; - private readonly AttributePredicate _attributePredicate; + private readonly Type _attributeType; private readonly AttributeLanguagesFunc _languagesFunc; private readonly bool _allowNetFramework; private ImmutableArray _lazyAllExtensions; private ImmutableDictionary> _lazyExtensionsPerLanguage; private ImmutableDictionary>? _lazyExtensionTypeNameMap; - internal Extensions(AnalyzerFileReference reference, AttributePredicate attributePredicate, AttributeLanguagesFunc languagesFunc, bool allowNetFramework) + internal Extensions(AnalyzerFileReference reference, Type attributeType, AttributeLanguagesFunc languagesFunc, bool allowNetFramework) { _reference = reference; - _attributePredicate = attributePredicate; + _attributeType = attributeType; _languagesFunc = languagesFunc; _allowNetFramework = allowNetFramework; _lazyAllExtensions = default; _lazyExtensionsPerLanguage = ImmutableDictionary>.Empty; } - internal ImmutableArray GetExtensionsForAllLanguages() + internal ImmutableArray GetExtensionsForAllLanguages(bool includeDuplicates) { if (_lazyAllExtensions.IsDefault) { - ImmutableInterlocked.InterlockedInitialize(ref _lazyAllExtensions, CreateExtensionsForAllLanguages(this)); + ImmutableInterlocked.InterlockedInitialize(ref _lazyAllExtensions, CreateExtensionsForAllLanguages(this, includeDuplicates)); } return _lazyAllExtensions; } - private static ImmutableArray CreateExtensionsForAllLanguages(Extensions extensions) + private static ImmutableArray CreateExtensionsForAllLanguages(Extensions extensions, bool includeDuplicates) { // Get all analyzers in the assembly. var map = ImmutableDictionary.CreateBuilder>(); @@ -344,10 +370,29 @@ private static ImmutableArray CreateExtensionsForAllLanguages(Extens var builder = ImmutableArray.CreateBuilder(); foreach (var analyzers in map.Values) { - builder.AddRange(analyzers); + foreach (var analyzer in analyzers) + { + builder.Add(analyzer); + } } - return builder.ToImmutable(); + if (includeDuplicates) + { + return builder.ToImmutable(); + } + else + { + return builder.Distinct(ExtTypeComparer.Instance).ToImmutableArray(); + } + } + + private class ExtTypeComparer : IEqualityComparer + { + public static readonly ExtTypeComparer Instance = new(); + + public bool Equals(TExtension? x, TExtension? y) => object.Equals(x?.GetType(), y?.GetType()); + + public int GetHashCode(TExtension obj) => obj.GetType().GetHashCode(); } internal ImmutableArray GetExtensions(string language) @@ -372,7 +417,7 @@ internal ImmutableDictionary> GetExtensionTypeN { if (_lazyExtensionTypeNameMap == null) { - var analyzerTypeNameMap = GetAnalyzerTypeNameMap(_reference.FullPath, _attributePredicate, _languagesFunc); + var analyzerTypeNameMap = GetAnalyzerTypeNameMap(_reference.FullPath, _attributeType, _languagesFunc); Interlocked.CompareExchange(ref _lazyExtensionTypeNameMap, analyzerTypeNameMap, null); } diff --git a/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerReference.cs b/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerReference.cs index 4837da230facd..ef0c4750888bb 100644 --- a/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerReference.cs +++ b/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerReference.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; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Diagnostics @@ -63,6 +64,15 @@ public virtual string Display /// /// Gets all the source generators defined in this assembly reference. /// - public virtual ImmutableArray GetGenerators() { return ImmutableArray.Empty; } + public virtual ImmutableArray GetGeneratorsForAllLanguages() => ImmutableArray.Empty; + + [Obsolete("Use GetGenerators(string language) or GetGeneratorsForAllLanguages()")] + public virtual ImmutableArray GetGenerators() => ImmutableArray.Empty; + + /// + /// Gets all the diagnostic generators defined in this assembly reference for the given . + /// + /// Language name. + public virtual ImmutableArray GetGenerators(string language) => ImmutableArray.Empty; } } diff --git a/src/Compilers/Core/Portable/PublicAPI.Unshipped.txt b/src/Compilers/Core/Portable/PublicAPI.Unshipped.txt index 5e2cd74d0c0ea..41853b3182167 100644 --- a/src/Compilers/Core/Portable/PublicAPI.Unshipped.txt +++ b/src/Compilers/Core/Portable/PublicAPI.Unshipped.txt @@ -1,5 +1,11 @@ +Microsoft.CodeAnalysis.GeneratorAttribute.GeneratorAttribute(string firstLanguage, params string[] additionalLanguages) -> void +Microsoft.CodeAnalysis.GeneratorAttribute.Languages.get -> string[] Microsoft.CodeAnalysis.ITypeSymbol.IsRecord.get -> bool Microsoft.CodeAnalysis.SymbolDisplayPartKind.RecordName = 31 -> Microsoft.CodeAnalysis.SymbolDisplayPartKind const Microsoft.CodeAnalysis.WellKnownDiagnosticTags.CompilationEnd = "CompilationEnd" -> string static Microsoft.CodeAnalysis.CaseInsensitiveComparison.Compare(System.ReadOnlySpan left, System.ReadOnlySpan right) -> int static Microsoft.CodeAnalysis.CaseInsensitiveComparison.Equals(System.ReadOnlySpan left, System.ReadOnlySpan right) -> bool +override Microsoft.CodeAnalysis.Diagnostics.AnalyzerFileReference.GetGenerators(string language) -> System.Collections.Immutable.ImmutableArray +override Microsoft.CodeAnalysis.Diagnostics.AnalyzerFileReference.GetGeneratorsForAllLanguages() -> System.Collections.Immutable.ImmutableArray +virtual Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference.GetGenerators(string language) -> System.Collections.Immutable.ImmutableArray +virtual Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference.GetGeneratorsForAllLanguages() -> System.Collections.Immutable.ImmutableArray diff --git a/src/Compilers/Core/Portable/SourceGeneration/AdditionalSourcesCollection.cs b/src/Compilers/Core/Portable/SourceGeneration/AdditionalSourcesCollection.cs index 37c6ef52c7f81..6b6dc14f364ef 100644 --- a/src/Compilers/Core/Portable/SourceGeneration/AdditionalSourcesCollection.cs +++ b/src/Compilers/Core/Portable/SourceGeneration/AdditionalSourcesCollection.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.Diagnostics; using System.IO; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; @@ -15,19 +16,17 @@ internal sealed class AdditionalSourcesCollection { private readonly ArrayBuilder _sourcesAdded; + private readonly string _fileExtension; + private const StringComparison _hintNameComparison = StringComparison.OrdinalIgnoreCase; private static readonly StringComparer s_hintNameComparer = StringComparer.OrdinalIgnoreCase; - internal AdditionalSourcesCollection() + internal AdditionalSourcesCollection(string fileExtension) { + Debug.Assert(fileExtension.Length > 0 && fileExtension[0] == '.'); _sourcesAdded = ArrayBuilder.GetInstance(); - } - - internal AdditionalSourcesCollection(ImmutableArray existingSources) - : this() - { - _sourcesAdded.AddRange(existingSources); + _fileExtension = fileExtension; } public void Add(string hintName, SourceText source) @@ -72,6 +71,8 @@ public void Add(string hintName, SourceText source) _sourcesAdded.Add(new GeneratedSourceText(hintName, source)); } + public void AddRange(ImmutableArray texts) => _sourcesAdded.AddRange(texts); + public void RemoveSource(string hintName) { hintName = AppendExtensionIfRequired(hintName); @@ -100,11 +101,11 @@ public bool Contains(string hintName) internal ImmutableArray ToImmutableAndFree() => _sourcesAdded.ToImmutableAndFree(); - private static string AppendExtensionIfRequired(string hintName) + private string AppendExtensionIfRequired(string hintName) { - if (!hintName.EndsWith(".cs", _hintNameComparison)) + if (!hintName.EndsWith(_fileExtension, _hintNameComparison)) { - hintName = string.Concat(hintName, ".cs"); + hintName = string.Concat(hintName, _fileExtension); } return hintName; diff --git a/src/Compilers/Core/Portable/SourceGeneration/GeneratorAttribute.cs b/src/Compilers/Core/Portable/SourceGeneration/GeneratorAttribute.cs index 0cc09d5fa4168..6d07d625ec0bc 100644 --- a/src/Compilers/Core/Portable/SourceGeneration/GeneratorAttribute.cs +++ b/src/Compilers/Core/Portable/SourceGeneration/GeneratorAttribute.cs @@ -11,6 +11,43 @@ namespace Microsoft.CodeAnalysis [AttributeUsage(AttributeTargets.Class)] public sealed class GeneratorAttribute : Attribute { - // https://github.com/dotnet/roslyn/issues/: we don't know if we'll keep this, but for now it lets us re-use the analyzer discovery mechanism + /// + /// The source languages to which this generator applies. See . + /// + public string[] Languages { get; } + + /// + /// Attribute constructor used to specify the attached class is a source generator that provides CSharp sources. + /// + public GeneratorAttribute() + : this(LanguageNames.CSharp) { } + + /// + /// Attribute constructor used to specify the attached class is a source generator and indicate which language(s) it supports. + /// + /// One language to which the generator applies. + /// Additional languages to which the generator applies. See . + public GeneratorAttribute(string firstLanguage, params string[] additionalLanguages) + { + if (firstLanguage == null) + { + throw new ArgumentNullException(nameof(firstLanguage)); + } + + if (additionalLanguages == null) + { + throw new ArgumentNullException(nameof(additionalLanguages)); + } + + var languages = new string[additionalLanguages.Length + 1]; + languages[0] = firstLanguage; + for (int index = 0; index < additionalLanguages.Length; index++) + { + languages[index + 1] = additionalLanguages[index]; + } + + this.Languages = languages; + } + } } diff --git a/src/Compilers/Core/Portable/SourceGeneration/GeneratorContexts.cs b/src/Compilers/Core/Portable/SourceGeneration/GeneratorContexts.cs index bd4228afb9920..0f3ae00f47c9e 100644 --- a/src/Compilers/Core/Portable/SourceGeneration/GeneratorContexts.cs +++ b/src/Compilers/Core/Portable/SourceGeneration/GeneratorContexts.cs @@ -19,7 +19,7 @@ public readonly struct GeneratorExecutionContext private readonly AdditionalSourcesCollection _additionalSources; - internal GeneratorExecutionContext(Compilation compilation, ParseOptions parseOptions, ImmutableArray additionalTexts, AnalyzerConfigOptionsProvider optionsProvider, ISyntaxReceiver? syntaxReceiver, CancellationToken cancellationToken = default) + internal GeneratorExecutionContext(Compilation compilation, ParseOptions parseOptions, ImmutableArray additionalTexts, AnalyzerConfigOptionsProvider optionsProvider, ISyntaxReceiver? syntaxReceiver, AdditionalSourcesCollection additionalSources, CancellationToken cancellationToken = default) { Compilation = compilation; ParseOptions = parseOptions; @@ -27,7 +27,7 @@ internal GeneratorExecutionContext(Compilation compilation, ParseOptions parseOp AnalyzerConfigOptions = optionsProvider; SyntaxReceiver = syntaxReceiver; CancellationToken = cancellationToken; - _additionalSources = new AdditionalSourcesCollection(); + _additionalSources = additionalSources; _diagnostics = new DiagnosticBag(); } @@ -150,9 +150,9 @@ private static void CheckIsEmpty(T x) internal readonly struct GeneratorEditContext { - internal GeneratorEditContext(ImmutableArray sources, CancellationToken cancellationToken = default) + internal GeneratorEditContext(AdditionalSourcesCollection sources, CancellationToken cancellationToken = default) { - AdditionalSources = new AdditionalSourcesCollection(sources); + AdditionalSources = sources; CancellationToken = cancellationToken; } diff --git a/src/Compilers/Core/Portable/SourceGeneration/GeneratorDriver.cs b/src/Compilers/Core/Portable/SourceGeneration/GeneratorDriver.cs index 16f254ea0a6de..4558041229fe6 100644 --- a/src/Compilers/Core/Portable/SourceGeneration/GeneratorDriver.cs +++ b/src/Compilers/Core/Portable/SourceGeneration/GeneratorDriver.cs @@ -240,7 +240,7 @@ internal GeneratorDriverState RunGeneratorsCore(Compilation compilation, Diagnos Debug.Assert(generatorState.Info.Initialized); // we create a new context for each run of the generator. We'll never re-use existing state, only replace anything we have - var context = new GeneratorExecutionContext(compilation, state.ParseOptions, state.AdditionalTexts.NullToEmpty(), state.OptionsProvider, generatorState.SyntaxReceiver); + var context = new GeneratorExecutionContext(compilation, state.ParseOptions, state.AdditionalTexts.NullToEmpty(), state.OptionsProvider, generatorState.SyntaxReceiver, CreateSourcesCollection()); try { generator.Execute(context); @@ -279,7 +279,9 @@ private GeneratorDriverState ApplyPartialEdit(GeneratorDriverState state, Pendin if (edit.AcceptedBy(generatorState.Info)) { // attempt to apply the edit - var context = new GeneratorEditContext(generatorState.SourceTexts.ToImmutableArray(), cancellationToken); + var previousSources = CreateSourcesCollection(); + previousSources.AddRange(generatorState.SourceTexts); + var context = new GeneratorEditContext(previousSources, cancellationToken); var succeeded = edit.TryApply(generatorState.Info, context); if (!succeeded) { @@ -289,7 +291,7 @@ private GeneratorDriverState ApplyPartialEdit(GeneratorDriverState state, Pendin } // update the state with the new edits - var additionalSources = context.AdditionalSources.ToImmutableAndFree(); + var additionalSources = previousSources.ToImmutableAndFree(); state = state.With(generatorStates: state.GeneratorStates.SetItem(i, new GeneratorState(generatorState.Info, sourceTexts: additionalSources, trees: ParseAdditionalSources(generator, additionalSources, cancellationToken), diagnostics: ImmutableArray.Empty))); } } @@ -394,5 +396,7 @@ internal static string GetFilePathPrefixForGenerator(ISourceGenerator generator) internal abstract GeneratorDriver FromState(GeneratorDriverState state); internal abstract SyntaxTree ParseGeneratedSourceText(GeneratedSourceText input, string fileName, CancellationToken cancellationToken); + + internal abstract AdditionalSourcesCollection CreateSourcesCollection(); } } diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.cs.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.cs.xlf index ae8f45857e5f1..7af0e5646464a 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.cs.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.cs.xlf @@ -14,12 +14,12 @@ The assembly containing type '{0}' references .NET Framework, which is not supported. - The assembly containing type '{0}' references .NET Framework, which is not supported. + Sestavení, které obsahuje typ {0}, se odkazuje na architekturu .NET Framework, což se nepodporuje. Changes must be within bounds of SourceText - Changes must be within bounds of SourceText + Změny musí spadat do mezí SourceText. @@ -126,7 +126,7 @@ The provided SourceText must have an explicit encoding set. - The provided SourceText must have an explicit encoding set. + Zadaný SourceText musí mít explicitní sadu kódování. 'SourceText' is not localizable. @@ -576,12 +576,12 @@ Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' - Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' + Název oddílu konfigurace globálního analyzátoru {0} není platný, protože to není absolutní cesta. Oddíl se bude ignorovat. Deklaroval se v souboru: {1} {0}: invalid section name, {1} path to global config Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. - Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. + Název oddílu konfigurace globálního analyzátoru není platný, protože to není absolutní cesta. Oddíl se bude ignorovat diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.de.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.de.xlf index 2bdb4d9f06bba..3e5b6e4cf15c7 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.de.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.de.xlf @@ -14,12 +14,12 @@ The assembly containing type '{0}' references .NET Framework, which is not supported. - The assembly containing type '{0}' references .NET Framework, which is not supported. + Die Assembly mit dem Typ "{0}" verweist auf das .NET Framework. Dies wird nicht unterstützt. Changes must be within bounds of SourceText - Changes must be within bounds of SourceText + Änderungen müssen innerhalb der Grenzen von "SourceText" erfolgen. @@ -51,7 +51,7 @@ Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'. - Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'. + Die zusätzliche Datei gehört nicht zur zugrunde liegenden "CompilationWithAnalyzers". @@ -126,7 +126,7 @@ The provided SourceText must have an explicit encoding set. - The provided SourceText must have an explicit encoding set. + Der angegebene SourceText muss über einen expliziten Codierungssatz verfügen. 'SourceText' is not localizable. @@ -576,12 +576,12 @@ Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' - Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' + Der Name des Konfigurationsabschnitts "{0}" des globalen Analysemoduls ist ungültig, weil es sich nicht um einen absoluten Pfad handelt. Der Abschnitt wird ignoriert. Der Abschnitt wurde in der Datei "{1}" deklariert. {0}: invalid section name, {1} path to global config Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. - Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. + Der Name des Konfigurationsabschnitts des globalen Analysemoduls ist ungültig, weil es sich nicht um einen absoluten Pfad handelt. Der Abschnitt wird ignoriert. diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.es.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.es.xlf index 3278f39f24051..1b3ff3ffea107 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.es.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.es.xlf @@ -14,12 +14,12 @@ The assembly containing type '{0}' references .NET Framework, which is not supported. - The assembly containing type '{0}' references .NET Framework, which is not supported. + El ensamblado que contiene el tipo "{0}" hace referencia a .NET Framework, lo cual no se admite. Changes must be within bounds of SourceText - Changes must be within bounds of SourceText + Los cambios deben estar dentro de los límites de SourceText. @@ -51,7 +51,7 @@ Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'. - Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'. + El archivo adicional no pertenece al elemento "CompilationWithAnalyzers" subyacente. @@ -126,7 +126,7 @@ The provided SourceText must have an explicit encoding set. - The provided SourceText must have an explicit encoding set. + El elemento SourceText proporcionado debe tener un conjunto de codificación explícito. 'SourceText' is not localizable. @@ -576,12 +576,12 @@ Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' - Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' + El nombre de la sección de configuración "{0}" del analizador global no es válido porque no es una ruta de acceso absoluta. La sección se ignorará; esta se declaró en el archivo "{1}" {0}: invalid section name, {1} path to global config Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. - Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. + El nombre de la sección de configuración del analizador global no es válido porque no es una ruta de acceso absoluta. La sección se ignorará. diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.fr.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.fr.xlf index ce2eeeff550bd..f424b82388804 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.fr.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.fr.xlf @@ -14,12 +14,12 @@ The assembly containing type '{0}' references .NET Framework, which is not supported. - The assembly containing type '{0}' references .NET Framework, which is not supported. + L'assembly contenant le type '{0}' référence le .NET Framework, ce qui n'est pas pris en charge. Changes must be within bounds of SourceText - Changes must be within bounds of SourceText + Les changements doivent se situer dans les limites de SourceText @@ -51,7 +51,7 @@ Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'. - Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'. + Le fichier supplémentaire n'appartient pas au 'CompilationWithAnalyzers' sous-jacent. @@ -126,7 +126,7 @@ The provided SourceText must have an explicit encoding set. - The provided SourceText must have an explicit encoding set. + Le SourceText fourni doit avoir un encodage explicite défini. 'SourceText' is not localizable. @@ -576,12 +576,12 @@ Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' - Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' + Le nom de section de configuration '{0}' de l'analyseur global est non valide, car il ne s'agit pas d'un chemin absolu. La section va être ignorée. La section a été déclarée dans le fichier '{1}' {0}: invalid section name, {1} path to global config Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. - Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. + Le nom de section de configuration de l'analyseur global est non valide, car il ne s'agit pas d'un chemin absolu. La section va être ignorée. diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.it.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.it.xlf index 2befb85a93744..8858f5f15739a 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.it.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.it.xlf @@ -14,12 +14,12 @@ The assembly containing type '{0}' references .NET Framework, which is not supported. - The assembly containing type '{0}' references .NET Framework, which is not supported. + L'assembly che contiene il tipo '{0}' fa riferimento a .NET Framework, che non è supportato. Changes must be within bounds of SourceText - Changes must be within bounds of SourceText + Le modifiche devono rientrare nei limiti di SourceText @@ -51,7 +51,7 @@ Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'. - Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'. + Il file aggiuntivo non appartiene all'oggetto 'CompilationWithAnalyzers' sottostante. @@ -126,7 +126,7 @@ The provided SourceText must have an explicit encoding set. - The provided SourceText must have an explicit encoding set. + L'elemento SourceText fornito deve avere una codifica esplicita impostata. 'SourceText' is not localizable. @@ -576,12 +576,12 @@ Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' - Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' + Il nome della sezione '{0}' di configurazione dell'analizzatore globale non è valido perché non è un percorso assoluto. La sezione verrà ignorata. La sezione è stata dichiarata nel file: '{1}' {0}: invalid section name, {1} path to global config Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. - Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. + Il nome della sezione di configurazione dell'analizzatore globale non è valido perché non è un percorso assoluto. La sezione verrà ignorata. diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.ja.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.ja.xlf index e2cc4836635cc..1ace32468a2c0 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.ja.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.ja.xlf @@ -14,12 +14,12 @@ The assembly containing type '{0}' references .NET Framework, which is not supported. - The assembly containing type '{0}' references .NET Framework, which is not supported. + 型 '{0}' を含むアセンブリが .NET Framework を参照しています。これはサポートされていません。 Changes must be within bounds of SourceText - Changes must be within bounds of SourceText + 変更は SourceText の範囲内でなければなりません @@ -51,7 +51,7 @@ Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'. - Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'. + 追加ファイルは、基になる 'CompilationWithAnalyzers' に属していません。 @@ -126,7 +126,7 @@ The provided SourceText must have an explicit encoding set. - The provided SourceText must have an explicit encoding set. + 指定する SourceText には明示的なエンコード セットを含める必要があります。 'SourceText' is not localizable. @@ -576,12 +576,12 @@ Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' - Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' + グローバル アナライザー構成セクション名 '{0}' は、絶対パスではないため無効です。セクションは無視されます。セクションはファイル '{1}' で宣言されました。 {0}: invalid section name, {1} path to global config Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. - Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. + グローバル アナライザー構成セクション名は、絶対パスではないため無効です。セクションは無視されます。 @@ -853,7 +853,7 @@ No analyzers found - アナライザーが見つかりません。 + アナライザーが見つかりません @@ -970,12 +970,12 @@ element is expected - 要素が必要です。 + 要素が必要です separator is expected - 区切り記号が必要です。 + 区切り記号が必要です @@ -985,7 +985,7 @@ Deserialization reader for '{0}' read incorrect number of values. - {0}' の逆シリアル化のリーダーが、正しくない数の値を読み取りました。 + '{0}' の逆シリアル化のリーダーが、正しくない数の値を読み取りました。 diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.ko.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.ko.xlf index 3f12ee7eec4f3..8455c20fc3e8e 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.ko.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.ko.xlf @@ -14,12 +14,12 @@ The assembly containing type '{0}' references .NET Framework, which is not supported. - The assembly containing type '{0}' references .NET Framework, which is not supported. + '{0}' 형식을 포함하는 어셈블리가 지원되지 않는 .NET Framework를 참조합니다. Changes must be within bounds of SourceText - Changes must be within bounds of SourceText + 변경 내용은 SourceText의 범위 내에 있어야 합니다. @@ -30,7 +30,7 @@ Analyzer '{0}' threw the following exception: '{1}'. - {0}' 분석기에서 다음 예외를 throw했습니다. + '{0}' 분석기에서 다음 예외를 throw했습니다. '{1}' @@ -51,7 +51,7 @@ Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'. - Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'. + 추가 파일이 기본 'CompilationWithAnalyzers'에 속하지 않습니다. @@ -126,7 +126,7 @@ The provided SourceText must have an explicit encoding set. - The provided SourceText must have an explicit encoding set. + SourceText에는 명시적인 인코딩 집합이 있어야 합니다. 'SourceText' is not localizable. @@ -406,7 +406,7 @@ Invalid module name specified in metadata module '{0}': '{1}' - {0}' 메타데이터 모듈에 잘못된 모듈 이름이 지정되었습니다('{1}'). + '{0}' 메타데이터 모듈에 잘못된 모듈 이름이 지정되었습니다('{1}'). @@ -576,12 +576,12 @@ Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' - Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' + 전역 분석기 구성 섹션 이름 '{0}'이(가) 절대 경로가 아니므로 잘못되었습니다. 섹션이 무시됩니다. 파일 '{1}'에 섹션이 선언되었습니다. {0}: invalid section name, {1} path to global config Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. - Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. + 전역 분석기 구성 섹션 이름이 절대 경로가 아니므로 잘못되었습니다. 섹션이 무시됩니다. @@ -738,12 +738,12 @@ Cannot deserialize type '{0}'. - {0}' 형식을 역직렬화할 수 없습니다. + '{0}' 형식을 역직렬화할 수 없습니다. Cannot serialize type '{0}'. - {0}' 형식을 직렬화할 수 없습니다. + '{0}' 형식을 직렬화할 수 없습니다. @@ -905,7 +905,7 @@ Reference of type '{0}' is not valid for this compilation. - {0}' 형식의 참조를 이 컴파일에 사용할 수 없습니다. + '{0}' 형식의 참조를 이 컴파일에 사용할 수 없습니다. @@ -985,7 +985,7 @@ Deserialization reader for '{0}' read incorrect number of values. - {0}'에 대한 역직렬화 판독기가 잘못된 숫자 값을 읽습니다. + '{0}'에 대한 역직렬화 판독기가 잘못된 숫자 값을 읽습니다. diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.pl.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.pl.xlf index 79154af741a6f..78cefd7b714eb 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.pl.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.pl.xlf @@ -14,12 +14,12 @@ The assembly containing type '{0}' references .NET Framework, which is not supported. - The assembly containing type '{0}' references .NET Framework, which is not supported. + Zestaw zawierający typ „{0}” odwołuje się do platformy .NET Framework, co nie jest obsługiwane. Changes must be within bounds of SourceText - Changes must be within bounds of SourceText + Zmiany muszą należeć do zakresu elementu SourceText @@ -51,7 +51,7 @@ Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'. - Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'. + Dodatkowy plik nie należy do źródłowego elementu „CompilationWithAnalyzers”. @@ -126,7 +126,7 @@ The provided SourceText must have an explicit encoding set. - The provided SourceText must have an explicit encoding set. + Podany tekst źródłowy (SourceText) musi mieć zestaw jawnego kodowania. 'SourceText' is not localizable. @@ -576,12 +576,12 @@ Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' - Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' + Nazwa globalnej sekcji konfiguracji analizatora „{0}” jest nieprawidłowa, ponieważ nie jest ścieżką bezwzględną. Sekcja zostanie zignorowana. Sekcja została zadeklarowana w pliku „{1}”. {0}: invalid section name, {1} path to global config Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. - Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. + Nazwa globalnej sekcji konfiguracji analizatora jest nieprawidłowa, ponieważ nie jest ścieżką bezwzględną. Sekcja zostanie zignorowana. diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.pt-BR.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.pt-BR.xlf index d1fad317f1980..1e2a813164d11 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.pt-BR.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.pt-BR.xlf @@ -14,12 +14,12 @@ The assembly containing type '{0}' references .NET Framework, which is not supported. - The assembly containing type '{0}' references .NET Framework, which is not supported. + O assembly contendo o tipo '{0}' faz referência a .NET Framework, mas não há suporte para isso. Changes must be within bounds of SourceText - Changes must be within bounds of SourceText + As alterações precisam estar dentro dos limites do SourceText @@ -51,7 +51,7 @@ Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'. - Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'. + O arquivo adicional não pertence ao 'CompilationWithAnalyzers' subjacente. @@ -126,7 +126,7 @@ The provided SourceText must have an explicit encoding set. - The provided SourceText must have an explicit encoding set. + O SourceText fornecido precisa ter um conjunto de codificação explícito. 'SourceText' is not localizable. @@ -446,12 +446,12 @@ 'start' must not be negative - '"início" não deve ser negativo + "início" não deve ser negativo 'end' must not be less than 'start' - '"fim" não deve ser menor que "início" + "fim" não deve ser menor que "início" @@ -576,12 +576,12 @@ Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' - Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' + O nome da seção de configuração do analisador global '{0}' é inválido porque não é um caminho absoluto. A seção será ignorada. A seção foi declarada no arquivo: '{1}' {0}: invalid section name, {1} path to global config Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. - Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. + O nome da seção de configuração do analisador global é inválido porque não é um caminho absoluto. A seção será ignorada. diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.ru.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.ru.xlf index 82fe5bb41c917..034d80857a098 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.ru.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.ru.xlf @@ -14,12 +14,12 @@ The assembly containing type '{0}' references .NET Framework, which is not supported. - The assembly containing type '{0}' references .NET Framework, which is not supported. + Сборка, содержащая тип "{0}", ссылается на платформу .NET Framework, которая не поддерживается. Changes must be within bounds of SourceText - Changes must be within bounds of SourceText + Изменения должны находиться в границах SourceText @@ -51,7 +51,7 @@ Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'. - Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'. + Дополнительный файл не принадлежит базовому элементу "CompilationWithAnalyzers". @@ -126,7 +126,7 @@ The provided SourceText must have an explicit encoding set. - The provided SourceText must have an explicit encoding set. + Предоставленный SourceText должен иметь явный набор кодировок. 'SourceText' is not localizable. @@ -576,12 +576,12 @@ Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' - Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' + Имя раздела конфигурации глобального анализатора "{0}" недопустимо, так как не является абсолютным путем. Раздел будет проигнорирован. Раздел объявлен в файле: "{1}". {0}: invalid section name, {1} path to global config Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. - Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. + Имя раздела конфигурации глобального анализатора недопустимо, так как не является абсолютным путем. Раздел будет проигнорирован. diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.tr.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.tr.xlf index eb913e58745de..5acb4f23c94ca 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.tr.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.tr.xlf @@ -14,12 +14,12 @@ The assembly containing type '{0}' references .NET Framework, which is not supported. - The assembly containing type '{0}' references .NET Framework, which is not supported. + '{0}' türünü içeren bütünleştirilmiş kod, desteklenmeyen .NET Framework'e başvuruyor. Changes must be within bounds of SourceText - Changes must be within bounds of SourceText + Değişiklikler, SourceText sınırları içinde olmalıdır @@ -30,7 +30,7 @@ Analyzer '{0}' threw the following exception: '{1}'. - {0}' çözümleyicisi şu özel durumu oluşturdu: + '{0}' çözümleyicisi şu özel durumu oluşturdu: '{1}'. @@ -51,7 +51,7 @@ Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'. - Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'. + Ek dosya, temel alınan 'CompilationWithAnalyzers' öğesine ait değil. @@ -126,7 +126,7 @@ The provided SourceText must have an explicit encoding set. - The provided SourceText must have an explicit encoding set. + Sağlanan SourceText'in açık bir kodlama kümesi olmalıdır. 'SourceText' is not localizable. @@ -406,7 +406,7 @@ Invalid module name specified in metadata module '{0}': '{1}' - {0}' meta veri modülünde geçersiz modül adı belirtildi: '{1}' + '{0}' meta veri modülünde geçersiz modül adı belirtildi: '{1}' @@ -576,12 +576,12 @@ Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' - Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' + Genel çözümleyici yapılandırması bölümü adı ('{0}') mutlak bir yol olmadığından geçersiz. Bölüm yoksayılacak. Bölüm '{1}' dosyasında bildirildi {0}: invalid section name, {1} path to global config Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. - Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. + Genel çözümleyici yapılandırması bölümü adı mutlak bir yol olmadığından geçersiz. Bölüm yoksayılacak. @@ -718,7 +718,7 @@ Reported diagnostic with ID '{0}' is not supported by the analyzer. - {0}' kimliği ile bildirilen tanılama, çözümleyici tarafından desteklenmiyor. + '{0}' kimliği ile bildirilen tanılama, çözümleyici tarafından desteklenmiyor. @@ -733,17 +733,17 @@ The type '{0}' is not understood by the serialization binder. - {0}' türü, serileştirme bağlayıcısı tarafından anlaşılamıyor. + '{0}' türü, serileştirme bağlayıcısı tarafından anlaşılamıyor. Cannot deserialize type '{0}'. - {0}' türü seri durumdan çıkarılamıyor. + '{0}' türü seri durumdan çıkarılamıyor. Cannot serialize type '{0}'. - {0}' türü seri hale getirilemiyor. + '{0}' türü seri hale getirilemiyor. @@ -905,7 +905,7 @@ Reference of type '{0}' is not valid for this compilation. - {0}' türündeki başvuru bu derleme için geçerli değil. + '{0}' türündeki başvuru bu derleme için geçerli değil. @@ -985,7 +985,7 @@ Deserialization reader for '{0}' read incorrect number of values. - {0}' türünün seri durumdan çıkarma okuyucusu, yanlış sayıda değer okudu. + '{0}' türünün seri durumdan çıkarma okuyucusu, yanlış sayıda değer okudu. diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.zh-Hans.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.zh-Hans.xlf index 8b2ce7f1ee441..1f3fb9506bf0d 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.zh-Hans.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + A language name cannot be specified for this option. @@ -14,12 +14,12 @@ The assembly containing type '{0}' references .NET Framework, which is not supported. - The assembly containing type '{0}' references .NET Framework, which is not supported. + 包含类型“{0}”的程序集引用了 .NET Framework,而此操作不受支持。 Changes must be within bounds of SourceText - Changes must be within bounds of SourceText + 必须在 SourceText 的边界内进行更改 @@ -126,7 +126,7 @@ The provided SourceText must have an explicit encoding set. - The provided SourceText must have an explicit encoding set. + 提供的 SourceText 必须具有显式编码集。 'SourceText' is not localizable. @@ -576,12 +576,12 @@ Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' - Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' + 全局分析器配置部分名称“{0}”无效,因为它不是绝对路径。部分将被忽略。部分已在以下文件中声明:“{1}”。 {0}: invalid section name, {1} path to global config Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. - Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. + 全局分析器配置部分名称无效,因为它不是绝对路径。部分将被忽略。 diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.zh-Hant.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.zh-Hant.xlf index efe33025cd2d9..9e04c86d96f2b 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.zh-Hant.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + A language name cannot be specified for this option. @@ -14,12 +14,12 @@ The assembly containing type '{0}' references .NET Framework, which is not supported. - The assembly containing type '{0}' references .NET Framework, which is not supported. + 包含類型 '{0}' 的組件參考了 .NET Framework,此情形不受支援。 Changes must be within bounds of SourceText - Changes must be within bounds of SourceText + 變更必須在 SourceText 的界限內 @@ -51,7 +51,7 @@ Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'. - Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'. + 其他檔案不屬於基礎 'CompilationWithAnalyzers'。 @@ -126,7 +126,7 @@ The provided SourceText must have an explicit encoding set. - The provided SourceText must have an explicit encoding set. + 提供的 SourceText 必須有明確的編碼集。 'SourceText' is not localizable. @@ -336,12 +336,12 @@ Return type can't be a value type, pointer, by-ref or open generic type - 傳回類型不可為值類型、指標、by-ref 或開放式泛型類型。 + 傳回類型不可為值類型、指標、by-ref 或開放式泛型類型 Return type can't be void, by-ref or open generic type - 傳回類型不可為 void、by-ref 或開放式泛型類型。 + 傳回類型不可為 void、by-ref 或開放式泛型類型 @@ -376,12 +376,12 @@ Empty or invalid resource name - 資源名稱是空的,或其無效。 + 資源名稱是空的,或其無效 Empty or invalid file name - 檔案名稱是空的,或其無效。 + 檔案名稱是空的,或其無效 @@ -576,12 +576,12 @@ Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' - Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' + 因為全域分析器組態區段名稱 '{0}' 不是絕對路徑,所以無效。將忽略區段。區段已在以下檔案中宣告: '{1}' {0}: invalid section name, {1} path to global config Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. - Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. + 因為全域分析器組態區段名稱不是絕對路徑,所以無效。將忽略區段。 @@ -985,7 +985,7 @@ Deserialization reader for '{0}' read incorrect number of values. - {0}' 的還原序列化讀取器所讀取的值數目不正確。 + '{0}' 的還原序列化讀取器所讀取的值數目不正確。 diff --git a/src/Compilers/Server/VBCSCompiler/AnalyzerConsistencyChecker.cs b/src/Compilers/Server/VBCSCompiler/AnalyzerConsistencyChecker.cs index 86e2b22ec2eb5..4641ff1634311 100644 --- a/src/Compilers/Server/VBCSCompiler/AnalyzerConsistencyChecker.cs +++ b/src/Compilers/Server/VBCSCompiler/AnalyzerConsistencyChecker.cs @@ -15,32 +15,33 @@ namespace Microsoft.CodeAnalysis.CompilerServer { internal static class AnalyzerConsistencyChecker { - private static readonly ImmutableArray s_defaultIgnorableReferenceNames = ImmutableArray.Create("mscorlib", "System", "Microsoft.CodeAnalysis", "netstandard"); - - public static bool Check(string baseDirectory, IEnumerable analyzerReferences, IAnalyzerAssemblyLoader loader, IEnumerable? ignorableReferenceNames = null) + public static bool Check( + string baseDirectory, + IEnumerable analyzerReferences, + IAnalyzerAssemblyLoader loader, + ICompilerServerLogger? logger = null) { - if (ignorableReferenceNames == null) - { - ignorableReferenceNames = s_defaultIgnorableReferenceNames; - } - try { - CompilerServerLogger.Log("Begin Analyzer Consistency Check"); - return CheckCore(baseDirectory, analyzerReferences, loader, ignorableReferenceNames); + logger?.Log("Begin Analyzer Consistency Check"); + return CheckCore(baseDirectory, analyzerReferences, loader, logger); } catch (Exception e) { - CompilerServerLogger.LogException(e, "Analyzer Consistency Check"); + logger?.LogException(e, "Analyzer Consistency Check"); return false; } finally { - CompilerServerLogger.Log("End Analyzer Consistency Check"); + logger?.Log("End Analyzer Consistency Check"); } } - private static bool CheckCore(string baseDirectory, IEnumerable analyzerReferences, IAnalyzerAssemblyLoader loader, IEnumerable ignorableReferenceNames) + private static bool CheckCore( + string baseDirectory, + IEnumerable analyzerReferences, + IAnalyzerAssemblyLoader loader, + ICompilerServerLogger? logger) { var resolvedPaths = new List(); @@ -59,21 +60,6 @@ private static bool CheckCore(string baseDirectory, IEnumerable missingDependency.Name.StartsWith(name))) - { - CompilerServerLogger.LogError($"Analyzer assembly {resolvedPath} depends on '{missingDependency}' but it was not found."); - return false; - } - } - } - // Register analyzers and their dependencies upfront, // so that assembly references can be resolved: foreach (var resolvedPath in resolvedPaths) @@ -98,7 +84,7 @@ private static bool CheckCore(string baseDirectory, IEnumerable new NamedPipeClientConnectionHost(pipeName); + internal static IClientConnectionHost CreateClientConnectionHost(string pipeName, ICompilerServerLogger logger) => new NamedPipeClientConnectionHost(pipeName, logger); - internal static ICompilerServerHost CreateCompilerServerHost() + internal static ICompilerServerHost CreateCompilerServerHost(ICompilerServerLogger logger) { // VBCSCompiler is installed in the same directory as csc.exe and vbc.exe which is also the // location of the response files. @@ -104,12 +106,12 @@ internal static ICompilerServerHost CreateCompilerServerHost() var clientDirectory = AppDomain.CurrentDomain.BaseDirectory!; var sdkDirectory = BuildClient.GetSystemSdkDirectory(); - return new CompilerServerHost(clientDirectory, sdkDirectory); + return new CompilerServerHost(clientDirectory, sdkDirectory, logger); } private async Task ConnectForShutdownAsync(string pipeName, int timeout) { - return await BuildServerConnection.TryConnectToServerAsync(pipeName, timeout, cancellationToken: default).ConfigureAwait(false); + return await BuildServerConnection.TryConnectToServerAsync(pipeName, timeout, _logger, cancellationToken: default).ConfigureAwait(false); } private static string? GetDefaultPipeName() @@ -130,8 +132,8 @@ internal int RunServer( { keepAlive ??= GetKeepAliveTimeout(); listener ??= new EmptyDiagnosticListener(); - clientConnectionHost ??= CreateClientConnectionHost(pipeName); - compilerServerHost ??= CreateCompilerServerHost(); + compilerServerHost ??= CreateCompilerServerHost(_logger); + clientConnectionHost ??= CreateClientConnectionHost(pipeName, _logger); // Grab the server mutex to prevent multiple servers from starting with the same // pipename and consuming excess resources. If someone else holds the mutex @@ -146,7 +148,7 @@ internal int RunServer( return CommonCompiler.Failed; } - CompilerServerLogger.Log("Keep alive timeout is: {0} milliseconds.", keepAlive?.TotalMilliseconds ?? 0); + compilerServerHost.Logger.Log("Keep alive timeout is: {0} milliseconds.", keepAlive?.TotalMilliseconds ?? 0); FatalError.Handler = FailFast.OnFatalException; var dispatcher = new ServerDispatcher(compilerServerHost, clientConnectionHost, listener); @@ -162,10 +164,12 @@ internal static int CreateAndRunServer( IDiagnosticListener? listener = null, TimeSpan? keepAlive = null, NameValueCollection? appSettings = null, + ICompilerServerLogger? logger = null, CancellationToken cancellationToken = default) { appSettings ??= new NameValueCollection(); - var controller = new BuildServerController(appSettings); + logger ??= EmptyCompilerServerLogger.Instance; + var controller = new BuildServerController(appSettings, logger); return controller.RunServer(pipeName, compilerServerHost, clientConnectionHost, listener, keepAlive, cancellationToken); } diff --git a/src/Compilers/Server/VBCSCompiler/ClientConnectionHandler.cs b/src/Compilers/Server/VBCSCompiler/ClientConnectionHandler.cs index e30e875d3ab1a..3ada2bf762f97 100644 --- a/src/Compilers/Server/VBCSCompiler/ClientConnectionHandler.cs +++ b/src/Compilers/Server/VBCSCompiler/ClientConnectionHandler.cs @@ -21,6 +21,7 @@ namespace Microsoft.CodeAnalysis.CompilerServer internal sealed class ClientConnectionHandler { internal ICompilerServerHost CompilerServerHost { get; } + internal ICompilerServerLogger Logger => CompilerServerHost.Logger; internal ClientConnectionHandler(ICompilerServerHost compilerServerHost) { @@ -42,7 +43,7 @@ internal async Task ProcessAsync( } catch (Exception ex) { - CompilerServerLogger.LogException(ex, $"Error processing request for client"); + Logger.LogException(ex, $"Error processing request for client"); return CompletionData.RequestError; } @@ -87,7 +88,7 @@ async Task ProcessCore() cancellationToken).ConfigureAwait(false); } - if (!Environment.Is64BitProcess && !MemoryHelper.IsMemoryAvailable()) + if (!Environment.Is64BitProcess && !MemoryHelper.IsMemoryAvailable(Logger)) { return await WriteBuildResponseAsync( clientConnection, @@ -100,14 +101,14 @@ async Task ProcessCore() } } - private static async Task WriteBuildResponseAsync(IClientConnection clientConnection, BuildResponse response, CompletionData completionData, CancellationToken cancellationToken) + private async Task WriteBuildResponseAsync(IClientConnection clientConnection, BuildResponse response, CompletionData completionData, CancellationToken cancellationToken) { var message = response switch { RejectedBuildResponse r => $"Writing {r.Type} response '{r.Reason}' for {clientConnection.LoggingIdentifier}", _ => $"Writing {response.Type} response for {clientConnection.LoggingIdentifier}" }; - CompilerServerLogger.Log(message); + Logger.Log(message); await clientConnection.WriteBuildResponseAsync(response, cancellationToken).ConfigureAwait(false); return completionData; } @@ -142,7 +143,7 @@ private async Task ProcessCompilationRequestAsync(IClientConnect { // The compilation task should never throw. If it does we need to assume that the compiler is // in a bad state and need to issue a RequestError - CompilerServerLogger.LogException(ex, $"Exception running compilation for {clientConnection.LoggingIdentifier}"); + Logger.LogException(ex, $"Exception running compilation for {clientConnection.LoggingIdentifier}"); response = new RejectedBuildResponse($"Exception during compilation: {ex.Message}"); completionData = CompletionData.RequestError; } diff --git a/src/Compilers/Server/VBCSCompiler/CompilerRequestHandler.cs b/src/Compilers/Server/VBCSCompiler/CompilerRequestHandler.cs index 2c5d5b25ec016..bd16c6a19e14d 100644 --- a/src/Compilers/Server/VBCSCompiler/CompilerRequestHandler.cs +++ b/src/Compilers/Server/VBCSCompiler/CompilerRequestHandler.cs @@ -57,15 +57,18 @@ internal sealed class CompilerServerHost : ICompilerServerHost /// private string SdkDirectory { get; } - internal CompilerServerHost(string clientDirectory, string sdkDirectory) + public ICompilerServerLogger Logger { get; } + + internal CompilerServerHost(string clientDirectory, string sdkDirectory, ICompilerServerLogger logger) { ClientDirectory = clientDirectory; SdkDirectory = sdkDirectory; + Logger = logger; } private bool CheckAnalyzers(string baseDirectory, ImmutableArray analyzers) { - return AnalyzerConsistencyChecker.Check(baseDirectory, analyzers, AnalyzerAssemblyLoader); + return AnalyzerConsistencyChecker.Check(baseDirectory, analyzers, AnalyzerAssemblyLoader, logger: Logger); } public bool TryCreateCompiler(RunRequest request, BuildPaths buildPaths, [NotNullWhen(true)] out CommonCompiler? compiler) @@ -96,7 +99,7 @@ public bool TryCreateCompiler(RunRequest request, BuildPaths buildPaths, [NotNul public BuildResponse RunCompilation(RunRequest request, CancellationToken cancellationToken) { - Log($@" + Logger.Log($@" Run Compilation CurrentDirectory = '{request.WorkingDirectory} LIB = '{request.LibDirectory}'"); @@ -128,11 +131,11 @@ Run Compilation return new AnalyzerInconsistencyBuildResponse(); } - Log($"Begin {request.Language} compiler run"); + Logger.Log($"Begin {request.Language} compiler run"); TextWriter output = new StringWriter(CultureInfo.InvariantCulture); int returnCode = compiler.Run(output, cancellationToken); var outputString = output.ToString(); - Log(@$" + Logger.Log(@$" End {request.Language} Compilation complete. Return code: {returnCode} Output: diff --git a/src/Compilers/Server/VBCSCompiler/ICompilerServerHost.cs b/src/Compilers/Server/VBCSCompiler/ICompilerServerHost.cs index 7c30d81c4267f..da1f26b49c850 100644 --- a/src/Compilers/Server/VBCSCompiler/ICompilerServerHost.cs +++ b/src/Compilers/Server/VBCSCompiler/ICompilerServerHost.cs @@ -15,6 +15,8 @@ namespace Microsoft.CodeAnalysis.CompilerServer { internal interface ICompilerServerHost { + ICompilerServerLogger Logger { get; } + BuildResponse RunCompilation(RunRequest request, CancellationToken cancellationToken); } } diff --git a/src/Compilers/Server/VBCSCompiler/MemoryHelper.cs b/src/Compilers/Server/VBCSCompiler/MemoryHelper.cs index 5780548ee6731..efd756ad6efb5 100644 --- a/src/Compilers/Server/VBCSCompiler/MemoryHelper.cs +++ b/src/Compilers/Server/VBCSCompiler/MemoryHelper.cs @@ -32,7 +32,7 @@ private MemoryHelper() public ulong AvailableVirtual; public ulong Reserved; //always 0 - public static bool IsMemoryAvailable() + public static bool IsMemoryAvailable(ICompilerServerLogger logger) { if (!PlatformInformation.IsWindows) { @@ -53,7 +53,7 @@ public static bool IsMemoryAvailable() unit = "KB"; } - CompilerServerLogger.Log("Free memory: {1}{0} of {2}{0}.", unit, free >> shift, max >> shift); + logger.Log("Free memory: {1}{0} of {2}{0}.", unit, free >> shift, max >> shift); return free >= 800 << 20; // Value (500MB) is arbitrary; feel free to improve. } diff --git a/src/Compilers/Server/VBCSCompiler/NamedPipeClientConnection.cs b/src/Compilers/Server/VBCSCompiler/NamedPipeClientConnection.cs index 20b861d4e652f..fdb3cf20e0670 100644 --- a/src/Compilers/Server/VBCSCompiler/NamedPipeClientConnection.cs +++ b/src/Compilers/Server/VBCSCompiler/NamedPipeClientConnection.cs @@ -21,15 +21,17 @@ internal sealed class NamedPipeClientConnection : IClientConnection private TaskCompletionSource DisconnectTaskCompletionSource { get; } = new TaskCompletionSource(); public NamedPipeServerStream Stream { get; } + public ICompilerServerLogger Logger { get; } public string LoggingIdentifier { get; } public bool IsDisposed { get; private set; } public Task DisconnectTask => DisconnectTaskCompletionSource.Task; - internal NamedPipeClientConnection(NamedPipeServerStream stream, string loggingIdentifier) + internal NamedPipeClientConnection(NamedPipeServerStream stream, string loggingIdentifier, ICompilerServerLogger logger) { Stream = stream; LoggingIdentifier = loggingIdentifier; + Logger = logger; } public void Dispose() @@ -44,7 +46,7 @@ public void Dispose() } catch (Exception ex) { - CompilerServerLogger.LogException(ex, $"Error closing client connection {LoggingIdentifier}"); + Logger.LogException(ex, $"Error closing client connection {LoggingIdentifier}"); } IsDisposed = true; @@ -71,11 +73,11 @@ async Task MonitorDisconnect() { try { - await BuildServerConnection.MonitorDisconnectAsync(Stream, LoggingIdentifier, DisconnectCancellationTokenSource.Token).ConfigureAwait(false); + await BuildServerConnection.MonitorDisconnectAsync(Stream, LoggingIdentifier, Logger, DisconnectCancellationTokenSource.Token).ConfigureAwait(false); } catch (Exception ex) { - CompilerServerLogger.LogException(ex, $"Error monitoring disconnect {LoggingIdentifier}"); + Logger.LogException(ex, $"Error monitoring disconnect {LoggingIdentifier}"); } finally { diff --git a/src/Compilers/Server/VBCSCompiler/NamedPipeClientConnectionHost.cs b/src/Compilers/Server/VBCSCompiler/NamedPipeClientConnectionHost.cs index 419adf09aa9a7..2419128053043 100644 --- a/src/Compilers/Server/VBCSCompiler/NamedPipeClientConnectionHost.cs +++ b/src/Compilers/Server/VBCSCompiler/NamedPipeClientConnectionHost.cs @@ -35,11 +35,13 @@ internal ListenResult(NamedPipeClientConnection? connection = null, Exception? e private AsyncQueue? _queue; public string PipeName { get; } + public ICompilerServerLogger Logger { get; } public bool IsListening { get; private set; } - internal NamedPipeClientConnectionHost(string pipeName) + internal NamedPipeClientConnectionHost(string pipeName, ICompilerServerLogger logger) { PipeName = pipeName; + Logger = logger; } public void BeginListening() @@ -69,7 +71,7 @@ public void BeginListening() int clientLoggingIdentifier = 0; for (int i = 0; i < listenCount; i++) { - var task = Task.Run(() => ListenCoreAsync(PipeName, _queue, GetNextClientLoggingIdentifier, _cancellationTokenSource.Token)); + var task = Task.Run(() => ListenCoreAsync(PipeName, Logger, _queue, GetNextClientLoggingIdentifier, _cancellationTokenSource.Token)); _listenTasks[i] = task; } @@ -108,7 +110,7 @@ public void EndListening() } catch (Exception ex) { - CompilerServerLogger.LogException(ex, $"Cancelling server listens threw an exception"); + Logger.LogException(ex, $"Cancelling server listens threw an exception"); } try @@ -117,7 +119,7 @@ public void EndListening() } catch (Exception ex) { - CompilerServerLogger.LogException(ex, $"Listen tasks threw exception during {nameof(EndListening)}"); + Logger.LogException(ex, $"Listen tasks threw exception during {nameof(EndListening)}"); } _queue.Complete(); @@ -171,6 +173,7 @@ public async Task GetNextClientConnectionAsync() /// Used to cancel the connection sequence. private static async Task ListenCoreAsync( string pipeName, + ICompilerServerLogger logger, AsyncQueue queue, Func getClientLoggingIdentifier, CancellationToken cancellationToken) @@ -186,7 +189,7 @@ private static async Task ListenCoreAsync( // as Windows refusing to create the pipe for some reason // (out of handles?), or the pipe was disconnected before we // starting listening - CompilerServerLogger.Log($"Constructing pipe and waiting for connections '{pipeName}'"); + logger.Log($"Constructing pipe and waiting for connections '{pipeName}'"); pipeStream = NamedPipeUtil.CreateServer(pipeName); // The WaitForConnectionAsync API does not fully respect the provided CancellationToken @@ -209,19 +212,19 @@ private static async Task ListenCoreAsync( } await connectTask.ConfigureAwait(false); - CompilerServerLogger.Log("Pipe connection established."); - var connection = new NamedPipeClientConnection(pipeStream, getClientLoggingIdentifier()); + logger.Log("Pipe connection established."); + var connection = new NamedPipeClientConnection(pipeStream, getClientLoggingIdentifier(), logger); queue.Enqueue(new ListenResult(connection: connection)); } catch (OperationCanceledException) { // Expected when the host is shutting down. - CompilerServerLogger.Log($"Pipe connection cancelled"); + logger.Log($"Pipe connection cancelled"); pipeStream?.Dispose(); } catch (Exception ex) { - CompilerServerLogger.LogException(ex, $"Pipe connection error"); + logger.LogException(ex, $"Pipe connection error"); queue.Enqueue(new ListenResult(exception: ex)); pipeStream?.Dispose(); } diff --git a/src/Compilers/Server/VBCSCompiler/ServerDispatcher.cs b/src/Compilers/Server/VBCSCompiler/ServerDispatcher.cs index a6dfa33682018..7f379c1da9035 100644 --- a/src/Compilers/Server/VBCSCompiler/ServerDispatcher.cs +++ b/src/Compilers/Server/VBCSCompiler/ServerDispatcher.cs @@ -53,6 +53,7 @@ private enum State internal static readonly TimeSpan GCTimeout = TimeSpan.FromSeconds(30); private readonly ICompilerServerHost _compilerServerHost; + private readonly ICompilerServerLogger _logger; private readonly IClientConnectionHost _clientConnectionHost; private readonly IDiagnosticListener _diagnosticListener; private State _state; @@ -66,6 +67,7 @@ private enum State internal ServerDispatcher(ICompilerServerHost compilerServerHost, IClientConnectionHost clientConnectionHost, IDiagnosticListener? diagnosticListener = null) { _compilerServerHost = compilerServerHost; + _logger = compilerServerHost.Logger; _clientConnectionHost = clientConnectionHost; _diagnosticListener = diagnosticListener ?? new EmptyDiagnosticListener(); } @@ -119,12 +121,12 @@ public void ListenAndDispatchConnections(TimeSpan? keepAlive, CancellationToken } catch (Exception ex) { - CompilerServerLogger.LogException(ex, $"Error disposing of {nameof(_listenTask)}"); + _logger.LogException(ex, $"Error disposing of {nameof(_listenTask)}"); } } } } - CompilerServerLogger.Log($"End ListenAndDispatchConnections"); + _logger.Log($"End ListenAndDispatchConnections"); } public void ListenAndDispatchConnectionsCore(CancellationToken cancellationToken) @@ -217,7 +219,7 @@ private void ChangeToShuttingDown(string reason) return; } - CompilerServerLogger.Log($"Shutting down server: {reason}"); + _logger.Log($"Shutting down server: {reason}"); Debug.Assert(_state == State.Running); Debug.Assert(_clientConnectionHost.IsListening); @@ -290,27 +292,27 @@ private void HandleCompletedConnections() switch (completionData.Reason) { case CompletionReason.RequestCompleted: - CompilerServerLogger.Log("Client request completed"); + _logger.Log("Client request completed"); if (completionData.NewKeepAlive is { } keepAlive) { - CompilerServerLogger.Log($"Client changed keep alive to {keepAlive}"); + _logger.Log($"Client changed keep alive to {keepAlive}"); ChangeKeepAlive(keepAlive); } if (completionData.ShutdownRequest) { - CompilerServerLogger.Log("Client requested shutdown"); + _logger.Log("Client requested shutdown"); shutdown = true; } break; case CompletionReason.RequestError: - CompilerServerLogger.LogError("Client request failed"); + _logger.LogError("Client request failed"); shutdown = true; break; default: - CompilerServerLogger.LogError("Unexpected enum value"); + _logger.LogError("Unexpected enum value"); shutdown = true; break; } diff --git a/src/Compilers/Server/VBCSCompiler/VBCSCompiler.cs b/src/Compilers/Server/VBCSCompiler/VBCSCompiler.cs index 206b6ac4f6054..007fe40de92b6 100644 --- a/src/Compilers/Server/VBCSCompiler/VBCSCompiler.cs +++ b/src/Compilers/Server/VBCSCompiler/VBCSCompiler.cs @@ -13,6 +13,8 @@ internal static class VBCSCompiler { public static int Main(string[] args) { + using var logger = new CompilerServerLogger(); + NameValueCollection appSettings; try { @@ -33,30 +35,21 @@ public static int Main(string[] args) // is corrupted. This should not prevent the server from starting, but instead just revert // to the default configuration. appSettings = new NameValueCollection(); - CompilerServerLogger.LogException(ex, "Error loading application settings"); + logger.LogException(ex, "Error loading application settings"); } try { - var controller = new BuildServerController(appSettings); + var controller = new BuildServerController(appSettings, logger); return controller.Run(args); } - catch (FileNotFoundException e) - { - // Assume the exception was the result of a missing compiler assembly. - LogException(e); - } - catch (TypeInitializationException e) when (e.InnerException is FileNotFoundException) + catch (Exception e) { // Assume the exception was the result of a missing compiler assembly. - LogException((FileNotFoundException)e.InnerException); + logger.LogException(e, "Cannot start server"); } - return CommonCompiler.Failed; - } - private static void LogException(FileNotFoundException e) - { - CompilerServerLogger.LogException(e, "File not found"); + return CommonCompiler.Failed; } } } diff --git a/src/Compilers/Server/VBCSCompilerTests/AnalyzerConsistencyCheckerTests.cs b/src/Compilers/Server/VBCSCompilerTests/AnalyzerConsistencyCheckerTests.cs index b251cb0d5b26a..248406894dc48 100644 --- a/src/Compilers/Server/VBCSCompilerTests/AnalyzerConsistencyCheckerTests.cs +++ b/src/Compilers/Server/VBCSCompilerTests/AnalyzerConsistencyCheckerTests.cs @@ -12,14 +12,23 @@ using System.Reflection; using System.Text; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CommandLine; using Microsoft.CodeAnalysis.CSharp; using Roslyn.Test.Utilities; using Xunit; +using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { public class AnalyzerConsistencyCheckerTests : TestBase { + private ICompilerServerLogger Logger { get; } + + public AnalyzerConsistencyCheckerTests(ITestOutputHelper testOutputHelper) + { + Logger = new XunitCompilerServerLogger(testOutputHelper); + } + [Fact] public void MissingReference() { @@ -27,9 +36,9 @@ public void MissingReference() var alphaDll = directory.CreateFile("Alpha.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Alpha); var analyzerReferences = ImmutableArray.Create(new CommandLineAnalyzerReference("Alpha.dll")); - var result = AnalyzerConsistencyChecker.Check(directory.Path, analyzerReferences, new InMemoryAssemblyLoader()); + var result = AnalyzerConsistencyChecker.Check(directory.Path, analyzerReferences, new InMemoryAssemblyLoader(), Logger); - Assert.False(result); + Assert.True(result); } [Fact] @@ -47,7 +56,7 @@ public void AllChecksPassed() new CommandLineAnalyzerReference("Gamma.dll"), new CommandLineAnalyzerReference("Delta.dll")); - var result = AnalyzerConsistencyChecker.Check(directory.Path, analyzerReferences, new InMemoryAssemblyLoader()); + var result = AnalyzerConsistencyChecker.Check(directory.Path, analyzerReferences, new InMemoryAssemblyLoader(), Logger); Assert.True(result); } @@ -72,7 +81,7 @@ public void DifferingMvids() new CommandLineAnalyzerReference("Gamma.dll"), new CommandLineAnalyzerReference("Delta.dll")); - var result = AnalyzerConsistencyChecker.Check(directory.Path, analyzerReferences, assemblyLoader); + var result = AnalyzerConsistencyChecker.Check(directory.Path, analyzerReferences, assemblyLoader, Logger); Assert.False(result); } @@ -86,7 +95,7 @@ public void AssemblyLoadException() var analyzerReferences = ImmutableArray.Create( new CommandLineAnalyzerReference("Delta.dll")); - var result = AnalyzerConsistencyChecker.Check(directory.Path, analyzerReferences, TestAnalyzerAssemblyLoader.LoadNotImplemented); + var result = AnalyzerConsistencyChecker.Check(directory.Path, analyzerReferences, TestAnalyzerAssemblyLoader.LoadNotImplemented, Logger); Assert.False(result); } @@ -107,7 +116,7 @@ public void NetstandardIgnored() var analyzerReferences = ImmutableArray.Create(new CommandLineAnalyzerReference(name)); - var result = AnalyzerConsistencyChecker.Check(directory.Path, analyzerReferences, new InMemoryAssemblyLoader()); + var result = AnalyzerConsistencyChecker.Check(directory.Path, analyzerReferences, new InMemoryAssemblyLoader(), Logger); Assert.True(result); } diff --git a/src/Compilers/Server/VBCSCompilerTests/BuildClientTests.cs b/src/Compilers/Server/VBCSCompilerTests/BuildClientTests.cs index f1b7c0983fecb..f33240edf1af9 100644 --- a/src/Compilers/Server/VBCSCompilerTests/BuildClientTests.cs +++ b/src/Compilers/Server/VBCSCompilerTests/BuildClientTests.cs @@ -21,6 +21,7 @@ using System.IO.Pipes; using System.Security.AccessControl; using System.Security.Principal; +using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { @@ -31,14 +32,16 @@ public sealed class ServerTests : BuildClientTests private readonly string _pipeName = Guid.NewGuid().ToString("N"); private readonly BuildPaths _buildPaths; private readonly List _serverDataList = new List(); + private readonly XunitCompilerServerLogger _logger; private bool _allowServer = true; private int _failedCreatedServerCount = 0; - public ServerTests() + public ServerTests(ITestOutputHelper testOutputHelper) { _buildPaths = ServerUtil.CreateBuildPaths( workingDir: Temp.CreateDirectory().Path, tempDir: Temp.CreateDirectory().Path); + _logger = new XunitCompilerServerLogger(testOutputHelper); } public override void Dispose() @@ -59,13 +62,13 @@ private BuildClient CreateClient( { language ??= RequestLanguage.CSharpCompile; compileFunc ??= delegate { return 0; }; - createServerFunc ??= ((_, pipeName) => TryCreateServer(pipeName)); - return new BuildClient(language.Value, compileFunc, createServerFunc); + createServerFunc ??= ((_, pipeName, _) => TryCreateServer(pipeName)); + return new BuildClient(language.Value, compileFunc, _logger, createServerFunc); } - private ServerData CreateServer(string pipeName, ICompilerServerHost compilerServerHost = null) + private ServerData CreateServer(string pipeName) { - var serverData = ServerUtil.CreateServer(pipeName, compilerServerHost).GetAwaiter().GetResult(); + var serverData = ServerUtil.CreateServer(_logger, pipeName).GetAwaiter().GetResult(); _serverDataList.Add(serverData); return serverData; } @@ -157,7 +160,7 @@ await Assert.ThrowsAnyAsync( async Task tryConnectToNamedPipe(int timeoutMs, CancellationToken cancellationToken) { - using var pipeStream = await BuildServerConnection.TryConnectToServerAsync(pipeName, timeoutMs, cancellationToken); + using var pipeStream = await BuildServerConnection.TryConnectToServerAsync(pipeName, timeoutMs, _logger, cancellationToken); return pipeStream != null; } } diff --git a/src/Compilers/Server/VBCSCompilerTests/BuildServerControllerTests.cs b/src/Compilers/Server/VBCSCompilerTests/BuildServerControllerTests.cs index 6b2443ca45919..56efd7ddaaf91 100644 --- a/src/Compilers/Server/VBCSCompilerTests/BuildServerControllerTests.cs +++ b/src/Compilers/Server/VBCSCompilerTests/BuildServerControllerTests.cs @@ -7,16 +7,15 @@ using System; using System.Collections.Specialized; using Xunit; +using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { public sealed class BuildServerControllerTests : IDisposable { - public void Dispose() { NamedPipeTestUtil.DisposeAll(); - } public sealed class GetKeepAliveTimeoutTests @@ -24,9 +23,9 @@ public sealed class GetKeepAliveTimeoutTests private readonly NameValueCollection _appSettings = new NameValueCollection(); private readonly BuildServerController _controller; - public GetKeepAliveTimeoutTests() + public GetKeepAliveTimeoutTests(ITestOutputHelper testOutputHelper) { - _controller = new BuildServerController(_appSettings); + _controller = new BuildServerController(_appSettings, new XunitCompilerServerLogger(testOutputHelper)); } [Fact] diff --git a/src/Compilers/Server/VBCSCompilerTests/CompilerServerApiTest.cs b/src/Compilers/Server/VBCSCompilerTests/CompilerServerApiTest.cs index 0d6dbd4471548..00936cca5a93b 100644 --- a/src/Compilers/Server/VBCSCompilerTests/CompilerServerApiTest.cs +++ b/src/Compilers/Server/VBCSCompilerTests/CompilerServerApiTest.cs @@ -19,11 +19,19 @@ using System.IO; using Microsoft.CodeAnalysis.Test.Utilities; using static Microsoft.CodeAnalysis.CommandLine.BuildResponse; +using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { public class CompilerServerApiTest : TestBase { + internal ICompilerServerLogger Logger { get; } + + public CompilerServerApiTest(ITestOutputHelper testOutputHelper) + { + Logger = new XunitCompilerServerLogger(testOutputHelper); + } + private const string HelloWorldSourceText = @" using System; class Hello @@ -168,7 +176,7 @@ public void MutexAcquiredWhenRunningServer() public async Task RejectEmptyTempPath() { using var temp = new TempRoot(); - using var serverData = await ServerUtil.CreateServer().ConfigureAwait(false); + using var serverData = await ServerUtil.CreateServer(Logger).ConfigureAwait(false); var request = BuildRequest.Create(RequestLanguage.CSharpCompile, workingDirectory: temp.CreateDirectory().Path, tempDirectory: null, compilerHash: BuildProtocolConstants.GetCommitHash(), libDirectory: null, args: Array.Empty()); var response = await serverData.SendAsync(request).ConfigureAwait(false); Assert.Equal(ResponseType.Rejected, response.Type); @@ -177,7 +185,7 @@ public async Task RejectEmptyTempPath() [Fact] public async Task IncorrectProtocolReturnsMismatchedVersionResponse() { - using var serverData = await ServerUtil.CreateServer().ConfigureAwait(false); + using var serverData = await ServerUtil.CreateServer(Logger).ConfigureAwait(false); var buildResponse = await serverData.SendAsync(new BuildRequest(1, RequestLanguage.CSharpCompile, "abc", new List { })).ConfigureAwait(false); Assert.Equal(BuildResponse.ResponseType.MismatchedVersion, buildResponse.Type); } @@ -185,7 +193,7 @@ public async Task IncorrectProtocolReturnsMismatchedVersionResponse() [Fact] public async Task IncorrectServerHashReturnsIncorrectHashResponse() { - using var serverData = await ServerUtil.CreateServer().ConfigureAwait(false); + using var serverData = await ServerUtil.CreateServer(Logger).ConfigureAwait(false); var buildResponse = await serverData.SendAsync(new BuildRequest(BuildProtocolConstants.ProtocolVersion, RequestLanguage.CSharpCompile, "abc", new List { })).ConfigureAwait(false); Assert.Equal(BuildResponse.ResponseType.IncorrectHash, buildResponse.Type); } diff --git a/src/Compilers/Server/VBCSCompilerTests/CompilerServerTests.cs b/src/Compilers/Server/VBCSCompilerTests/CompilerServerTests.cs index 5759a18805acd..d05eb3effeb15 100644 --- a/src/Compilers/Server/VBCSCompilerTests/CompilerServerTests.cs +++ b/src/Compilers/Server/VBCSCompilerTests/CompilerServerTests.cs @@ -14,10 +14,12 @@ using System.Text; using System.Threading; using System.Threading.Tasks; +using Castle.Core.Resource; using Microsoft.CodeAnalysis.CommandLine; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; +using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { @@ -59,10 +61,12 @@ End Sub }; private readonly TempDirectory _tempDirectory; + private readonly ICompilerServerLogger _logger; - public CompilerServerUnitTests() + public CompilerServerUnitTests(ITestOutputHelper testOutputHelper) { _tempDirectory = Temp.CreateDirectory(); + _logger = new XunitCompilerServerLogger(testOutputHelper); } #region Helpers @@ -182,7 +186,7 @@ private static (T Result, string Output) UseTextWriter(Encoding encoding, Fun } } - internal static (int ExitCode, string Output) RunCommandLineCompiler( + internal (int ExitCode, string Output) RunCommandLineCompiler( RequestLanguage language, string argumentsSingle, TempDirectory currentDirectory, @@ -205,7 +209,7 @@ internal static (int ExitCode, string Output) RunCommandLineCompiler( // case where these tests are run under extreme load. In high load scenarios the // client will correctly drop down to a local compilation if the server doesn't respond // fast enough. - var client = ServerUtil.CreateBuildClient(language, timeoutOverride: Timeout.Infinite); + var client = ServerUtil.CreateBuildClient(language, _logger, timeoutOverride: Timeout.Infinite); var sdkDir = ServerUtil.DefaultSdkDirectory; @@ -220,6 +224,51 @@ internal static (int ExitCode, string Output) RunCommandLineCompiler( return (result.ExitCode, output); } + /// + /// Compiles some source code and returns the bytes that were contained in the compiled DLL file. + /// + /// Each time that this function is called, it will be compiled in a different directory. + /// + /// The default flags are "/shared /deterministic+ /nologo /t:library". + /// + /// The source code for the program that will be compiled + /// An array of bytes that were read from the compiled DLL + private async Task<(byte[] assemblyBytes, string finalFlags)> CompileAndGetBytes(string source, string flags) + { + // Setup + var tempDir = Temp.CreateDirectory(); + var srcFile = tempDir.CreateFile("test.cs").WriteAllText(source).Path; + var outFile = srcFile.Replace("test.cs", "test.dll"); + + try + { + string finalFlags = null; + using (var serverData = await ServerUtil.CreateServer(_logger)) + { + finalFlags = $"{flags} /shared:{serverData.PipeName} /pathmap:{tempDir.Path}=/ /out:{outFile} {srcFile}"; + var result = RunCommandLineCompiler( + CSharpCompilerClientExecutable, + finalFlags, + currentDirectory: tempDir); + if (result.ExitCode != 0) + { + AssertEx.Fail($"Deterministic compile failed \n stdout: { result.Output }"); + } + var listener = await serverData.Complete().ConfigureAwait(false); + Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single()); + } + var bytes = File.ReadAllBytes(outFile); + AssertEx.NotNull(bytes); + + return (bytes, finalFlags); + } + finally + { + File.Delete(srcFile); + File.Delete(outFile); + } + } + private static DisposableFile GetResultFile(TempDirectory directory, string resultFileName) { return new DisposableFile(Path.Combine(directory.Path, resultFileName)); @@ -260,7 +309,7 @@ await ApplyEnvironmentVariables( new[] { new KeyValuePair("TMPDIR", newTempDir.Path) }, async () => { - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); var result = RunCommandLineCompiler( CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} /nologo hello.cs", @@ -279,7 +328,7 @@ public async Task FallbackToCsc() { // Verify csc will fall back to command line when server fails to process var testableCompilerServerHost = new TestableCompilerServerHost(delegate { throw new Exception(); }); - using var serverData = await ServerUtil.CreateServer(compilerServerHost: testableCompilerServerHost); + using var serverData = await ServerUtil.CreateServer(_logger, compilerServerHost: testableCompilerServerHost); var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} /nologo hello.cs", _tempDirectory, s_helloWorldSrcCs, shouldRunOnServer: false); VerifyResultAndOutput(result, _tempDirectory, "Hello, world."); @@ -292,7 +341,7 @@ public async Task CscFallBackOutputNoUtf8() { // Verify csc will fall back to command line when server fails to process var testableCompilerServerHost = new TestableCompilerServerHost(delegate { throw new Exception(); }); - using var serverData = await ServerUtil.CreateServer(compilerServerHost: testableCompilerServerHost); + using var serverData = await ServerUtil.CreateServer(_logger, compilerServerHost: testableCompilerServerHost); var files = new Dictionary { { "hello.cs", "♕" } }; var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} /nologo hello.cs", _tempDirectory, files, redirectEncoding: Encoding.ASCII, shouldRunOnServer: false); @@ -309,7 +358,7 @@ public async Task CscFallBackOutputUtf8() var srcFile = _tempDirectory.CreateFile("test.cs").WriteAllText("♕").Path; var testableCompilerServerHost = new TestableCompilerServerHost(delegate { throw new Exception(); }); - using var serverData = await ServerUtil.CreateServer(compilerServerHost: testableCompilerServerHost); + using var serverData = await ServerUtil.CreateServer(_logger, compilerServerHost: testableCompilerServerHost); var result = RunCommandLineCompiler( CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} /utf8output /nologo /t:library {srcFile}", @@ -331,7 +380,7 @@ public async Task VbcFallbackNoUtf8() var srcFile = _tempDirectory.CreateFile("test.vb").WriteAllText("♕").Path; var testableCompilerServerHost = new TestableCompilerServerHost(delegate { throw new Exception(); }); - using var serverData = await ServerUtil.CreateServer(compilerServerHost: testableCompilerServerHost); + using var serverData = await ServerUtil.CreateServer(_logger, compilerServerHost: testableCompilerServerHost); var result = RunCommandLineCompiler( BasicCompilerClientExecutable, $"/shared:{serverData.PipeName} /vbruntime* /nologo test.vb", @@ -355,7 +404,7 @@ public async Task VbcFallbackUtf8() var srcFile = _tempDirectory.CreateFile("test.vb").WriteAllText("♕").Path; var testableCompilerServerHost = new TestableCompilerServerHost(delegate { throw new Exception(); }); - using var serverData = await ServerUtil.CreateServer(compilerServerHost: testableCompilerServerHost); + using var serverData = await ServerUtil.CreateServer(_logger, compilerServerHost: testableCompilerServerHost); var result = RunCommandLineCompiler( BasicCompilerClientExecutable, $"/shared:{serverData.PipeName} /vbruntime* /utf8output /nologo /t:library {srcFile}", @@ -377,7 +426,7 @@ public async Task VbcFallbackUtf8() public async Task FallbackToVbc() { var testableCompilerServerHost = new TestableCompilerServerHost(delegate { throw new Exception(); }); - using var serverData = await ServerUtil.CreateServer(compilerServerHost: testableCompilerServerHost); + using var serverData = await ServerUtil.CreateServer(_logger, compilerServerHost: testableCompilerServerHost); var result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"/shared:{serverData.PipeName} /nologo /vbruntime* hello.vb", _tempDirectory, s_helloWorldSrcVb, shouldRunOnServer: false); VerifyResultAndOutput(result, _tempDirectory, "Hello from VB"); @@ -390,7 +439,7 @@ public async Task FallbackToVbc() [Trait(Traits.Environment, Traits.Environments.VSProductInstall)] public async Task HelloWorldCS() { - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} /nologo hello.cs", _tempDirectory, s_helloWorldSrcCs); VerifyResultAndOutput(result, _tempDirectory, "Hello, world."); @@ -403,7 +452,7 @@ public async Task HelloWorldCS() [Trait(Traits.Environment, Traits.Environments.VSProductInstall)] public async Task HelloWorldCSDashShared() { - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"-shared:{serverData.PipeName} /nologo hello.cs", _tempDirectory, s_helloWorldSrcCs); VerifyResultAndOutput(result, _tempDirectory, "Hello, world."); @@ -432,7 +481,7 @@ public void CompilerBinariesAreNotX86() [Trait(Traits.Environment, Traits.Environments.VSProductInstall)] public async Task Platformx86MscorlibCsc() { - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); var files = new Dictionary { { "c.cs", "class C {}" } }; var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} /nologo /t:library /platform:x86 c.cs", @@ -447,7 +496,7 @@ public async Task Platformx86MscorlibCsc() [Trait(Traits.Environment, Traits.Environments.VSProductInstall)] public async Task Platformx86MscorlibVbc() { - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); var files = new Dictionary { { "c.vb", "Class C\nEnd Class" } }; var result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"/shared:{serverData.PipeName} /vbruntime* /nologo /t:library /platform:x86 c.vb", @@ -462,7 +511,7 @@ public async Task Platformx86MscorlibVbc() [Trait(Traits.Environment, Traits.Environments.VSProductInstall)] public async Task ExtraMSCorLibCS() { - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} /nologo /r:mscorlib.dll hello.cs", _tempDirectory, @@ -476,7 +525,7 @@ public async Task ExtraMSCorLibCS() [Trait(Traits.Environment, Traits.Environments.VSProductInstall)] public async Task HelloWorldVB() { - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); var result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"/shared:{serverData.PipeName} /nologo /vbruntime* hello.vb", _tempDirectory, @@ -490,7 +539,7 @@ public async Task HelloWorldVB() [Trait(Traits.Environment, Traits.Environments.VSProductInstall)] public async Task ExtraMSCorLibVB() { - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); var result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"/shared:{serverData.PipeName} /nologo /r:mscorlib.dll /vbruntime* hello.vb", _tempDirectory, @@ -504,7 +553,7 @@ public async Task ExtraMSCorLibVB() [Trait(Traits.Environment, Traits.Environments.VSProductInstall)] public async Task CompileErrorsCS() { - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); Dictionary files = new Dictionary { { "hello.cs", @@ -531,7 +580,7 @@ static void Main() [Trait(Traits.Environment, Traits.Environments.VSProductInstall)] public async Task CompileErrorsVB() { - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); Dictionary files = new Dictionary { @@ -561,7 +610,7 @@ End Sub [Trait(Traits.Environment, Traits.Environments.VSProductInstall)] public async Task MissingFileErrorCS() { - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} missingfile.cs", _tempDirectory); // Should output errors, but not create output file. @@ -578,7 +627,7 @@ public async Task MissingFileErrorCS() [Trait(Traits.Environment, Traits.Environments.VSProductInstall)] public async Task MissingReferenceErrorCS() { - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} /r:missing.dll hello.cs", _tempDirectory, s_helloWorldSrcCs); @@ -597,7 +646,7 @@ public async Task MissingReferenceErrorCS() [Trait(Traits.Environment, Traits.Environments.VSProductInstall)] public async Task InvalidMetadataFileErrorCS() { - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); Dictionary files = new Dictionary { @@ -621,7 +670,7 @@ public async Task InvalidMetadataFileErrorCS() [Trait(Traits.Environment, Traits.Environments.VSProductInstall)] public async Task MissingFileErrorVB() { - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); var result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"/shared:{serverData.PipeName} /vbruntime* missingfile.vb", _tempDirectory); @@ -639,7 +688,7 @@ public async Task MissingFileErrorVB() [Trait(Traits.Environment, Traits.Environments.VSProductInstall)] public async Task MissingReferenceErrorVB() { - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); Dictionary files = new Dictionary { @@ -669,7 +718,7 @@ End Sub [Trait(Traits.Environment, Traits.Environments.VSProductInstall)] public async Task InvalidMetadataFileErrorVB() { - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); Dictionary files = new Dictionary { @@ -713,7 +762,7 @@ End Function End Class "}}; - using (var serverData = await ServerUtil.CreateServer()) + using (var serverData = await ServerUtil.CreateServer(_logger)) using (var tmpFile = GetResultFile(rootDirectory, "lib.dll")) { var result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"src1.vb /shared:{serverData.PipeName} /nologo /t:library /out:lib.dll", rootDirectory, files); @@ -817,7 +866,7 @@ public async Task ReferenceCachingCS() { TempDirectory rootDirectory = _tempDirectory.CreateDirectory("ReferenceCachingCS"); - using (var serverData = await ServerUtil.CreateServer()) + using (var serverData = await ServerUtil.CreateServer(_logger)) using (var tmpFile = GetResultFile(rootDirectory, "lib.dll")) { // Create DLL "lib.dll" @@ -923,7 +972,7 @@ public static void Main() GC.KeepAlive(rootDirectory); } - private static Task RunCompilationAsync(RequestLanguage language, string pipeName, int i, TempDirectory compilationDir) + private Task RunCompilationAsync(RequestLanguage language, string pipeName, int i, TempDirectory compilationDir) { string sourceFile; string exeFileName; @@ -985,7 +1034,7 @@ End Sub [Trait(Traits.Environment, Traits.Environments.VSProductInstall)] public async Task MultipleSimultaneousCompiles() { - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); // Run this many compiles simultaneously in different directories. const int numberOfCompiles = 20; @@ -1021,7 +1070,7 @@ public static string GetString() { return ""library1""; } }"}}; - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"src1.cs /shared:{serverData.PipeName} /nologo /t:library /out:" + Path.Combine(libDirectory.Path, "lib.dll"), @@ -1072,7 +1121,7 @@ End Function End Class "}}; - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); var result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"src1.vb /shared:{serverData.PipeName} /vbruntime* /nologo /t:library /out:" + Path.Combine(libDirectory.Path, "lib.dll"), @@ -1111,7 +1160,7 @@ public async Task Utf8Output_WithRedirecting_Off_Shared() { var srcFile = _tempDirectory.CreateFile("test.cs").WriteAllText("♕").Path; - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); var result = RunCommandLineCompiler( CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} /nologo /t:library {srcFile}", @@ -1134,7 +1183,7 @@ public async Task Utf8Output_WithRedirecting_Off_Share() var srcFile = _tempDirectory.CreateFile("test.vb").WriteAllText(@"♕").Path; var tempOut = _tempDirectory.CreateFile("output.txt"); - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); var result = RunCommandLineCompiler( BasicCompilerClientExecutable, $"/shared:{serverData.PipeName} /nologo /vbruntime* /t:library {srcFile}", @@ -1160,7 +1209,7 @@ public async Task Utf8Output_WithRedirecting_On_Shared_CS() { var srcFile = _tempDirectory.CreateFile("test.cs").WriteAllText("♕").Path; - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); var result = RunCommandLineCompiler( CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} /utf8output /nologo /t:library {srcFile}", @@ -1182,7 +1231,7 @@ public async Task Utf8Output_WithRedirecting_On_Shared_VB() { var srcFile = _tempDirectory.CreateFile("test.vb").WriteAllText(@"♕").Path; - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); var result = RunCommandLineCompiler( BasicCompilerClientExecutable, @@ -1223,7 +1272,7 @@ public System.Exception GetException() } "}}; - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"ref_mscorlib2.cs /shared:{serverData.PipeName} /nologo /nostdlib /noconfig /t:library /r:mscorlib20.dll", @@ -1263,7 +1312,7 @@ static void Main(string[] args) [Fact] public async Task Utf8OutputInRspFileCsc() { - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); var srcFile = _tempDirectory.CreateFile("test.cs").WriteAllText("♕").Path; var rspFile = _tempDirectory.CreateFile("temp.rsp").WriteAllText( @@ -1287,7 +1336,7 @@ public async Task Utf8OutputInRspFileCsc() [Fact] public async Task Utf8OutputInRspFileVbc() { - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); var srcFile = _tempDirectory.CreateFile("test.cs").WriteAllText("♕").Path; var rspFile = _tempDirectory.CreateFile("temp.rsp").WriteAllText( @@ -1353,7 +1402,7 @@ public void BadKeepAlive4() [WorkItem(1024619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024619")] public async Task Bug1024619_01() { - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); var srcFile = _tempDirectory.CreateFile("test.cs").WriteAllText("").Path; @@ -1387,7 +1436,7 @@ public async Task Bug1024619_01() [WorkItem(1024619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024619")] public async Task Bug1024619_02() { - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(_logger); var srcFile = _tempDirectory.CreateFile("test.vb").WriteAllText("").Path; @@ -1445,7 +1494,7 @@ public async Task MissingCompilerAssembly_CompilerServerHost() throw new FileNotFoundException(); }); - using var serverData = await ServerUtil.CreateServer(compilerServerHost: host).ConfigureAwait(false); + using var serverData = await ServerUtil.CreateServer(_logger, compilerServerHost: host).ConfigureAwait(false); var request = new BuildRequest(1, RequestLanguage.CSharpCompile, string.Empty, new BuildRequest.Argument[0]); var compileTask = serverData.SendAsync(request); var response = await compileTask.ConfigureAwait(false); @@ -1455,5 +1504,109 @@ public async Task MissingCompilerAssembly_CompilerServerHost() var listener = await serverData.Complete().ConfigureAwait(false); Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single()); } + + /// + /// Runs CompileAndGetBytes twice and compares the output. + /// + /// The source of the program that will be compiled + private async Task RunDeterministicTest(string source) + { + var flags = "/deterministic+ /nologo /t:library /pdb:none"; + var (first, finalFlags1) = await CompileAndGetBytes(source, flags); + var (second, finalFlags2) = await CompileAndGetBytes(source, flags); + Assert.Equal(first.Length, second.Length); + for (int i = 0; i < first.Length; i++) + { + if (first[i] != second[i]) + { + AssertEx.Fail($"Bytes were different at position { i } ({ first[i] } vs { second[i] }). Flags used were (\"{ finalFlags1 }\" vs \"{ finalFlags2 }\")"); + } + } + } + + [Fact] + public async Task DeterminismHelloWorld() + { + var source = @"using System; +class Hello +{ + static void Main() + { + Console.WriteLine(""Hello, world.""); + } +}"; + + await RunDeterministicTest(source); + } + + [Fact] + public async Task DeterminismCallerInfo() + { + var source = @"using System; +class CallerInfo { + public static void DoProcessing() + { + TraceMessage(""Something happened.""); + } + public static void TraceMessage(string message, + [System.Runtime.CompilerServices.CallerMemberName] string memberName = """", + [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = """", + [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0) + { + System.Diagnostics.Trace.WriteLine(""message: "" + message); + System.Diagnostics.Trace.WriteLine(""member name: "" + memberName); + System.Diagnostics.Trace.WriteLine(""source file path: "" + sourceFilePath); + System.Diagnostics.Trace.WriteLine(""source line number: "" + sourceLineNumber); + } + static void Main() { + DoProcessing(); + } +}"; + await RunDeterministicTest(source); + } + + [Fact] + public async Task DeterminismAnonType() + { + var source = @"using System; +class AnonType { + public static void Main() { + var person = new { firstName = ""john"", lastName = ""Smith"" }; + var date = new { year = 2015, month = ""jan"", day = 5 }; + var color = new { red = 255, green = 125, blue = 0 }; + + Console.WriteLine(person); + Console.WriteLine(date); + Console.WriteLine(color); + } +}"; + await RunDeterministicTest(source); + } + + [Fact] + public async Task DeterminismLineDirective() + { + var source = @"using System; +class CallerInfo { + public static void TraceMessage(string message, + [System.Runtime.CompilerServices.CallerMemberName] string memberName = """", + [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = """", + [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0) + { + System.Diagnostics.Trace.WriteLine(""message: "" + message); + System.Diagnostics.Trace.WriteLine(""member name: "" + memberName); + System.Diagnostics.Trace.WriteLine(""source file path: "" + sourceFilePath); + System.Diagnostics.Trace.WriteLine(""source line number: "" + sourceLineNumber); + } + static void Main() { + TraceMessage(""from main""); +#line 10 ""coolFile.cs"" + TraceMessage(""from the cool file""); +#line default + TraceMessage(""back in main""); + } +}"; + await RunDeterministicTest(source); + } } } diff --git a/src/Compilers/Server/VBCSCompilerTests/EndToEndDeterminismTest.cs b/src/Compilers/Server/VBCSCompilerTests/EndToEndDeterminismTest.cs deleted file mode 100644 index 015f3ca7390f7..0000000000000 --- a/src/Compilers/Server/VBCSCompilerTests/EndToEndDeterminismTest.cs +++ /dev/null @@ -1,168 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -#nullable disable - -using System.IO; -using System.Threading.Tasks; -using Roslyn.Test.Utilities; -using Xunit; -using Microsoft.CodeAnalysis.Test.Utilities; -using System.Linq; - -namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests -{ - public class EndToEndDeterminismTest : TestBase - { - private readonly string _flags = "/deterministic+ /nologo /t:library /pdb:none"; - - /// - /// Compiles some source code and returns the bytes that were contained in the compiled DLL file. - /// - /// Each time that this function is called, it will be compiled in a different directory. - /// - /// The default flags are "/shared /deterministic+ /nologo /t:library". - /// - /// The source code for the program that will be compiled - /// An array of bytes that were read from the compiled DLL - private async Task<(byte[] assemblyBytes, string finalFlags)> CompileAndGetBytes(string source) - { - // Setup - var tempDir = Temp.CreateDirectory(); - var srcFile = tempDir.CreateFile("test.cs").WriteAllText(source).Path; - var outFile = srcFile.Replace("test.cs", "test.dll"); - - try - { - string finalFlags = null; - using (var serverData = await ServerUtil.CreateServer()) - { - finalFlags = $"{ _flags } /shared:{ serverData.PipeName } /pathmap:{tempDir.Path}=/ /out:{ outFile } { srcFile }"; - var result = CompilerServerUnitTests.RunCommandLineCompiler( - CompilerServerUnitTests.CSharpCompilerClientExecutable, - finalFlags, - currentDirectory: tempDir); - if (result.ExitCode != 0) - { - AssertEx.Fail($"Deterministic compile failed \n stdout: { result.Output }"); - } - var listener = await serverData.Complete().ConfigureAwait(false); - Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single()); - } - var bytes = File.ReadAllBytes(outFile); - AssertEx.NotNull(bytes); - - return (bytes, finalFlags); - } - finally - { - File.Delete(srcFile); - File.Delete(outFile); - } - } - - /// - /// Runs CompileAndGetBytes twice and compares the output. - /// - /// The source of the program that will be compiled - private async Task RunDeterministicTest(string source) - { - var (first, finalFlags1) = await CompileAndGetBytes(source); - var (second, finalFlags2) = await CompileAndGetBytes(source); - Assert.Equal(first.Length, second.Length); - for (int i = 0; i < first.Length; i++) - { - if (first[i] != second[i]) - { - AssertEx.Fail($"Bytes were different at position { i } ({ first[i] } vs { second[i] }). Flags used were (\"{ finalFlags1 }\" vs \"{ finalFlags2 }\")"); - } - } - } - - [Fact] - public async Task HelloWorld() - { - var source = @"using System; -class Hello -{ - static void Main() - { - Console.WriteLine(""Hello, world.""); - } -}"; - - await RunDeterministicTest(source); - } - - [Fact] - public async Task CallerInfo() - { - var source = @"using System; -class CallerInfo { - public static void DoProcessing() - { - TraceMessage(""Something happened.""); - } - public static void TraceMessage(string message, - [System.Runtime.CompilerServices.CallerMemberName] string memberName = """", - [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = """", - [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0) - { - System.Diagnostics.Trace.WriteLine(""message: "" + message); - System.Diagnostics.Trace.WriteLine(""member name: "" + memberName); - System.Diagnostics.Trace.WriteLine(""source file path: "" + sourceFilePath); - System.Diagnostics.Trace.WriteLine(""source line number: "" + sourceLineNumber); - } - static void Main() { - DoProcessing(); - } -}"; - await RunDeterministicTest(source); - } - - [Fact] - public async Task AnonType() - { - var source = @"using System; -class AnonType { - public static void Main() { - var person = new { firstName = ""john"", lastName = ""Smith"" }; - var date = new { year = 2015, month = ""jan"", day = 5 }; - var color = new { red = 255, green = 125, blue = 0 }; - - Console.WriteLine(person); - Console.WriteLine(date); - Console.WriteLine(color); - } -}"; - await RunDeterministicTest(source); - } - - [Fact] - public async Task LineDirective() - { - var source = @"using System; -class CallerInfo { - public static void TraceMessage(string message, - [System.Runtime.CompilerServices.CallerMemberName] string memberName = """", - [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = """", - [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0) - { - System.Diagnostics.Trace.WriteLine(""message: "" + message); - System.Diagnostics.Trace.WriteLine(""member name: "" + memberName); - System.Diagnostics.Trace.WriteLine(""source file path: "" + sourceFilePath); - System.Diagnostics.Trace.WriteLine(""source line number: "" + sourceLineNumber); - } - static void Main() { - TraceMessage(""from main""); -#line 10 ""coolFile.cs"" - TraceMessage(""from the cool file""); -#line default - TraceMessage(""back in main""); - } -}"; - await RunDeterministicTest(source); - } - } -} diff --git a/src/Compilers/Server/VBCSCompilerTests/NamedPipeClientConnectionHostTests.cs b/src/Compilers/Server/VBCSCompilerTests/NamedPipeClientConnectionHostTests.cs index 0bdada71e2b74..d26aa7076a153 100644 --- a/src/Compilers/Server/VBCSCompilerTests/NamedPipeClientConnectionHostTests.cs +++ b/src/Compilers/Server/VBCSCompilerTests/NamedPipeClientConnectionHostTests.cs @@ -10,6 +10,7 @@ using Microsoft.CodeAnalysis.CommandLine; using Roslyn.Test.Utilities; using Xunit; +using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { @@ -17,9 +18,9 @@ public class NamedPipeClientConnectionHostTests : IDisposable { private readonly NamedPipeClientConnectionHost _host; - public NamedPipeClientConnectionHostTests() + public NamedPipeClientConnectionHostTests(ITestOutputHelper testOutputHelper) { - _host = new NamedPipeClientConnectionHost(ServerUtil.GetPipeName()); + _host = new NamedPipeClientConnectionHost(ServerUtil.GetPipeName(), new XunitCompilerServerLogger(testOutputHelper)); } public void Dispose() @@ -35,6 +36,7 @@ public void Dispose() private Task ConnectAsync(CancellationToken cancellationToken = default) => BuildServerConnection.TryConnectToServerAsync( _host.PipeName, timeoutMs: Timeout.Infinite, + logger: _host.Logger, cancellationToken); [ConditionalFact(typeof(WindowsOrLinuxOnly), Reason = "https://github.com/dotnet/runtime/issues/40301")] diff --git a/src/Compilers/Server/VBCSCompilerTests/ServerUtil.cs b/src/Compilers/Server/VBCSCompilerTests/ServerUtil.cs index 62dce5ae3c6e9..c2dccbddb76ac 100644 --- a/src/Compilers/Server/VBCSCompilerTests/ServerUtil.cs +++ b/src/Compilers/Server/VBCSCompilerTests/ServerUtil.cs @@ -55,17 +55,19 @@ internal sealed class ServerData : IDisposable internal CancellationTokenSource CancellationTokenSource { get; } internal Task ServerTask { get; } internal string PipeName { get; } + internal ICompilerServerLogger Logger { get; } - internal ServerData(CancellationTokenSource cancellationTokenSource, string pipeName, Task serverTask) + internal ServerData(CancellationTokenSource cancellationTokenSource, string pipeName, ICompilerServerLogger logger, Task serverTask) { CancellationTokenSource = cancellationTokenSource; PipeName = pipeName; + Logger = logger; ServerTask = serverTask; } internal async Task SendAsync(BuildRequest request, CancellationToken cancellationToken = default) { - using var client = await BuildServerConnection.TryConnectToServerAsync(PipeName, Timeout.Infinite, cancellationToken).ConfigureAwait(false); + using var client = await BuildServerConnection.TryConnectToServerAsync(PipeName, Timeout.Infinite, Logger, cancellationToken).ConfigureAwait(false); await request.WriteAsync(client).ConfigureAwait(false); return await BuildResponse.ReadAsync(client).ConfigureAwait(false); } @@ -111,6 +113,7 @@ internal static BuildPaths CreateBuildPaths(string workingDir, string tempDir) internal static string GetPipeName() => Guid.NewGuid().ToString().Substring(0, 10); internal static async Task CreateServer( + ICompilerServerLogger logger, string pipeName = null, ICompilerServerHost compilerServerHost = null, IClientConnectionHost clientConnectionHost = null, @@ -118,8 +121,8 @@ internal static async Task CreateServer( { // The total pipe path must be < 92 characters on Unix, so trim this down to 10 chars pipeName ??= GetPipeName(); - compilerServerHost ??= BuildServerController.CreateCompilerServerHost(); - clientConnectionHost ??= BuildServerController.CreateClientConnectionHost(pipeName); + compilerServerHost ??= BuildServerController.CreateCompilerServerHost(logger); + clientConnectionHost ??= BuildServerController.CreateClientConnectionHost(pipeName, logger); keepAlive ??= TimeSpan.FromMilliseconds(-1); var listener = new TestableDiagnosticListener(); @@ -145,18 +148,19 @@ internal static async Task CreateServer( await Task.Yield(); } - return new ServerData(cts, pipeName, task); + return new ServerData(cts, pipeName, logger, task); } internal static BuildClient CreateBuildClient( RequestLanguage language, + ICompilerServerLogger logger, CompileFunc compileFunc = null, TextWriter textWriter = null, int? timeoutOverride = null) { compileFunc = compileFunc ?? GetCompileFunc(language); textWriter = textWriter ?? new StringWriter(); - return new BuildClient(language, compileFunc, timeoutOverride: timeoutOverride); + return new BuildClient(language, compileFunc, logger, timeoutOverride: timeoutOverride); } internal static CompileFunc GetCompileFunc(RequestLanguage language) diff --git a/src/Compilers/Server/VBCSCompilerTests/TestableCompilerServerHost.cs b/src/Compilers/Server/VBCSCompilerTests/TestableCompilerServerHost.cs index 8e2bd3fb7450b..06f7dfd63cc85 100644 --- a/src/Compilers/Server/VBCSCompilerTests/TestableCompilerServerHost.cs +++ b/src/Compilers/Server/VBCSCompilerTests/TestableCompilerServerHost.cs @@ -12,11 +12,13 @@ namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { internal sealed class TestableCompilerServerHost : ICompilerServerHost { - internal Func RunCompilation; + internal Func RunCompilation { get; } + public ICompilerServerLogger Logger { get; } - internal TestableCompilerServerHost(Func runCompilation = null) + internal TestableCompilerServerHost(Func runCompilation = null, ICompilerServerLogger logger = null) { RunCompilation = runCompilation; + Logger = logger ?? EmptyCompilerServerLogger.Instance; } BuildResponse ICompilerServerHost.RunCompilation(RunRequest request, CancellationToken cancellationToken) diff --git a/src/Compilers/Server/VBCSCompilerTests/VBCSCompilerServerTests.cs b/src/Compilers/Server/VBCSCompilerTests/VBCSCompilerServerTests.cs index bcb61e6224b07..42e0a9eb41c35 100644 --- a/src/Compilers/Server/VBCSCompilerTests/VBCSCompilerServerTests.cs +++ b/src/Compilers/Server/VBCSCompilerTests/VBCSCompilerServerTests.cs @@ -17,6 +17,7 @@ using System.Threading; using System.Threading.Tasks; using Xunit; +using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { @@ -45,16 +46,23 @@ public async Task ShadowCopyAnalyzerAssemblyLoaderMissingDirectory() public class ShutdownTests : VBCSCompilerServerTests { - private static Task RunShutdownAsync(string pipeName, bool waitForProcess = true, TimeSpan? timeout = null, CancellationToken cancellationToken = default(CancellationToken)) + internal XunitCompilerServerLogger Logger { get; } + + public ShutdownTests(ITestOutputHelper testOutputHelper) + { + Logger = new XunitCompilerServerLogger(testOutputHelper); + } + + private Task RunShutdownAsync(string pipeName, bool waitForProcess = true, TimeSpan? timeout = null, CancellationToken cancellationToken = default(CancellationToken)) { var appSettings = new NameValueCollection(); - return new BuildServerController(appSettings).RunShutdownAsync(pipeName, waitForProcess, timeout, cancellationToken); + return new BuildServerController(appSettings, Logger).RunShutdownAsync(pipeName, waitForProcess, timeout, cancellationToken); } [Fact] public async Task Standard() { - using var serverData = await ServerUtil.CreateServer(); + using var serverData = await ServerUtil.CreateServer(Logger); var exitCode = await RunShutdownAsync(serverData.PipeName, waitForProcess: false).ConfigureAwait(false); Assert.Equal(CommonCompiler.Succeeded, exitCode); @@ -194,7 +202,7 @@ public async Task ShutdownDoesNotAbortCompilation() return ProtocolUtil.EmptyBuildResponse; }); - using var serverData = await ServerUtil.CreateServer(compilerServerHost: compilerServerHost).ConfigureAwait(false); + using var serverData = await ServerUtil.CreateServer(Logger, compilerServerHost: compilerServerHost).ConfigureAwait(false); // Get the server to the point that it is running the compilation. var compileTask = serverData.SendAsync(ProtocolUtil.EmptyCSharpBuildRequest); @@ -233,7 +241,7 @@ public async Task ShutdownRepeated() return ProtocolUtil.EmptyBuildResponse; }); - using var serverData = await ServerUtil.CreateServer(compilerServerHost: compilerServerHost).ConfigureAwait(false); + using var serverData = await ServerUtil.CreateServer(Logger, compilerServerHost: compilerServerHost).ConfigureAwait(false); // Get the server to the point that it is running the compilation. var compileTask = serverData.SendAsync(ProtocolUtil.EmptyCSharpBuildRequest); @@ -258,6 +266,13 @@ public async Task ShutdownRepeated() public class KeepAliveTests : VBCSCompilerServerTests { + internal XunitCompilerServerLogger Logger { get; } + + public KeepAliveTests(ITestOutputHelper testOutputHelper) + { + Logger = new XunitCompilerServerLogger(testOutputHelper); + } + /// /// Ensure server hits keep alive when processing no connections /// @@ -266,6 +281,7 @@ public async Task NoConnections() { var compilerServerHost = new TestableCompilerServerHost((request, cancellationToken) => ProtocolUtil.EmptyBuildResponse); using var serverData = await ServerUtil.CreateServer( + Logger, keepAlive: TimeSpan.FromSeconds(3), compilerServerHost: compilerServerHost).ConfigureAwait(false); @@ -285,7 +301,7 @@ public async Task NoConnections() public async Task SimpleCases(int connectionCount) { var compilerServerHost = new TestableCompilerServerHost((request, cancellationToken) => ProtocolUtil.EmptyBuildResponse); - using var serverData = await ServerUtil.CreateServer(compilerServerHost: compilerServerHost).ConfigureAwait(false); + using var serverData = await ServerUtil.CreateServer(Logger, compilerServerHost: compilerServerHost).ConfigureAwait(false); var workingDirectory = TempRoot.CreateDirectory().Path; for (var i = 0; i < connectionCount; i++) @@ -318,7 +334,7 @@ public async Task SimultaneousConnections(int connectionCount) return ProtocolUtil.EmptyBuildResponse; }); - using var serverData = await ServerUtil.CreateServer(compilerServerHost: compilerServerHost).ConfigureAwait(false); + using var serverData = await ServerUtil.CreateServer(Logger, compilerServerHost: compilerServerHost).ConfigureAwait(false); var list = new List(); for (var i = 0; i < connectionCount; i++) { @@ -341,6 +357,13 @@ public async Task SimultaneousConnections(int connectionCount) public class MiscTests : VBCSCompilerServerTests { + internal XunitCompilerServerLogger Logger { get; } + + public MiscTests(ITestOutputHelper testOutputHelper) + { + Logger = new XunitCompilerServerLogger(testOutputHelper); + } + [Fact] public async Task CompilationExceptionShouldShutdown() { @@ -350,7 +373,7 @@ public async Task CompilationExceptionShouldShutdown() hitCompilation = true; throw new Exception(""); }); - using var serverData = await ServerUtil.CreateServer(compilerServerHost: compilerServerHost).ConfigureAwait(false); + using var serverData = await ServerUtil.CreateServer(Logger, compilerServerHost: compilerServerHost).ConfigureAwait(false); var response = await serverData.SendAsync(ProtocolUtil.EmptyBasicBuildRequest).ConfigureAwait(false); Assert.True(response is RejectedBuildResponse); @@ -370,7 +393,7 @@ public async Task AnalyzerInconsistencyShouldShutdown() return new AnalyzerInconsistencyBuildResponse(); }); - using var serverData = await ServerUtil.CreateServer(compilerServerHost: compilerServerHost).ConfigureAwait(false); + using var serverData = await ServerUtil.CreateServer(Logger, compilerServerHost: compilerServerHost).ConfigureAwait(false); var response = await serverData.SendAsync(ProtocolUtil.EmptyBasicBuildRequest).ConfigureAwait(false); Assert.True(response is AnalyzerInconsistencyBuildResponse); diff --git a/src/Compilers/Server/VBCSCompilerTests/XunitCompilerServerLogger.cs b/src/Compilers/Server/VBCSCompilerTests/XunitCompilerServerLogger.cs new file mode 100644 index 0000000000000..64b7df0b1acf7 --- /dev/null +++ b/src/Compilers/Server/VBCSCompilerTests/XunitCompilerServerLogger.cs @@ -0,0 +1,25 @@ +// Licensed to the .NET Foundation under one or more 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.CommandLine; +using Xunit.Abstractions; + +namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests +{ + internal sealed class XunitCompilerServerLogger : ICompilerServerLogger + { + public ITestOutputHelper TestOutputHelper { get; } + public bool IsLogging => true; + + public XunitCompilerServerLogger(ITestOutputHelper testOutputHelper) + { + TestOutputHelper = testOutputHelper; + } + + public void Log(string message) + { + TestOutputHelper.WriteLine(message); + } + } +} diff --git a/src/Compilers/Shared/BuildClient.cs b/src/Compilers/Shared/BuildClient.cs index 273a5cd2b2e7a..4d1660794cb22 100644 --- a/src/Compilers/Shared/BuildClient.cs +++ b/src/Compilers/Shared/BuildClient.cs @@ -51,16 +51,18 @@ internal sealed class BuildClient private readonly RequestLanguage _language; private readonly CompileFunc _compileFunc; + private readonly ICompilerServerLogger _logger; private readonly CreateServerFunc _createServerFunc; private readonly int? _timeoutOverride; /// /// When set it overrides all timeout values in milliseconds when communicating with the server. /// - internal BuildClient(RequestLanguage language, CompileFunc compileFunc, CreateServerFunc createServerFunc = null, int? timeoutOverride = null) + internal BuildClient(RequestLanguage language, CompileFunc compileFunc, ICompilerServerLogger logger, CreateServerFunc createServerFunc = null, int? timeoutOverride = null) { _language = language; _compileFunc = compileFunc; + _logger = logger; _createServerFunc = createServerFunc ?? BuildServerConnection.TryCreateServerCore; _timeoutOverride = timeoutOverride; } @@ -75,7 +77,7 @@ public static string GetSystemSdkDirectory() : RuntimeEnvironment.GetRuntimeDirectory(); } - internal static int Run(IEnumerable arguments, RequestLanguage language, CompileFunc compileFunc) + internal static int Run(IEnumerable arguments, RequestLanguage language, CompileFunc compileFunc, ICompilerServerLogger logger) { var sdkDir = GetSystemSdkDirectory(); if (RuntimeHostInfo.IsCoreClrRuntime) @@ -85,7 +87,7 @@ internal static int Run(IEnumerable arguments, RequestLanguage language, System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); } - var client = new BuildClient(language, compileFunc); + var client = new BuildClient(language, compileFunc, logger); var clientDir = AppContext.BaseDirectory; var workingDir = Directory.GetCurrentDirectory(); var tempDir = BuildServerConnection.GetTempPath(workingDir); @@ -272,7 +274,7 @@ private Task RunServerCompilationAsync( string libDirectory, CancellationToken cancellationToken) { - return RunServerCompilationCoreAsync(_language, arguments, buildPaths, sessionKey, keepAlive, libDirectory, _timeoutOverride, _createServerFunc, cancellationToken); + return RunServerCompilationCoreAsync(_language, arguments, buildPaths, sessionKey, keepAlive, libDirectory, _timeoutOverride, _createServerFunc, _logger, cancellationToken); } private static Task RunServerCompilationCoreAsync( @@ -284,6 +286,7 @@ private static Task RunServerCompilationCoreAsync( string libEnvVariable, int? timeoutOverride, CreateServerFunc createServerFunc, + ICompilerServerLogger logger, CancellationToken cancellationToken) { var alt = new BuildPathsAlt( @@ -301,6 +304,7 @@ private static Task RunServerCompilationCoreAsync( libEnvVariable, timeoutOverride, createServerFunc, + logger, cancellationToken); } diff --git a/src/Compilers/Shared/BuildServerConnection.cs b/src/Compilers/Shared/BuildServerConnection.cs index dd01a98a6311d..f6dd1ce1f08a6 100644 --- a/src/Compilers/Shared/BuildServerConnection.cs +++ b/src/Compilers/Shared/BuildServerConnection.cs @@ -62,7 +62,7 @@ internal BuildPathsAlt(string clientDir, string workingDir, string? sdkDir, stri } } - internal delegate bool CreateServerFunc(string clientDir, string pipeName); + internal delegate bool CreateServerFunc(string clientDir, string pipeName, ICompilerServerLogger logger); internal sealed class BuildServerConnection { @@ -84,6 +84,7 @@ public static Task RunServerCompilationAsync( BuildPathsAlt buildPaths, string? keepAlive, string? libEnvVariable, + ICompilerServerLogger logger, CancellationToken cancellationToken) { var pipeNameOpt = sharedCompilationId ?? GetPipeNameForPath(buildPaths.ClientDirectory); @@ -97,6 +98,7 @@ public static Task RunServerCompilationAsync( libEnvVariable, timeoutOverride: null, createServerFunc: TryCreateServerCore, + logger: logger, cancellationToken: cancellationToken); } @@ -109,6 +111,7 @@ internal static async Task RunServerCompilationCoreAsync( string? libEnvVariable, int? timeoutOverride, CreateServerFunc createServerFunc, + ICompilerServerLogger logger, CancellationToken cancellationToken) { if (pipeName is null) @@ -127,7 +130,7 @@ internal static async Task RunServerCompilationCoreAsync( return new IncorrectHashBuildResponse(); } - var pipeTask = tryConnectToServer(pipeName, buildPaths, timeoutOverride, createServerFunc, cancellationToken); + var pipeTask = tryConnectToServer(pipeName, buildPaths, timeoutOverride, createServerFunc, logger, cancellationToken); if (pipeTask is null) { return new RejectedBuildResponse("Failed to connect to server"); @@ -149,7 +152,7 @@ internal static async Task RunServerCompilationCoreAsync( keepAlive: keepAlive, libDirectory: libEnvVariable); - return await TryCompileAsync(pipe, request, cancellationToken).ConfigureAwait(false); + return await TryCompileAsync(pipe, request, logger, cancellationToken).ConfigureAwait(false); } } @@ -161,6 +164,7 @@ internal static async Task RunServerCompilationCoreAsync( BuildPathsAlt buildPaths, int? timeoutOverride, CreateServerFunc createServerFunc, + ICompilerServerLogger logger, CancellationToken cancellationToken) { var originalThreadId = Thread.CurrentThread.ManagedThreadId; @@ -213,9 +217,9 @@ internal static async Task RunServerCompilationCoreAsync( bool wasServerRunning = WasServerMutexOpen(serverMutexName); var timeout = wasServerRunning ? timeoutExistingProcess : timeoutNewProcess; - if (wasServerRunning || createServerFunc(clientDir, pipeName)) + if (wasServerRunning || createServerFunc(clientDir, pipeName, logger)) { - pipeTask = TryConnectToServerAsync(pipeName, timeout, cancellationToken); + pipeTask = TryConnectToServerAsync(pipeName, timeout, logger, cancellationToken); } return pipeTask; @@ -240,9 +244,11 @@ internal static async Task RunServerCompilationCoreAsync( /// Try to compile using the server. Returns a null-containing Task if a response /// from the server cannot be retrieved. /// - private static async Task TryCompileAsync(NamedPipeClientStream pipeStream, - BuildRequest request, - CancellationToken cancellationToken) + private static async Task TryCompileAsync( + NamedPipeClientStream pipeStream, + BuildRequest request, + ICompilerServerLogger logger, + CancellationToken cancellationToken) { BuildResponse response; using (pipeStream) @@ -250,26 +256,26 @@ private static async Task TryCompileAsync(NamedPipeClientStream p // Write the request try { - Log("Begin writing request"); + logger.Log("Begin writing request"); await request.WriteAsync(pipeStream, cancellationToken).ConfigureAwait(false); - Log("End writing request"); + logger.Log("End writing request"); } catch (Exception e) { - LogException(e, "Error writing build request."); + logger.LogException(e, "Error writing build request."); return new RejectedBuildResponse($"Error writing build request: {e.Message}"); } // Wait for the compilation and a monitor to detect if the server disconnects var serverCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - Log("Begin reading response"); + logger.Log("Begin reading response"); var responseTask = BuildResponse.ReadAsync(pipeStream, serverCts.Token); - var monitorTask = MonitorDisconnectAsync(pipeStream, "client", serverCts.Token); + var monitorTask = MonitorDisconnectAsync(pipeStream, "client", logger, serverCts.Token); await Task.WhenAny(responseTask, monitorTask).ConfigureAwait(false); - Log("End reading response"); + logger.Log("End reading response"); if (responseTask.IsCompleted) { @@ -280,13 +286,13 @@ private static async Task TryCompileAsync(NamedPipeClientStream p } catch (Exception e) { - LogException(e, "Error reading response"); + logger.LogException(e, "Error reading response"); response = new RejectedBuildResponse($"Error reading response: {e.Message}"); } } else { - LogError("Client disconnect"); + logger.LogError("Client disconnect"); response = new RejectedBuildResponse($"Client disconnected"); } @@ -304,7 +310,8 @@ private static async Task TryCompileAsync(NamedPipeClientStream p /// internal static async Task MonitorDisconnectAsync( PipeStream pipeStream, - string? identifier = null, + string identifier, + ICompilerServerLogger logger, CancellationToken cancellationToken = default) { var buffer = Array.Empty(); @@ -325,7 +332,7 @@ internal static async Task MonitorDisconnectAsync( { // It is okay for this call to fail. Errors will be reflected in the // IsConnected property which will be read on the next iteration of the - LogException(e, $"Error poking pipe {identifier}."); + logger.LogException(e, $"Error poking pipe {identifier}."); } } } @@ -343,6 +350,7 @@ internal static async Task MonitorDisconnectAsync( internal static async Task TryConnectToServerAsync( string pipeName, int timeoutMs, + ICompilerServerLogger logger, CancellationToken cancellationToken) { NamedPipeClientStream? pipeStream = null; @@ -351,12 +359,12 @@ internal static async Task MonitorDisconnectAsync( // Machine-local named pipes are named "\\.\pipe\". // We use the SHA1 of the directory the compiler exes live in as the pipe name. // The NamedPipeClientStream class handles the "\\.\pipe\" part for us. - Log("Attempt to open named pipe '{0}'", pipeName); + logger.Log("Attempt to open named pipe '{0}'", pipeName); pipeStream = NamedPipeUtil.CreateClient(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); cancellationToken.ThrowIfCancellationRequested(); - Log("Attempt to connect named pipe '{0}'", pipeName); + logger.Log("Attempt to connect named pipe '{0}'", pipeName); try { // NamedPipeClientStream.ConnectAsync on the "full" framework has a bug where it @@ -378,11 +386,11 @@ internal static async Task MonitorDisconnectAsync( // IOException: The server is connected to another client and the // time-out period has expired. - LogException(e, $"Connecting to server timed out after {timeoutMs} ms"); + logger.LogException(e, $"Connecting to server timed out after {timeoutMs} ms"); pipeStream.Dispose(); return null; } - Log("Named pipe '{0}' connected", pipeName); + logger.Log("Named pipe '{0}' connected", pipeName); cancellationToken.ThrowIfCancellationRequested(); @@ -390,7 +398,7 @@ internal static async Task MonitorDisconnectAsync( if (!NamedPipeUtil.CheckPipeConnectionOwnership(pipeStream)) { pipeStream.Dispose(); - LogError("Owner of named pipe is incorrect"); + logger.LogError("Owner of named pipe is incorrect"); return null; } @@ -398,7 +406,7 @@ internal static async Task MonitorDisconnectAsync( } catch (Exception e) when (!(e is TaskCanceledException || e is OperationCanceledException)) { - LogException(e, "Exception while connecting to process"); + logger.LogException(e, "Exception while connecting to process"); pipeStream?.Dispose(); return null; } @@ -411,7 +419,7 @@ internal static (string processFilePath, string commandLineArguments, string too return RuntimeHostInfo.GetProcessInfo(serverPathWithoutExtension, commandLineArgs); } - internal static bool TryCreateServerCore(string clientDir, string pipeName) + internal static bool TryCreateServerCore(string clientDir, string pipeName, ICompilerServerLogger logger) { var serverInfo = GetServerProcessInfo(clientDir, pipeName); @@ -436,7 +444,7 @@ internal static bool TryCreateServerCore(string clientDir, string pipeName) PROCESS_INFORMATION processInfo; - Log("Attempting to create process '{0}'", serverInfo.processFilePath); + logger.Log("Attempting to create process '{0}'", serverInfo.processFilePath); var builder = new StringBuilder($@"""{serverInfo.processFilePath}"" {serverInfo.commandLineArguments}"); @@ -454,13 +462,13 @@ internal static bool TryCreateServerCore(string clientDir, string pipeName) if (success) { - Log("Successfully created process with process id {0}", processInfo.dwProcessId); + logger.Log("Successfully created process with process id {0}", processInfo.dwProcessId); CloseHandle(processInfo.hProcess); CloseHandle(processInfo.hThread); } else { - LogError("Failed to create process. GetLastError={0}", Marshal.GetLastWin32Error()); + logger.LogError("Failed to create process. GetLastError={0}", Marshal.GetLastWin32Error()); } return success; } diff --git a/src/Compilers/Test/Core/SourceGeneration/TestGenerators.cs b/src/Compilers/Test/Core/SourceGeneration/TestGenerators.cs index 60c5bbb518c6b..5beea3fae7517 100644 --- a/src/Compilers/Test/Core/SourceGeneration/TestGenerators.cs +++ b/src/Compilers/Test/Core/SourceGeneration/TestGenerators.cs @@ -57,7 +57,7 @@ public void Execute(GeneratorExecutionContext context) _onExecute(context); if (!string.IsNullOrWhiteSpace(_source)) { - context.AddSource("source.cs", SourceText.From(_source, Encoding.UTF8)); + context.AddSource("source", SourceText.From(_source, Encoding.UTF8)); } } public void Initialize(GeneratorInitializationContext context) => _onInit(context); diff --git a/src/Compilers/VisualBasic/Portable/CommandLine/VisualBasicCompiler.vb b/src/Compilers/VisualBasic/Portable/CommandLine/VisualBasicCompiler.vb index 8efe8137042dd..8e60e03a1232a 100644 --- a/src/Compilers/VisualBasic/Portable/CommandLine/VisualBasicCompiler.vb +++ b/src/Compilers/VisualBasic/Portable/CommandLine/VisualBasicCompiler.vb @@ -297,6 +297,14 @@ Namespace Microsoft.CodeAnalysis.VisualBasic embeddedFiles.Add(resolvedPath) Next End Sub + + Private Protected Overrides Function RunGenerators(input As Compilation, parseOptions As ParseOptions, generators As ImmutableArray(Of ISourceGenerator), analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider, additionalTexts As ImmutableArray(Of AdditionalText), diagnostics As DiagnosticBag) As Compilation + Dim driver = VisualBasicGeneratorDriver.Create(generators, additionalTexts, DirectCast(parseOptions, VisualBasicParseOptions), analyzerConfigOptionsProvider) + Dim compilationOut As Compilation = Nothing, generatorDiagnostics As ImmutableArray(Of Diagnostic) = Nothing + driver.RunGeneratorsAndUpdateCompilation(input, compilationOut, generatorDiagnostics) + diagnostics.AddRange(generatorDiagnostics) + Return compilationOut + End Function + End Class End Namespace - diff --git a/src/Compilers/VisualBasic/Portable/Compilation/SemanticModel.vb b/src/Compilers/VisualBasic/Portable/Compilation/SemanticModel.vb index 9b6276c38b1f4..2b5fc1facb7a3 100644 --- a/src/Compilers/VisualBasic/Portable/Compilation/SemanticModel.vb +++ b/src/Compilers/VisualBasic/Portable/Compilation/SemanticModel.vb @@ -891,7 +891,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic End If Else ' 2 or more symbols. Use a hash set to remove duplicates. - Dim symbolSet As New HashSet(Of Symbol) + Dim symbolSet = PooledHashSet(Of Symbol).GetInstance() For Each s In symbolsBuilder If (options And SymbolInfoOptions.ResolveAliases) <> 0 Then s = UnwrapAlias(s) @@ -909,7 +909,9 @@ Namespace Microsoft.CodeAnalysis.VisualBasic End If Next - Return ImmutableArray.CreateRange(symbolSet) + Dim result = ImmutableArray.CreateRange(symbolSet) + symbolSet.Free() + Return result End If End Function @@ -1393,13 +1395,7 @@ _Default: End Sub Private Shared Function UnwrapAliases(symbols As ImmutableArray(Of Symbol)) As ImmutableArray(Of Symbol) - Dim anyAliases As Boolean = False - - For Each sym In symbols - If sym.Kind = SymbolKind.Alias Then - anyAliases = True - End If - Next + Dim anyAliases As Boolean = symbols.Any(Function(sym) sym.Kind = SymbolKind.Alias) If Not anyAliases Then Return symbols @@ -1934,7 +1930,7 @@ _Default: results As ArrayBuilder(Of Symbol)) Debug.Assert(results IsNot Nothing) - Dim uniqueSymbols = New HashSet(Of Symbol)() + Dim uniqueSymbols = PooledHashSet(Of Symbol).GetInstance() Dim tempResults = ArrayBuilder(Of Symbol).GetInstance(arities.Count) For Each knownArity In arities @@ -1949,6 +1945,7 @@ _Default: tempResults.Free() results.AddRange(uniqueSymbols) + uniqueSymbols.Free() End Sub Private Shadows Sub LookupSymbols(binder As Binder, @@ -1981,7 +1978,7 @@ _Default: If result.HasDiagnostic Then ' In the ambiguous symbol case, we have a good symbol with a diagnostics that ' mentions the other symbols. Union everything together with a set to prevent dups. - Dim symbolSet As New HashSet(Of Symbol) + Dim symbolSet = PooledHashSet(Of Symbol).GetInstance() Dim symBuilder = ArrayBuilder(Of Symbol).GetInstance() AddSymbolsFromDiagnosticInfo(symBuilder, result.Diagnostic) symbolSet.UnionWith(symBuilder) @@ -1989,7 +1986,7 @@ _Default: symBuilder.Free() results.AddRange(symbolSet) - + symbolSet.Free() ElseIf result.HasSingleSymbol AndAlso result.SingleSymbol.Kind = SymbolKind.Namespace AndAlso DirectCast(result.SingleSymbol, NamespaceSymbol).NamespaceKind = NamespaceKindNamespaceGroup Then results.AddRange(DirectCast(result.SingleSymbol, NamespaceSymbol).ConstituentNamespaces) diff --git a/src/Compilers/VisualBasic/Portable/Compilation/VisualBasicDiagnosticFilter.vb b/src/Compilers/VisualBasic/Portable/Compilation/VisualBasicDiagnosticFilter.vb index 923f64a6a134f..8f1f42fc0b9ca 100644 --- a/src/Compilers/VisualBasic/Portable/Compilation/VisualBasicDiagnosticFilter.vb +++ b/src/Compilers/VisualBasic/Portable/Compilation/VisualBasicDiagnosticFilter.vb @@ -135,20 +135,35 @@ Namespace Microsoft.CodeAnalysis.VisualBasic Dim report As ReportDiagnostic Dim tree = location?.SourceTree Dim isSpecified As Boolean = False + Dim specifiedWarnAsErrorMinus As Boolean = False ' Global options depend on other options, so calculate those first If caseInsensitiveSpecificDiagnosticOptions.TryGetValue(id, report) Then ' 2. Command line options (/nowarn, /warnaserror) isSpecified = True - ElseIf syntaxTreeOptions IsNot Nothing Then - If (tree IsNot Nothing AndAlso syntaxTreeOptions.TryGetDiagnosticValue(tree, id, cancellationToken, report)) OrElse - syntaxTreeOptions.TryGetGlobalDiagnosticValue(id, cancellationToken, report) Then - ' 3. Editor config options (syntax tree level) - ' 4. Global analyzer config options (compilation level) + + ' 'ReportDiagnostic.Default' is added to SpecificDiagnosticOptions for "/warnaserror-:DiagnosticId", + If report = ReportDiagnostic.Default Then + specifiedWarnAsErrorMinus = True + End If + End If + + ' Apply syntax tree options, if applicable. + If syntaxTreeOptions IsNot Nothing AndAlso + (Not isSpecified OrElse specifiedWarnAsErrorMinus) Then + + ' 3. Editor config options (syntax tree level) + ' 4. Global analyzer config options (compilation level) + ' Do not apply config options if it is bumping a warning to an error and "/warnaserror-:DiagnosticId" was specified on the command line. + Dim reportFromSyntaxTreeOptions As ReportDiagnostic + If ((tree IsNot Nothing AndAlso syntaxTreeOptions.TryGetDiagnosticValue(tree, id, cancellationToken, reportFromSyntaxTreeOptions)) OrElse + syntaxTreeOptions.TryGetGlobalDiagnosticValue(id, cancellationToken, reportFromSyntaxTreeOptions)) AndAlso + Not (specifiedWarnAsErrorMinus AndAlso severity = DiagnosticSeverity.Warning AndAlso reportFromSyntaxTreeOptions = ReportDiagnostic.Error) Then isSpecified = True + report = reportFromSyntaxTreeOptions ' '/warnaserror' should promote warnings configured in analyzer config to error. - If report = ReportDiagnostic.Warn AndAlso generalDiagnosticOption = ReportDiagnostic.Error Then + If Not specifiedWarnAsErrorMinus AndAlso report = ReportDiagnostic.Warn AndAlso generalDiagnosticOption = ReportDiagnostic.Error Then report = ReportDiagnostic.Error End If End If diff --git a/src/Compilers/VisualBasic/Portable/Errors/Errors.vb b/src/Compilers/VisualBasic/Portable/Errors/Errors.vb index 413174db5d049..b31a08f1ab5a8 100644 --- a/src/Compilers/VisualBasic/Portable/Errors/Errors.vb +++ b/src/Compilers/VisualBasic/Portable/Errors/Errors.vb @@ -1976,6 +1976,9 @@ Namespace Microsoft.CodeAnalysis.VisualBasic WRN_AttributeNotSupportedInVB = 42381 ERR_MultipleAnalyzerConfigsInSameDir = 42500 + WRN_GeneratorFailedDuringInitialization = 42501 + WRN_GeneratorFailedDuringGeneration = 42502 + WRN_AnalyzerReferencesFramework = 42503 ' // AVAILABLE 42600 - 49998 ERRWRN_NextAvailable = 42600 diff --git a/src/Compilers/VisualBasic/Portable/Errors/MessageProvider.vb b/src/Compilers/VisualBasic/Portable/Errors/MessageProvider.vb index 4f8daa201656d..a8fdc08b208f4 100644 --- a/src/Compilers/VisualBasic/Portable/Errors/MessageProvider.vb +++ b/src/Compilers/VisualBasic/Portable/Errors/MessageProvider.vb @@ -232,7 +232,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic Public Overrides ReadOnly Property WRN_AnalyzerReferencesFramework As Integer Get - Throw ExceptionUtilities.Unreachable + Return ERRID.WRN_AnalyzerReferencesFramework End Get End Property @@ -584,13 +584,13 @@ Namespace Microsoft.CodeAnalysis.VisualBasic ' Generators Public Overrides ReadOnly Property WRN_GeneratorFailedDuringInitialization As Integer Get - Throw ExceptionUtilities.Unreachable + Return ERRID.WRN_GeneratorFailedDuringInitialization End Get End Property Public Overrides ReadOnly Property WRN_GeneratorFailedDuringGeneration As Integer Get - Throw ExceptionUtilities.Unreachable + Return ERRID.WRN_GeneratorFailedDuringGeneration End Get End Property diff --git a/src/Compilers/VisualBasic/Portable/Generated/ErrorFacts.Generated.vb b/src/Compilers/VisualBasic/Portable/Generated/ErrorFacts.Generated.vb index 6a2333ce91161..81cad21849fa2 100644 --- a/src/Compilers/VisualBasic/Portable/Generated/ErrorFacts.Generated.vb +++ b/src/Compilers/VisualBasic/Portable/Generated/ErrorFacts.Generated.vb @@ -170,7 +170,10 @@ ERRID.WRN_UnableToLoadAnalyzer, ERRID.WRN_AttributeIgnoredWhenPublicSigning, ERRID.WRN_Experimental, - ERRID.WRN_AttributeNotSupportedInVB + ERRID.WRN_AttributeNotSupportedInVB, + ERRID.WRN_GeneratorFailedDuringInitialization, + ERRID.WRN_GeneratorFailedDuringGeneration, + ERRID.WRN_AnalyzerReferencesFramework Return True Case Else Return False diff --git a/src/Compilers/VisualBasic/Portable/Parser/Parser.vb b/src/Compilers/VisualBasic/Portable/Parser/Parser.vb index f1f1ab8d26c8c..128f4e83f3794 100644 --- a/src/Compilers/VisualBasic/Portable/Parser/Parser.vb +++ b/src/Compilers/VisualBasic/Portable/Parser/Parser.vb @@ -4181,14 +4181,6 @@ checkNullable: If CurrentToken.Kind = SyntaxKind.OpenParenToken Then propertyParameters = ParseParameters(openParen, closeParen) - - ' If we blow up on the parameters try to resume on the AS, =, or Implements - ' TODO - GreenSepList knows its error count. Expose it instead of recomputing it. - If propertyParameters.Count = 0 Then - Dim unexpected = ResyncAt({SyntaxKind.AsKeyword, SyntaxKind.ImplementsKeyword, SyntaxKind.EqualsToken}) - closeParen = closeParen.AddTrailingSyntax(unexpected) - End If - optionalParameters = SyntaxFactory.ParameterList(openParen, propertyParameters, closeParen) Else If ident.ContainsDiagnostics Then diff --git a/src/Compilers/VisualBasic/Portable/PublicAPI.Unshipped.txt b/src/Compilers/VisualBasic/Portable/PublicAPI.Unshipped.txt index 8b137891791fe..2afc778f2f9de 100644 --- a/src/Compilers/VisualBasic/Portable/PublicAPI.Unshipped.txt +++ b/src/Compilers/VisualBasic/Portable/PublicAPI.Unshipped.txt @@ -1 +1,2 @@ - +Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver +Shared Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver.Create(generators As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.ISourceGenerator), additionalTexts As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.AdditionalText) = Nothing, parseOptions As Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions = Nothing, analyzerConfigOptionsProvider As Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider = Nothing) -> Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver diff --git a/src/Compilers/VisualBasic/Portable/SourceGeneration/VisualBasicGeneratorDriver.vb b/src/Compilers/VisualBasic/Portable/SourceGeneration/VisualBasicGeneratorDriver.vb new file mode 100644 index 0000000000000..f98e598291dbb --- /dev/null +++ b/src/Compilers/VisualBasic/Portable/SourceGeneration/VisualBasicGeneratorDriver.vb @@ -0,0 +1,48 @@ +' Licensed to the .NET Foundation under one or more agreements. +' The .NET Foundation licenses this file to you under the MIT license. +' See the LICENSE file in the project root for more information. + +Imports System.Collections.Immutable +Imports System.Threading +Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Diagnostics +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax + +Namespace Microsoft.CodeAnalysis.VisualBasic + + Public Class VisualBasicGeneratorDriver + Inherits GeneratorDriver + + Private Sub New(state As GeneratorDriverState) + MyBase.New(state) + End Sub + + Friend Sub New(parseOptions As VisualBasicParseOptions, generators As ImmutableArray(Of ISourceGenerator), optionsProvider As AnalyzerConfigOptionsProvider, additionalTexts As ImmutableArray(Of AdditionalText)) + MyBase.New(parseOptions, generators, optionsProvider, additionalTexts) + End Sub + + Friend Overrides ReadOnly Property MessageProvider As CommonMessageProvider + Get + Return VisualBasic.MessageProvider.Instance + End Get + End Property + + Friend Overrides Function FromState(state As GeneratorDriverState) As GeneratorDriver + Return New VisualBasicGeneratorDriver(state) + End Function + + Friend Overrides Function ParseGeneratedSourceText(input As GeneratedSourceText, fileName As String, cancellationToken As CancellationToken) As SyntaxTree + Return SyntaxFactory.ParseSyntaxTree(input.Text, _state.ParseOptions, fileName, cancellationToken) + End Function + + Public Shared Function Create(generators As ImmutableArray(Of ISourceGenerator), Optional additionalTexts As ImmutableArray(Of AdditionalText) = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider = Nothing) As VisualBasicGeneratorDriver + Return New VisualBasicGeneratorDriver(parseOptions, generators, analyzerConfigOptionsProvider, additionalTexts) + End Function + + Friend Overrides Function CreateSourcesCollection() As AdditionalSourcesCollection + Return New AdditionalSourcesCollection(".vb") + End Function + + End Class + +End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousDelegate_TemplateSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousDelegate_TemplateSymbol.vb index ec9e39bf24e12..28a3a6c238180 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousDelegate_TemplateSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousDelegate_TemplateSymbol.vb @@ -52,12 +52,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols returnType) For i = 0 To parameterDescriptors.Length - 2 - parameters.Add(New AnonymousDelegateParameterSymbol(delegateInvoke, - Me.TypeParameters(i), - i, - parameterDescriptors(i).IsByRef, - parameterDescriptors(i).Name, - i)) + parameters.Add(New AnonymousTypeOrDelegateParameterSymbol(delegateInvoke, + Me.TypeParameters(i), + i, + parameterDescriptors(i).IsByRef, + parameterDescriptors(i).Name, + i)) Next delegateInvoke.SetParameters(parameters.ToImmutable()) @@ -71,8 +71,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols delegateCtor.SetParameters( ImmutableArray.Create(Of ParameterSymbol)( - New AnonymousDelegateParameterSymbol(delegateCtor, manager.System_Object, 0, False, StringConstants.DelegateConstructorInstanceParameterName), - New AnonymousDelegateParameterSymbol(delegateCtor, manager.System_IntPtr, 1, False, StringConstants.DelegateConstructorMethodParameterName) + New AnonymousTypeOrDelegateParameterSymbol(delegateCtor, manager.System_Object, 0, False, StringConstants.DelegateConstructorInstanceParameterName), + New AnonymousTypeOrDelegateParameterSymbol(delegateCtor, manager.System_IntPtr, 1, False, StringConstants.DelegateConstructorMethodParameterName) )) Dim delegateBeginInvoke As SynthesizedDelegateMethodSymbol @@ -93,12 +93,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols For i = 0 To delegateInvoke.ParameterCount - 1 Dim parameter As ParameterSymbol = delegateInvoke.Parameters(i) - parameters.Add(New AnonymousDelegateParameterSymbol(delegateBeginInvoke, parameter.Type, i, parameter.IsByRef(), parameter.Name, i)) + parameters.Add(New AnonymousTypeOrDelegateParameterSymbol(delegateBeginInvoke, parameter.Type, i, parameter.IsByRef(), parameter.Name, i)) Next - parameters.Add(New AnonymousDelegateParameterSymbol(delegateBeginInvoke, manager.System_AsyncCallback, i, False, StringConstants.DelegateMethodCallbackParameterName)) + parameters.Add(New AnonymousTypeOrDelegateParameterSymbol(delegateBeginInvoke, manager.System_AsyncCallback, i, False, StringConstants.DelegateMethodCallbackParameterName)) i += 1 - parameters.Add(New AnonymousDelegateParameterSymbol(delegateBeginInvoke, manager.System_Object, i, False, StringConstants.DelegateMethodInstanceParameterName)) + parameters.Add(New AnonymousTypeOrDelegateParameterSymbol(delegateBeginInvoke, manager.System_Object, i, False, StringConstants.DelegateMethodInstanceParameterName)) delegateBeginInvoke.SetParameters(parameters.ToImmutable()) parameters.Clear() @@ -112,12 +112,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Dim parameter As ParameterSymbol = delegateInvoke.Parameters(i) If parameter.IsByRef Then - parameters.Add(New AnonymousDelegateParameterSymbol(delegateEndInvoke, parameter.Type, ordinal, parameter.IsByRef(), parameter.Name, i)) + parameters.Add(New AnonymousTypeOrDelegateParameterSymbol(delegateEndInvoke, parameter.Type, ordinal, parameter.IsByRef(), parameter.Name, i)) ordinal += 1 End If Next - parameters.Add(New AnonymousDelegateParameterSymbol(delegateEndInvoke, manager.System_IAsyncResult, ordinal, False, StringConstants.DelegateMethodResultParameterName)) + parameters.Add(New AnonymousTypeOrDelegateParameterSymbol(delegateEndInvoke, manager.System_IAsyncResult, ordinal, False, StringConstants.DelegateMethodResultParameterName)) delegateEndInvoke.SetParameters(parameters.ToImmutable()) _members = ImmutableArray.Create(delegateCtor, delegateBeginInvoke, delegateEndInvoke, delegateInvoke) diff --git a/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousTypeOrDelegateTemplateSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousTypeOrDelegateTemplateSymbol.vb index fe00a78d5b548..2b07bd589d8da 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousTypeOrDelegateTemplateSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousTypeOrDelegateTemplateSymbol.vb @@ -37,6 +37,9 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Private ReadOnly _typeParameters As ImmutableArray(Of TypeParameterSymbol) Private _adjustedPropertyNames As LocationAndNames +#If DEBUG Then + Private _locationAndNamesAreLocked As Boolean +#End If ''' ''' The key of the anonymous type descriptor used for this type template @@ -315,6 +318,9 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Public ReadOnly Property SmallestLocation As Location Get +#If DEBUG Then + _locationAndNamesAreLocked = True +#End If Return Me._adjustedPropertyNames.Location End Get End Property @@ -335,12 +341,16 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ' to set it ('location' in type descriptor is bigger that the one in m_adjustedPropertyNames) Dim currentAdjustedNames As LocationAndNames = Me._adjustedPropertyNames If currentAdjustedNames IsNot Nothing AndAlso - Me.Manager.Compilation.CompareSourceLocations(currentAdjustedNames.Location, newLocation) < 0 Then + Me.Manager.Compilation.CompareSourceLocations(currentAdjustedNames.Location, newLocation) <= 0 Then ' The template's adjusted property names do not need to be changed Exit Sub End If +#If DEBUG Then + Debug.Assert(Not _locationAndNamesAreLocked) +#End If + Dim newAdjustedNames As New LocationAndNames(typeDescr) If Interlocked.CompareExchange(Me._adjustedPropertyNames, newAdjustedNames, currentAdjustedNames) Is currentAdjustedNames Then @@ -351,6 +361,9 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols End Sub Friend Function GetAdjustedName(index As Integer) As String +#If DEBUG Then + _locationAndNamesAreLocked = True +#End If Dim names = Me._adjustedPropertyNames Debug.Assert(names IsNot Nothing) Debug.Assert(names.Names.Length > index) diff --git a/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousDelegate_ParameterSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousTypeOrDelegate_ParameterSymbol.vb similarity index 68% rename from src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousDelegate_ParameterSymbol.vb rename to src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousTypeOrDelegate_ParameterSymbol.vb index 151b4c152b7da..834f606b82e5d 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousDelegate_ParameterSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousTypeOrDelegate_ParameterSymbol.vb @@ -13,26 +13,26 @@ Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class AnonymousTypeManager - Private NotInheritable Class AnonymousDelegateParameterSymbol + Private NotInheritable Class AnonymousTypeOrDelegateParameterSymbol Inherits SynthesizedParameterSymbol - Public ReadOnly CorrespondingInvokeParameter As Integer + Public ReadOnly CorrespondingInvokeParameterOrProperty As Integer Public Sub New( - container As SynthesizedDelegateMethodSymbol, + container As MethodSymbol, type As TypeSymbol, ordinal As Integer, isByRef As Boolean, name As String, - Optional correspondingInvokeParameter As Integer = -1 + Optional correspondingInvokeParameterOrProperty As Integer = -1 ) MyBase.New(container, type, ordinal, isByRef, name) - Me.CorrespondingInvokeParameter = correspondingInvokeParameter + Me.CorrespondingInvokeParameterOrProperty = correspondingInvokeParameterOrProperty End Sub Public Overrides ReadOnly Property MetadataName As String Get - If CorrespondingInvokeParameter <> -1 Then - Return DirectCast(_container.ContainingSymbol, AnonymousDelegateTemplateSymbol).GetAdjustedName(CorrespondingInvokeParameter) + If CorrespondingInvokeParameterOrProperty <> -1 Then + Return DirectCast(_container.ContainingSymbol, AnonymousTypeOrDelegateTemplateSymbol).GetAdjustedName(CorrespondingInvokeParameterOrProperty) End If Return MyBase.MetadataName diff --git a/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType_ConstructorSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType_ConstructorSymbol.vb index 4354071e0347e..072a475fbc0e3 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType_ConstructorSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType_ConstructorSymbol.vb @@ -22,7 +22,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Dim paramsArr = New ParameterSymbol(fieldsCount - 1) {} For index = 0 To fieldsCount - 1 Dim [property] As PropertySymbol = container.Properties(index) - paramsArr(index) = New SynthesizedParameterSimpleSymbol(Me, [property].Type, index, [property].Name) + paramsArr(index) = New AnonymousTypeOrDelegateParameterSymbol(Me, [property].Type, index, isByRef:=False, [property].Name, correspondingInvokeParameterOrProperty:=index) Next Me._parameters = paramsArr.AsImmutableOrNull() End Sub diff --git a/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType_PropertyBackingFieldSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType_PropertyBackingFieldSymbol.vb index 373c41730624e..cc9445d9bbfde 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType_PropertyBackingFieldSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType_PropertyBackingFieldSymbol.vb @@ -26,7 +26,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Get ' To be sure that when we emitting the name, it's ' casing is in sync with that of the property - Return "$" & Me._propertyOrEvent.Name + Return "$" & Me._propertyOrEvent.MetadataName End Get End Property diff --git a/src/Compilers/VisualBasic/Portable/VBResources.resx b/src/Compilers/VisualBasic/Portable/VBResources.resx index 86c0a8cc0948d..6fbca2938acb9 100644 --- a/src/Compilers/VisualBasic/Portable/VBResources.resx +++ b/src/Compilers/VisualBasic/Portable/VBResources.resx @@ -5580,4 +5580,35 @@ Attribute is not supported in VB + + Generator '{0}' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + {0} is the string representation of the exception that was thrown. + + + Generator failed to generate source. + + + Generator '{0}' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + {0} is the string representation of the exception that was thrown. + + + Generator failed to initialize. + + + The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + {1} is the type that was loaded, {0} is the containing assembly. + + + The loaded assembly references .NET Framework, which is not supported. + diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.cs.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.cs.xlf index 2a771895a42f2..0c2f9b9a5efa0 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.cs.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.cs.xlf @@ -212,169 +212,169 @@ -vbruntime:<file> Compile with the alternate Visual Basic runtime in <file>. - Visual Basic Compiler Options + Parametry kompilátoru Visual Basic - - OUTPUT FILE - --out:<file> Specifies the output file name. --target:exe Create a console application (default). - (Short form: -t) --target:winexe Create a Windows application. --target:library Create a library assembly. --target:module Create a module that can be added to an - assembly. --target:appcontainerexe Create a Windows application that runs in - AppContainer. --target:winmdobj Create a Windows Metadata intermediate file --doc[+|-] Generates XML documentation file. --doc:<file> Generates XML documentation file to <file>. --refout:<file> Reference assembly output to generate + - VÝSTUPNÍ SOUBOR - +-out:<soubor> Určuje název výstupního souboru. +-target:exe Vytvoří konzolovou aplikaci (výchozí). + (Krátký tvar: -t) +-target:winexe Vytvoří aplikaci Windows. +-target:library Vytvoří sestavení knihovny. +-target:module Vytvoří modul, který jde přidat + do sestavení. +-target:appcontainerexe Vytvoří aplikaci Windows, která bude běžet + v kontejneru AppContainer. +-target:winmdobj Vytvoří pomocný soubor metadat Windows. +-doc[+|-] Generuje soubor dokumentace XML. +-doc:<soubor> Generuje soubor dokumentace XML s určeným názvem. +-refout:<file> Výstup referenčního sestavení, který se bude generovat - - INPUT FILES - --addmodule:<file_list> Reference metadata from the specified modules --link:<file_list> Embed metadata from the specified interop - assembly. (Short form: -l) --recurse:<wildcard> Include all files in the current directory - and subdirectories according to the - wildcard specifications. --reference:<file_list> Reference metadata from the specified - assembly. (Short form: -r) --analyzer:<file_list> Run the analyzers from this assembly - (Short form: -a) --additionalfile:<file list> Additional files that don't directly affect code - generation but may be used by analyzers for producing - errors or warnings. + - VSTUPNÍ SOUBORY - +-addmodule:<seznam_souborů> Odkazuje na metadata ze zadaných modulů. +-link:<seznam_souborů> Vloží metadata ze zadaného definičního + sestavení. (Krátký tvar: -l) +-recurse:<zástupný_znak> Zahrne všechny soubory v aktuálním adresáři + a podadresářích podle zadaného + zástupného znaku. +-reference:<seznam_souborů> Odkazuje na metadata ze zadaného + sestavení. (Krátký tvar: -r) +-analyzer:<seznam_souborů> Spustí analyzátory z tohoto sestavení. + (Krátký tvar: -a) +-additionalfile:<seznam_souborů> Další soubory, které přímo neovlivňují generování + kódu, ale analyzátory můžou jejich pomocí + produkovat chyby nebo upozornění. - - RESOURCES - --linkresource:<resinfo> Links the specified file as an external - assembly resource. - resinfo:<file>[,<name>[,public|private]] - (Short form: -linkres) --nowin32manifest The default manifest should not be embedded - in the manifest section of the output PE. --resource:<resinfo> Adds the specified file as an embedded - assembly resource. - resinfo:<file>[,<name>[,public|private]] - (Short form: -res) --win32icon:<file> Specifies a Win32 icon file (.ico) for the - default Win32 resources. --win32manifest:<file> The provided file is embedded in the manifest - section of the output PE. --win32resource:<file> Specifies a Win32 resource file (.res). + - PROSTŘEDKY - +-linkresource:<prostředek> Připojí zadaný soubor jako externí prostředek + sestavení. + prostředek: <soubor>[,<název>[,public|private]] + (Krátký tvar: -linkres) +-nowin32manifest Výchozí manifest by se neměl vkládat + do oddílu manifestu výstupního PE. +-resource:<prostředek> Přidá zadaný soubor jako vložený prostředek + sestavení. + prostředek: <soubor>[,<název>[,public|private]] + (Krátký tvar: -res) +-win32icon:<soubor> Určuje soubor ikony Win32 (.ico) pro + výchozí prostředky Win32. +-win32manifest:<soubor> Zadaný soubor se vloží do oddílu + manifestu výstupního PE. +-win32resource:<soubor> Určuje soubor prostředků Win32 (.res). - - CODE GENERATION - --optimize[+|-] Enable optimizations. --removeintchecks[+|-] Remove integer checks. Default off. --debug[+|-] Emit debugging information. --debug:full Emit full debugging information (default). --debug:pdbonly Emit full debugging information. --debug:portable Emit cross-platform debugging information. --debug:embedded Emit cross-platform debugging information into - the target .dll or .exe. --deterministic Produce a deterministic assembly - (including module version GUID and timestamp) --refonly Produce a reference assembly in place of the main output --instrument:TestCoverage Produce an assembly instrumented to collect - coverage information --sourcelink:<file> Source link info to embed into PDB. + - GENEROVÁNÍ KÓDU - +-optimize[+|-] Povolí optimalizace. +-removeintchecks[+|-] Odebere kontroly celých čísel. Standardně vypnuté. +-debug[+|-] Generuje ladicí informace. +-debug:full Generuje úplné ladicí informace (výchozí). +-debug:pdbonly Generuje úplné ladicí informace. +-debug:portable Generuje ladicí informace napříč platformami. +-debug:embedded Generuje ladicí informace napříč platformami + do cílového souboru .dll nebo .exe. +-deterministic Vytvoří deterministické sestavení + (včetně GUID verze modulu a časového razítka). +-refonly Vytvoří referenční sestavení na místě hlavního výstupu. +-instrument:TestCoverage Vytvoří sestavení instrumentované pro shromažďování informací + o pokrytí. +-sourcelink:<soubor> Informace o zdrojovém odkazu vkládané do přenosného PDB. - - ERRORS AND WARNINGS - --nowarn Disable all warnings. --nowarn:<number_list> Disable a list of individual warnings. --warnaserror[+|-] Treat all warnings as errors. --warnaserror[+|-]:<number_list> Treat a list of warnings as errors. --ruleset:<file> Specify a ruleset file that disables specific - diagnostics. --errorlog:<file>[,version=<sarif_version>] - Specify a file to log all compiler and analyzer - diagnostics in SARIF format. - sarif_version:{1|2|2.1} Default is 1. 2 and 2.1 - both mean SARIF version 2.1.0. --reportanalyzer Report additional analyzer information, such as - execution time. --skipanalyzers[+|-] Skip execution of diagnostic analyzers. + - CHYBY A UPOZORNĚNÍ - +-nowarn Zakáže všechna upozornění. +-nowarn:<seznam_čísel> Zakáže upozornění ze seznamu. +-warnaserror[+|-] Zpracuje všechna upozornění jako chyby. +-warnaserror[+|-]:<seznam_čísel> Zpracuje zadaná upozornění jako chyby. +-ruleset:<soubor> Určuje soubor sady pravidel, která zakazuje + specifickou diagnostiku. +-errorlog:<soubor>[,version=<verze_sarif>] + Určuje soubor pro protokolování veškeré diagnostiky + kompilátoru a analyzátoru ve formátu SARIF. + verze_sarif:{1|2|2.1} Výchozí jsou 1. 2 a 2.1. + Obě hodnoty znamenají SARIF verze 2.1.0. +-reportanalyzer Oznamuje další informace analyzátoru, jako třeba + dobu zpracování. +-skipanalyzers[+|-] Přeskočí spouštění diagnostických analyzátorů. - - LANGUAGE - --define:<symbol_list> Declare global conditional compilation - symbol(s). symbol_list:name=value,... - (Short form: -d) --imports:<import_list> Declare global Imports for namespaces in - referenced metadata files. - import_list:namespace,... --langversion:? Display the allowed values for language version --langversion:<string> Specify language version such as - `default` (latest major version), or - `latest` (latest version, including minor versions), - or specific versions like `14` or `15.3` --optionexplicit[+|-] Require explicit declaration of variables. --optioninfer[+|-] Allow type inference of variables. --rootnamespace:<string> Specifies the root Namespace for all type - declarations. --optionstrict[+|-] Enforce strict language semantics. --optionstrict:custom Warn when strict language semantics are not - respected. --optioncompare:binary Specifies binary-style string comparisons. - This is the default. --optioncompare:text Specifies text-style string comparisons. + - JAZYK - +-define:<seznam_symbolů> Deklaruje globální symboly podmíněné + kompilace. seznam_symbolů: název=hodnota,... + (Krátký tvar: -d) +-imports:<seznam_importů> Deklaruje globální importy pro obory názvů + v odkazovaných souborech metadat. + seznam_importů: obor_názvů,... +-langversion:? Zobrazí povolené hodnoty jazykové verze. +-langversion:<číslo> Určuje jazykovou verzi, například + default (nejnovější hlavní verze) nebo + latest (nejnovější verze včetně podverzí) nebo + konkrétní verze, například 14 nebo 15.3. +-optionexplicit[+|-] Vyžaduje explicitní deklarování proměnných. +-optioninfer[+|-] Povoluje odvození typu proměnných. +-rootnamespace:<řetězec> Určuje kořenový obor názvů pro všechny + deklarace typů. +-optionstrict[+|-] Vynucuje striktní sémantiku jazyka. +-optionstrict:custom Upozorňuje na nedodržování striktní + sémantiky jazyka. +-optioncompare:binary Určuje binární styl porovnávání řetězců. + Jde o výchozí možnost. +-optioncompare:text Určuje textový styl porovnávání řetězců. - - MISCELLANEOUS - --help Display this usage message. (Short form: -?) --noconfig Do not auto-include VBC.RSP file. --nologo Do not display compiler copyright banner. --quiet Quiet output mode. --verbose Display verbose messages. --parallel[+|-] Concurrent build. --version Display the compiler version number and exit. + - RŮZNÉ - +-help Zobrazí tuto zprávu o použití. (Krátký tvar: -?) +-noconfig Nezahrnuje automaticky soubor VBC.RSP. +-nologo Nezobrazí zprávu o autorských právech kompilátoru. +-quiet Určuje tichý výstupní režim. +-verbose Zobrazí podrobné zprávy. +-parallel[+|-] Souběžné sestavení +-version Zobrazí číslo verze kompilátoru a ukončí se. - - ADVANCED - --baseaddress:<number> The base address for a library or module - (hex). --checksumalgorithm:<alg> Specify algorithm for calculating source file - checksum stored in PDB. Supported values are: - SHA1 or SHA256 (default). --codepage:<number> Specifies the codepage to use when opening - source files. --delaysign[+|-] Delay-sign the assembly using only the public - portion of the strong name key. --publicsign[+|-] Public-sign the assembly using only the public - portion of the strong name key. --errorreport:<string> Specifies how to handle internal compiler - errors; must be prompt, send, none, or queue - (default). --filealign:<number> Specify the alignment used for output file - sections. --highentropyva[+|-] Enable high-entropy ASLR. --keycontainer:<string> Specifies a strong name key container. --keyfile:<file> Specifies a strong name key file. --libpath:<path_list> List of directories to search for metadata - references. (Semi-colon delimited.) --main:<class> Specifies the Class or Module that contains - Sub Main. It can also be a Class that - inherits from System.Windows.Forms.Form. - (Short form: -m) --moduleassemblyname:<string> Name of the assembly which this module will - be a part of. --netcf Target the .NET Compact Framework. --nostdlib Do not reference standard libraries - (system.dll and VBC.RSP file). + - POKROČILÉ - +-baseaddress:<číslo> Určuje základní adresu pro knihovnu nebo + modul (hex). +-checksumalgorithm:<alg> Určuje algoritmus pro výpočet kontrolního součtu + zdrojového souboru uloženého v PDB. Podporované + hodnoty jsou SHA1 nebo SHA256 (výchozí). +-codepage:<číslo> Určuje znakovou stránku, která se má použít + při otevírání zdrojových souborů. +-delaysign[+|-] Vytvoří zpožděný podpis sestavení s využitím + veřejné části klíče silného názvu. +-publicsign[+|-] Vytvoří veřejný podpis sestavení s využitím jenom veřejné + části klíče silného názvu. +-errorreport:<řetězec> Určuje způsob zpracování interních chyb + kompilátoru: prompt, send, none nebo queue + (výchozí). +-filealign:<číslo> Určuje zarovnání použité pro oddíly výstupního + souboru. +-highentropyva[+|-] Povoluje ASLR s vysokou entropií. +-keycontainer:<řetězec> Určuje kontejner klíče se silným názvem. +-keyfile:<soubor> Určuje soubor klíče se silným názvem. +-libpath:<seznam_cest> Seznam adresářů, kde se mají hledat odkazy + na metadata (oddělený středníky) +-main:<třída> Určuje třídu nebo modul obsahující + Sub Main. Může to být taky třída, která + dědí od System.Windows.Forms.Form. + (Krátký tvar: -m) +-moduleassemblyname:<řetězec> Určuje název sestavení, jehož součástí bude + tento modul. +-netcf Cílí na .NET Compact Framework. +-nostdlib Neodkazuje na standardní knihovny + (system.dll a VBC.RSP). -pathmap:<K1>=<V1>,<K2>=<V2>,... - Specify a mapping for source path names output by - the compiler. --platform:<string> Limit which platforms this code can run on; - must be x86, x64, Itanium, arm, arm64 - AnyCPU32BitPreferred or anycpu (default). --preferreduilang Specify the preferred output language name. --nosdkpath Disable searching the default SDK path for standard library assemblies. --sdkpath:<path> Location of the .NET Framework SDK directory + Určuje mapování pro výstup zdrojových názvů cest + kompilátorem. +-platform:<řetězec> Omezuje platformy, na kterých se dá tento kód + spustit: x86, x64, Itanium, arm, arm64, + AnyCPU32BitPreferred nebo anycpu (výchozí). +-preferreduilang Určuje název upřednostňovaného výstupního jazyka. +-nosdkpath Zakáže hledání cesty k výchozí sadě SDK pro sestavení standardních knihoven. +-sdkpath:<cesta> Umístění adresáře s .NET Framework SDK (mscorlib.dll). --subsystemversion:<version> Specify subsystem version of the output PE. - version:<number>[.<number>] --utf8output[+|-] Emit compiler output in UTF8 character - encoding. -@<file> Insert command-line settings from a text file --vbruntime[+|-|*] Compile with/without the default Visual Basic - runtime. --vbruntime:<file> Compile with the alternate Visual Basic - runtime in <file>. +-subsystemversion:<verze> Určuje verzi subsystému výstupního PE. + verze: <číslo>[.<číslo>] +-utf8output[+|-] Generuje výstup kompilátoru v kódování + UTF-8. +@<soubor> Vloží nastavení příkazového řádku ze souboru. +-vbruntime[+|-|*] Kompiluje s výchozím modulem runtime nebo bez něj + Visual Basicu. +-vbruntime:<soubor> Kompiluje s alternativním modulem runtime + Visual Basicu určeným parametrem <soubor>. @@ -463,6 +463,50 @@ Argument typu nemůže být Nothing. + + The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + Sestavení {0}, které obsahuje typ {1}, se odkazuje na architekturu .NET Framework, což se nepodporuje. + {1} is the type that was loaded, {0} is the containing assembly. + + + The loaded assembly references .NET Framework, which is not supported. + Načtené sestavení se odkazuje na architekturu .NET Framework, což se nepodporuje + + + + Generator '{0}' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + Generátor {0} nemohl vygenerovat zdroj. V důsledku toho může docházet k chybám kompilace a generátor nebude přispívat na výstup. Výjimka měla typ {1} se zprávou {2}. + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + Generátor vyvolal následující výjimku: +{0}. + {0} is the string representation of the exception that was thrown. + + + Generator failed to generate source. + Generátoru se nepovedlo vygenerovat zdroj + + + + Generator '{0}' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + Generátor {0} se nepovedlo inicializovat. V důsledku toho může docházet k chybám kompilace a generátor nebude přispívat na výstup. Výjimka měla typ {1} se zprávou {2}. + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + Generátor vyvolal následující výjimku: +{0}. + {0} is the string representation of the exception that was thrown. + + + Generator failed to initialize. + Generátor se nepovedlo inicializovat + + Wrong number of type arguments Chybný počet argumentů typu @@ -615,7 +659,7 @@ '{0}' is not a valid value for /moduleassemblyname - '{0} není platný pro /moduleassemblyname. + {0} není platný pro /moduleassemblyname. @@ -1060,12 +1104,12 @@ '{0}' is a type and cannot be used as an expression. - '{0} je typ a nejde ho použít jako výraz. + {0} je typ a nejde ho použít jako výraz. '{0}' is a class type and cannot be used as an expression. - '{0} je typ třídy a nejde ho použít jako výraz. + {0} je typ třídy a nejde ho použít jako výraz. @@ -1075,12 +1119,12 @@ '{0}' is an interface type and cannot be used as an expression. - '{0} je typ rozhraní a nejde ho použít jako výraz. + {0} je typ rozhraní a nejde ho použít jako výraz. '{0}' is a namespace and cannot be used as an expression. - '{0} je obor názvů a nedá se použít jako výraz. + {0} je obor názvů a nedá se použít jako výraz. @@ -1090,7 +1134,7 @@ '{0}' is an XML prefix and cannot be used as an expression. Use the GetXmlNamespace operator to create a namespace object. - '{0} je předpona jazyka XML, kterou nejde použít jako výraz. K vytvoření objektu oboru názvů použijte operátor GetXmlNamespace. + {0} je předpona jazyka XML, kterou nejde použít jako výraz. K vytvoření objektu oboru názvů použijte operátor GetXmlNamespace. @@ -1350,17 +1394,17 @@ '{0}' is not valid on a constant declaration. - '{0} není platná deklarace konstanty. + {0} není platná deklarace konstanty. '{0}' is not valid on a WithEvents declaration. - '{0} není platný v deklaraci WithEvents. + {0} není platný v deklaraci WithEvents. '{0}' is not valid on a member variable declaration. - '{0} není platný v deklaraci členské proměnné. + {0} není platný v deklaraci členské proměnné. @@ -1400,27 +1444,27 @@ '{0}' is not valid on a method declaration. - '{0} není platný v deklaraci metody. + {0} není platný v deklaraci metody. '{0}' is not valid on an event declaration. - '{0} není platný v deklaraci události. + {0} není platný v deklaraci události. '{0}' is not valid on a Declare. - '{0} není platný v příkazu Declare. + {0} není platný v příkazu Declare. '{0}' is not valid on a local constant declaration. - '{0} není platný v deklaraci lokální konstanty. + {0} není platný v deklaraci lokální konstanty. '{0}' is not valid on a local variable declaration. - '{0} není platný v deklaraci lokální proměnné. + {0} není platný v deklaraci lokální proměnné. @@ -1484,32 +1528,32 @@ '{0}' cannot override '{1}' because it is declared 'NotOverridable'. - '{0} nemůže přepsat {1}, protože je deklarovaná jako NotOverridable. + {0} nemůže přepsat {1}, protože je deklarovaná jako NotOverridable. '{0}' has multiple definitions with identical signatures. - '{0} má několik definic s identickými podpisy. + {0} má několik definic s identickými podpisy. '{0}' has multiple definitions with identical signatures with different tuple element names, including '{1}'. - '{0} má více definicí s identickými podpisy s různými názvy elementů řazené kolekce členů, včetně {1}. + {0} má více definicí s identickými podpisy s různými názvy elementů řazené kolekce členů, včetně {1}. '{0}' is not valid on an interface method declaration. - '{0} není platný v deklaraci metody rozhraní. + {0} není platný v deklaraci metody rozhraní. '{0}' is not a parameter of '{1}'. - '{0} není parametr pro {1}. + {0} není parametr pro {1}. '{0}' is not valid on an interface property declaration. - '{0} není platný v deklaraci vlastnosti rozhraní. + {0} není platný v deklaraci vlastnosti rozhraní. @@ -1519,7 +1563,7 @@ '{0}' is not valid on an interface event declaration. - '{0} není platný v deklaraci události rozhraní. + {0} není platný v deklaraci události rozhraní. @@ -1618,17 +1662,17 @@ '{0}' cannot inherit from {2} '{1}' because '{1}' is declared 'NotInheritable'. - '{0} nemůže dědit z {2} {1}, protože {1} se deklaruje jako NotInheritable. + {0} nemůže dědit z {2} {1}, protože {1} se deklaruje jako NotInheritable. '{0}' and '{1}' cannot overload each other because they differ only by optional parameters. - '{0} a {1} se nemůžou vzájemně přetěžovat, protože se liší jenom nepovinnými parametry. + {0} a {1} se nemůžou vzájemně přetěžovat, protože se liší jenom nepovinnými parametry. '{0}' and '{1}' cannot overload each other because they differ only by return types. - '{0} a {1} se nemůžou vzájemně přetěžovat, protože se liší jenom typy vrácených hodnot. + {0} a {1} se nemůžou vzájemně přetěžovat, protože se liší jenom typy vrácených hodnot. @@ -1643,7 +1687,7 @@ '{0}' and '{1}' cannot overload each other because they differ only by the default values of optional parameters. - '{0} a {1} se nemůžou vzájemně přetěžovat, protože se liší jenom výchozími hodnotami nepovinných parametrů. + {0} a {1} se nemůžou vzájemně přetěžovat, protože se liší jenom výchozími hodnotami nepovinných parametrů. @@ -1653,12 +1697,12 @@ '{0}' cannot override '{1}' because they differ by the default values of optional parameters. - '{0} nemůže přepsat {1}, protože se liší výchozími hodnotami nepovinných parametrů. + {0} nemůže přepsat {1}, protože se liší výchozími hodnotami nepovinných parametrů. '{0}' cannot override '{1}' because they differ by optional parameters. - '{0} nemůže přepsat {1}, protože se liší nepovinnými parametry. + {0} nemůže přepsat {1}, protože se liší nepovinnými parametry. @@ -1693,7 +1737,7 @@ '{0}' and '{1}' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'. - '{0} a {1} se nemůžou vzájemně přetěžovat, protože se liší jenom parametry deklarovanými jako ByRef nebo ByVal. + {0} a {1} se nemůžou vzájemně přetěžovat, protože se liší jenom parametry deklarovanými jako ByRef nebo ByVal. @@ -1713,12 +1757,12 @@ '{0}' and '{1}' cannot overload each other because only one is declared 'Default'. - '{0} a {1} se nemůžou vzájemně přetěžovat, protože jenom v jedné deklaraci je uvedené klíčové slovo Default. + {0} a {1} se nemůžou vzájemně přetěžovat, protože jenom v jedné deklaraci je uvedené klíčové slovo Default. '{0}' cannot override '{1}' because they differ by 'ReadOnly' or 'WriteOnly'. - '{0} nemůže přepsat {1}, protože se liší příznakem ReadOnly nebo WriteOnly. + {0} nemůže přepsat {1}, protože se liší příznakem ReadOnly nebo WriteOnly. @@ -1733,7 +1777,7 @@ '{0}' and '{1}' cannot overload each other because they differ only by 'ReadOnly' or 'WriteOnly'. - '{0} a {1} se nemůžou vzájemně přetěžovat, protože se liší jenom příznakem ReadOnly nebo WriteOnly. + {0} a {1} se nemůžou vzájemně přetěžovat, protože se liší jenom příznakem ReadOnly nebo WriteOnly. @@ -1743,7 +1787,7 @@ '{0}' and '{1}' cannot overload each other because they differ only by parameters declared 'ParamArray'. - '{0} a {1} se nemůžou vzájemně přetěžovat, protože se liší jenom parametry s deklarací ParamArray. + {0} a {1} se nemůžou vzájemně přetěžovat, protože se liší jenom parametry s deklarací ParamArray. @@ -1798,7 +1842,7 @@ '{0}' is not valid on a Delegate declaration. - '{0} není platný v deklaraci delegáta. + {0} není platný v deklaraci delegáta. @@ -1828,22 +1872,22 @@ '{0}' is not valid on a Structure declaration. - '{0} není platný v deklaraci struktury. + {0} není platný v deklaraci struktury. '{0}' is not valid on an Enum declaration. - '{0} není platný v deklaraci výčtu. + {0} není platný v deklaraci výčtu. '{0}' is not valid on an Interface declaration. - '{0} není platný v deklaraci rozhraní. + {0} není platný v deklaraci rozhraní. '{0}' cannot override '{1}' because they differ by a parameter that is marked as 'ByRef' versus 'ByVal'. - '{0} nemůže přepsat {1}, protože se liší parametrem, který je označený jednou jako ByRef a podruhé jako ByVal. + {0} nemůže přepsat {1}, protože se liší parametrem, který je označený jednou jako ByRef a podruhé jako ByVal. @@ -1858,7 +1902,7 @@ '{0}' cannot implement {1} '{2}' on interface '{3}' because the tuple element names in '{4}' do not match those in '{5}'. - '{0} nemůže implementovat {1} {2} v rozhraní {3}, protože názvy elementů řazené kolekce členů v {4} neodpovídá názvům elementů v {5}. + {0} nemůže implementovat {1} {2} v rozhraní {3}, protože názvy elementů řazené kolekce členů v {4} neodpovídá názvům elementů v {5}. @@ -1923,12 +1967,12 @@ '{0}' cannot override '{1}' because they differ by their return types. - '{0} nemůže přepsat {1}, protože se liší typy vrácených hodnot. + {0} nemůže přepsat {1}, protože se liší typy vrácených hodnot. '{0}' cannot override '{1}' because they differ by their tuple element names. - '{0} nemůže přepsat {1}, protože se liší v názvech elementů řazené kolekce členů. + {0} nemůže přepsat {1}, protože se liší v názvech elementů řazené kolekce členů. @@ -1958,7 +2002,7 @@ '{0}' is not declared. It may be inaccessible due to its protection level. - '{0} není deklarované. Může být z důvodu úrovně ochrany nepřístupné. + {0} není deklarované. Může být z důvodu úrovně ochrany nepřístupné. @@ -1978,7 +2022,7 @@ '{0}' is not a member of '{1}'. - '{0} není člen u {1}. + {0} není člen u {1}. @@ -1998,7 +2042,7 @@ '{1}' for the Imports '{0}' does not refer to a Namespace, Class, Structure, Enum or Module. - '{1} importů {0} neodkazuje na obor názvů, třídu, strukturu, výčet ani modul. + {1} importů {0} neodkazuje na obor názvů, třídu, strukturu, výčet ani modul. @@ -2103,7 +2147,7 @@ '{0}' cannot inherit from {1} '{2}' because it expands the access of the base {1} to {3} '{4}'. - '{0} nemůže dědit z {1} - {2}, protože rozšiřuje přístup základní třídy {1} na {3} - {4}. + {0} nemůže dědit z {1} - {2}, protože rozšiřuje přístup základní třídy {1} na {3} - {4}. @@ -2205,7 +2249,7 @@ '{0}' cannot be indexed because it has no default property. - '{0} se nedá indexovat, protože nemá žádnou výchozí vlastnost. + {0} se nedá indexovat, protože nemá žádnou výchozí vlastnost. @@ -2220,7 +2264,7 @@ '{0}' is ambiguous. - '{0} je nejednoznačný. + {0} je nejednoznačný. @@ -2320,12 +2364,12 @@ '{0}.{1}' cannot be implemented more than once. - '{0}.{1} nejde implementovat víc než jednou. + {0}.{1} nejde implementovat víc než jednou. '{0}' cannot be inherited more than once. - '{0} nejde dědit víc než jednou. + {0} nejde dědit víc než jednou. @@ -2390,7 +2434,7 @@ '{0}' is a MustOverride event in the base class '{1}'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class '{2}' MustInherit. - '{0} je událost třídy MustOverride v základní třídě {1}. Visual Basic nepodporuje přepisování událostí. Buď musíte zadat implementaci události v základní třídě, nebo vytvořit třídu {2} MustInherit. + {0} je událost třídy MustOverride v základní třídě {1}. Visual Basic nepodporuje přepisování událostí. Buď musíte zadat implementaci události v základní třídě, nebo vytvořit třídu {2} MustInherit. @@ -2570,7 +2614,7 @@ '{0}' is an unsupported type. - '{0} je nepodporovaný typ. + {0} je nepodporovaný typ. @@ -2717,7 +2761,7 @@ '{0}' is not an event of '{1}'. - '{0} není událost v {1}. + {0} není událost v {1}. @@ -2782,7 +2826,7 @@ '{0}' cannot override '{1}' because they differ by the types of optional parameters. - '{0} nemůže přepsat {1}, protože se liší typy nepovinných parametrů. + {0} nemůže přepsat {1}, protože se liší typy nepovinných parametrů. @@ -2802,7 +2846,7 @@ '{0}' is already declared as a parameter of this method. - '{0} už je deklarovaný jako parametr této metody. + {0} už je deklarovaný jako parametr této metody. @@ -3027,7 +3071,7 @@ '{0}' cannot override '{1}' because they differ by parameters declared 'ParamArray'. - '{0} nemůže přepsat {1}, protože se liší parametry deklarovanými jako ParamArray. + {0} nemůže přepsat {1}, protože se liší parametry deklarovanými jako ParamArray. @@ -3042,12 +3086,12 @@ '{0}' cannot expose type '{1}' outside the project through {2} '{3}'. - '{0} nemůže vystavovat typ {1} mimo projekt prostřednictvím {2} - {3}. + {0} nemůže vystavovat typ {1} mimo projekt prostřednictvím {2} - {3}. '{0}' cannot inherit from {1} '{2}' because it expands the access of the base {1} outside the assembly. - '{0} nemůže dědit z {1} - {2}, protože rozšiřuje přístup základní třídy {1} mimo sestavení. + {0} nemůže dědit z {1} - {2}, protože rozšiřuje přístup základní třídy {1} mimo sestavení. @@ -3062,12 +3106,12 @@ '{0}' cannot expose the underlying delegate type '{1}' of the event it is implementing to {2} '{3}' through {4} '{5}'. - '{0} nemůže vystavovat nadřazený typ delegáta {1} události, kterou implementuje do {2} - {3} prostřednictvím {4} - {5}. + {0} nemůže vystavovat nadřazený typ delegáta {1} události, kterou implementuje do {2} - {3} prostřednictvím {4} - {5}. '{0}' cannot expose the underlying delegate type '{1}' of the event it is implementing outside the project through {2} '{3}'. - '{0} nemůže vystavovat nadřazený typ delegáta {1} události, kterou implementuje mimo projekt prostřednictvím {2} - {3}. + {0} nemůže vystavovat nadřazený typ delegáta {1} události, kterou implementuje mimo projekt prostřednictvím {2} - {3}. @@ -3097,12 +3141,12 @@ '{0}' cannot inherit from {1} '{2}' because it expands the access of type '{3}' to {4} '{5}'. - '{0} nemůže dědit z {1} - {2}, protože rozšiřuje přístup typu {3} na {4} - {5}. + {0} nemůže dědit z {1} - {2}, protože rozšiřuje přístup typu {3} na {4} - {5}. '{0}' cannot inherit from {1} '{2}' because it expands the access of type '{3}' outside the assembly. - '{0} nemůže dědit z {1} - {2}, protože rozšiřuje přístup typu {3} mimo sestavení. + {0} nemůže dědit z {1} - {2}, protože rozšiřuje přístup typu {3} mimo sestavení. @@ -3213,7 +3257,7 @@ '{0}' in class '{1}' cannot override '{2}' in class '{3}' because an intermediate class '{4}' overrides '{2}' in class '{3}' but is not accessible. - '{0} ve třídě {1} nemůže potlačovat {2} ve třídě {3}, protože zprostředkující třída {4} potlačuje {2} ve třídě {3}, ale není dostupná. + {0} ve třídě {1} nemůže potlačovat {2} ve třídě {3}, protože zprostředkující třída {4} potlačuje {2} ve třídě {3}, ale není dostupná. @@ -3513,12 +3557,12 @@ '{0}' is a module and cannot be referenced as an assembly. - '{0} je modul a nejde na něho odkazovat jako na sestavení. + {0} je modul a nejde na něho odkazovat jako na sestavení. '{0}' is an assembly and cannot be referenced as a module. - '{0} je sestavení a nejde na něho odkazovat jako na modul. + {0} je sestavení a nejde na něho odkazovat jako na modul. @@ -3528,7 +3572,7 @@ '{0}' is not a local variable or parameter, and so cannot be used as a 'Catch' variable. - '{0} není lokální proměnná ani parametr, a proto se nedá použít jako proměnná Catch. + {0} není lokální proměnná ani parametr, a proto se nedá použít jako proměnná Catch. @@ -3548,7 +3592,7 @@ '{0}' cannot override '{1}' because it is not declared 'Overridable'. - '{0} nemůže přepsat {1}, protože není deklarovaná jako Overridable. + {0} nemůže přepsat {1}, protože není deklarovaná jako Overridable. @@ -3788,7 +3832,7 @@ '{0}' cannot refer to itself through its default instance; use 'Me' instead. - '{0} nemůže odkazovat sama na sebe prostřednictvím výchozí instance; místo toho použijte možnost Me. + {0} nemůže odkazovat sama na sebe prostřednictvím výchozí instance; místo toho použijte možnost Me. @@ -3803,7 +3847,7 @@ '{0}' cannot be applied to the 'AddHandler', 'RemoveHandler', or 'RaiseEvent' definitions. If required, apply the attribute directly to the event. - '{0} nejde použít pro definice AddHandler, RemoveHandler nebo RaiseEvent. V případě potřeby použijte atribut přímo pro událost. + {0} nejde použít pro definice AddHandler, RemoveHandler nebo RaiseEvent. V případě potřeby použijte atribut přímo pro událost. @@ -4113,7 +4157,7 @@ '{0}' cannot shadow a method declared 'MustOverride'. - '{0} nemůže zastiňovat metodu s deklarací MustOverride. + {0} nemůže zastiňovat metodu s deklarací MustOverride. @@ -4123,7 +4167,7 @@ '{0}' and '{1}' cannot be combined. - '{0} a {1} nejde kombinovat. + {0} a {1} nejde kombinovat. @@ -4143,12 +4187,12 @@ '{0}', implicitly declared for {1} '{2}', cannot shadow a 'MustOverride' method in the base {3} '{4}'. - '{0}, implicitně deklarovaný pro {1} - {2}, nemůže zastiňovat metodu MustOverride v základní třídě {3} – {4}. + {0}, implicitně deklarovaný pro {1} - {2}, nemůže zastiňovat metodu MustOverride v základní třídě {3} – {4}. '{0}' cannot override '{1}' because it is not accessible in this context. - '{0} nemůže přepsat {1}, protože není v tomto kontextu k dispozici. + {0} nemůže přepsat {1}, protože není v tomto kontextu k dispozici. @@ -4163,7 +4207,7 @@ '{0}' conflicts with the reserved member by this name that is implicitly declared in all enums. - '{0} je v konfliktu s vyhrazeným členem podle tohoto názvu, který je implicitně deklarovaný ve všech výčtech. + {0} je v konfliktu s vyhrazeným členem podle tohoto názvu, který je implicitně deklarovaný ve všech výčtech. @@ -4188,7 +4232,7 @@ '{0}' in assembly '{1}' has been forwarded to itself and so is an unsupported type. - '{0} v sestavení {1} se předal sám sobě, jedná se proto o nepodporovaný typ. + {0} v sestavení {1} se předal sám sobě, jedná se proto o nepodporovaný typ. @@ -4483,7 +4527,7 @@ '{0}' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event. - '{0} je událost a nejde ji vyvolat přímo. K vyvolání události použijte příkaz RaiseEvent. + {0} je událost a nejde ji vyvolat přímo. K vyvolání události použijte příkaz RaiseEvent. @@ -4568,7 +4612,7 @@ '{0}' has no type parameters and so cannot have type arguments. - '{0} nemá žádné parametry typu, nemůže proto mít argumenty typu. + {0} nemá žádné parametry typu, nemůže proto mít argumenty typu. @@ -4608,7 +4652,7 @@ '{0}' has the same name as a type parameter. - '{0} má stejný název jako parametr typu. + {0} má stejný název jako parametr typu. @@ -4633,7 +4677,7 @@ '{0}' cannot be used as a type constraint. - '{0} nejde použít jako omezení typu. + {0} nejde použít jako omezení typu. @@ -4688,12 +4732,12 @@ '{0}' cannot override '{1}' because they differ by type parameter constraints. - '{0} nemůže přepsat {1}, protože se liší v omezeních parametrů typu. + {0} nemůže přepsat {1}, protože se liší v omezeních parametrů typu. '{0}' cannot implement '{1}.{2}' because they differ by type parameter constraints. - '{0} nemůže implementovat {1}.{2}, protože se liší v omezeních parametrů typu. + {0} nemůže implementovat {1}.{2}, protože se liší v omezeních parametrů typu. @@ -4748,7 +4792,7 @@ '{0}' is already declared as a type parameter of this method. - '{0} je už deklarovaný jako parametr typu této metody. + {0} je už deklarovaný jako parametr typu této metody. @@ -5340,7 +5384,7 @@ '{0}' has the same name as a member used for type '{1}' exposed in a 'My' group. Rename the type or its enclosing namespace. - '{0} má stejný název, jako jiný člen použil pro typ {1} vystavený ve skupině My. Přejmenujte typ nebo obor názvů, v němž je obsažený. + {0} má stejný název, jako jiný člen použil pro typ {1} vystavený ve skupině My. Přejmenujte typ nebo obor názvů, v němž je obsažený. @@ -5440,7 +5484,7 @@ '{0}' is not a member of '{1}'; it does not exist in the current context. - '{0} není členem {1} a v aktuálním kontextu neexistuje. + {0} není členem {1} a v aktuálním kontextu neexistuje. @@ -5512,7 +5556,7 @@ '{0}' is not a method parameter. - '{0} není parametr metody. + {0} není parametr metody. @@ -5564,7 +5608,7 @@ '{0}' is not a parameter of extension method '{1}' defined in '{2}'. - '{0} není parametr metody rozšíření {1} definované v {2}. + {0} není parametr metody rozšíření {1} definované v {2}. @@ -5609,7 +5653,7 @@ '{0}{1}' is not valid because '{2}' is inside a scope that defines a variable that is used in a lambda or query expression. - '{0}{1} je neplatný, protože {2} se nachází v oboru definujícím proměnnou, která se používá v lambda výrazu nebo ve výrazu dotazu. + {0}{1} je neplatný, protože {2} se nachází v oboru definujícím proměnnou, která se používá v lambda výrazu nebo ve výrazu dotazu. @@ -6136,7 +6180,7 @@ '{0}' is not CLS-compliant because it derives from '{1}', which is not CLS-compliant. - '{0} není kompatibilní se specifikací CLS, protože se odvozuje z {1}, které není kompatibilní se specifikací CLS. + {0} není kompatibilní se specifikací CLS, protože se odvozuje z {1}, které není kompatibilní se specifikací CLS. @@ -6166,7 +6210,7 @@ '{0}' is not CLS-compliant because the interface '{1}' it inherits from is not CLS-compliant. - '{0} není kompatibilní se specifikací CLS, protože rozhraní {1}, ze kterého se dědí, není kompatibilní se specifikací CLS. + {0} není kompatibilní se specifikací CLS, protože rozhraní {1}, ze kterého se dědí, není kompatibilní se specifikací CLS. @@ -6226,7 +6270,7 @@ '{0}' is not CLS-compliant because it overloads '{1}' which differs from it only by array of array parameter types or by the rank of the array parameter types. - '{0} není kompatibilní se specifikací CLS, protože přetěžuje {1}. Navzájem se liší jenom polem typů parametrů polí nebo rozměrem typů parametru pole. + {0} není kompatibilní se specifikací CLS, protože přetěžuje {1}. Navzájem se liší jenom polem typů parametrů polí nebo rozměrem typů parametru pole. @@ -6366,7 +6410,7 @@ '{0}' in designer-generated type '{1}' should call InitializeComponent method. - '{0} v typu {1} vygenerovaném prvkem návrhu musí volat metodu InitializeComponent. + {0} v typu {1} vygenerovaném prvkem návrhu musí volat metodu InitializeComponent. @@ -7361,7 +7405,7 @@ '{0}' cannot expose type '{1}' in {2} '{3}' through {4} '{5}'. - '{0} nemůže vystavovat typ {1} v {2} - {3} prostřednictvím {4} - {5}. + {0} nemůže vystavovat typ {1} v {2} - {3} prostřednictvím {4} - {5}. @@ -7371,7 +7415,7 @@ '{0}' cannot be implemented by a {1} property. - '{0} nejde implementovat vlastností {1}. + {0} nejde implementovat vlastností {1}. @@ -7663,12 +7707,12 @@ '{0}' cannot be converted to '{1}'. Consider using '{2}' instead. - '{0} není možno převést na {1}. Místo toho zvažte použití {2}. + {0} není možno převést na {1}. Místo toho zvažte použití {2}. '{0}' cannot be converted to '{1}'. Consider using '{2}' instead. - '{0} není možno převést na {1}. Místo toho zvažte použití {2}. + {0} není možno převést na {1}. Místo toho zvažte použití {2}. @@ -7678,12 +7722,12 @@ '{4}' cannot be converted to '{5}' because '{0}' is not derived from '{1}', as required for the 'In' generic parameter '{2}' in '{3}'. - '{4} není možno převést na {5}, protože {0} není odvozené z {1}, jak se vyžaduje pro obecný parametr In {2} v {3}. + {4} není možno převést na {5}, protože {0} není odvozené z {1}, jak se vyžaduje pro obecný parametr In {2} v {3}. '{4}' cannot be converted to '{5}' because '{0}' is not derived from '{1}', as required for the 'Out' generic parameter '{2}' in '{3}'. - '{4} není možno převést na {5}, protože {0} není odvozené z {1}, jak se vyžaduje pro obecný parametr Out {2} v {3}. + {4} není možno převést na {5}, protože {0} není odvozené z {1}, jak se vyžaduje pro obecný parametr Out {2} v {3}. @@ -7708,17 +7752,17 @@ '{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an In type parameter, 'In {2}'. - '{0} není možno převést na {1}. Zvažte změnu {2} v definici {3} na parametr typu In: In {2}. + {0} není možno převést na {1}. Zvažte změnu {2} v definici {3} na parametr typu In: In {2}. '{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an Out type parameter, 'Out {2}'. - '{0} není možno převést na {1}. Zvažte změnu {2} v definici {3} na parametr typu Out: Out {2}. + {0} není možno převést na {1}. Zvažte změnu {2} v definici {3} na parametr typu Out: Out {2}. '{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an In type parameter, 'In {2}'. - '{0} není možno převést na {1}. Zvažte změnu {2} v definici {3} na parametr typu In: In {2}. + {0} není možno převést na {1}. Zvažte změnu {2} v definici {3} na parametr typu In: In {2}. @@ -7728,7 +7772,7 @@ '{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an Out type parameter, 'Out {2}'. - '{0} není možno převést na {1}. Zvažte změnu {2} v definici {3} na parametr typu Out: Out {2}. + {0} není možno převést na {1}. Zvažte změnu {2} v definici {3} na parametr typu Out: Out {2}. @@ -7998,7 +8042,7 @@ '{0}' does not implement '{1}'. - '{0} neimplementuje {1}. + {0} neimplementuje {1}. @@ -8093,7 +8137,7 @@ '{0}' cannot be used as a parameter type for an Iterator or Async method. - '{0} nejde použít jako typ parametru pro metodu iterátoru nebo asynchronní metodu. + {0} nejde použít jako typ parametru pro metodu iterátoru nebo asynchronní metodu. @@ -8218,12 +8262,12 @@ '{0}.{1}' from 'implements {2}' is already implemented by the base class '{3}'. Re-implementation of Windows Runtime Interface '{4}' is not allowed - '{0}.{1} z klauzule implements {2} je už implementované základní třídou {3}. Opětovná implementace rozhraní Windows Runtime {4} není povolená. + {0}.{1} z klauzule implements {2} je už implementované základní třídou {3}. Opětovná implementace rozhraní Windows Runtime {4} není povolená. '{0}.{1}' is already implemented by the base class '{2}'. Re-implementation of Windows Runtime Interface '{3}' is not allowed - '{0}.{1} je už implementované základní třídou {2}. Opětovná implementace rozhraní modulu Windows Runtime {3} není povolená. + {0}.{1} je už implementované základní třídou {2}. Opětovná implementace rozhraní modulu Windows Runtime {3} není povolená. @@ -8448,12 +8492,12 @@ '{0}' is an unsupported .NET module. - '{0} je nepodporovaný modul .NET. + {0} je nepodporovaný modul .NET. '{0}' is an unsupported event. - '{0} je nepodporovaná událost. + {0} je nepodporovaná událost. @@ -8718,7 +8762,7 @@ '{0}' is not a valid format specifier - '{0} není platným specifikátorem formátu. + {0} není platným specifikátorem formátu. @@ -8733,7 +8777,7 @@ '{0}' cannot be made nullable. - '{0} nejde nastavit tak, aby se povolovala hodnota null. + {0} nejde nastavit tak, aby se povolovala hodnota null. @@ -9103,7 +9147,7 @@ '{0}' is for evaluation purposes only and is subject to change or removal in future updates. - '{0} slouží jen pro účely vyhodnocení a v budoucích aktualizacích může dojít ke změně nebo odebrání. + {0} slouží jen pro účely vyhodnocení a v budoucích aktualizacích může dojít ke změně nebo odebrání. diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.de.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.de.xlf index b6c94960b2008..24d84acaabc0a 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.de.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.de.xlf @@ -212,169 +212,169 @@ -vbruntime:<file> Compile with the alternate Visual Basic runtime in <file>. - Visual Basic Compiler Options + Visual Basic-Compileroptionen - - OUTPUT FILE - --out:<file> Specifies the output file name. --target:exe Create a console application (default). - (Short form: -t) --target:winexe Create a Windows application. --target:library Create a library assembly. --target:module Create a module that can be added to an - assembly. --target:appcontainerexe Create a Windows application that runs in - AppContainer. --target:winmdobj Create a Windows Metadata intermediate file --doc[+|-] Generates XML documentation file. --doc:<file> Generates XML documentation file to <file>. --refout:<file> Reference assembly output to generate + – AUSGABEDATEI – +-out:<Datei> Gibt den Ausgabedateinamen an. +-target:exe Erstellt eine Konsolenanwendung (Standardwert). + (Kurzform: -t) +-target:winexe Erstellt eine Windows-Anwendung. +-target:library Erstellt eine Bibliotheksassembly. +-target:module Erstellt ein Modul, das einer Assembly + hinzugefügt werden kann. +-target:appcontainerexe Erstellt eine Windows-Anwendung, die in + AppContainer ausgeführt wird. +-target:winmdobj Erstellt eine Windows-Metadatenzwischendatei. +-doc[+|-] Generiert eine XML-Dokumentationsdatei. +-doc:<Datei> Generiert eine XML-Dokumentationsdatei in <Datei>. +-refout:<Datei> Zu generierende Referenzassemblyausgabe - - INPUT FILES - --addmodule:<file_list> Reference metadata from the specified modules --link:<file_list> Embed metadata from the specified interop - assembly. (Short form: -l) --recurse:<wildcard> Include all files in the current directory - and subdirectories according to the - wildcard specifications. --reference:<file_list> Reference metadata from the specified - assembly. (Short form: -r) --analyzer:<file_list> Run the analyzers from this assembly - (Short form: -a) --additionalfile:<file list> Additional files that don't directly affect code - generation but may be used by analyzers for producing - errors or warnings. + – EINGABEDATEIEN – +-addmodule:<Dateiliste> Verweist auf Metadaten aus den angegebenen Modulen. +-link:<Dateiliste> Bettet Metadaten aus der angegebenen Interop- + assembly ein. (Kurzform: -l) +-recurse:<Platzhalter> Schließt alle Dateien im aktuellen Verzeichnis + und dessen Unterverzeichnissen gemäß den + Platzhalterspezifikationen ein. +-reference:<Dateiliste> Verweist auf Metadaten aus der angegebenen + Assembly. (Kurzform: -r) +-analyzer:<Dateiliste> Führt die Analyzer aus dieser Assembly aus. + (Kurzform: -a) +-additionalfile:<Dateiliste> Zusätzliche Dateien, die sich nicht direkt auf die Code- + generierung auswirken, aber ggf. von Analyzern zum Erstellen von + Fehlern oder Warnungen verwendet werden können. - - RESOURCES - --linkresource:<resinfo> Links the specified file as an external - assembly resource. - resinfo:<file>[,<name>[,public|private]] - (Short form: -linkres) --nowin32manifest The default manifest should not be embedded - in the manifest section of the output PE. --resource:<resinfo> Adds the specified file as an embedded - assembly resource. - resinfo:<file>[,<name>[,public|private]] - (Short form: -res) --win32icon:<file> Specifies a Win32 icon file (.ico) for the - default Win32 resources. --win32manifest:<file> The provided file is embedded in the manifest - section of the output PE. --win32resource:<file> Specifies a Win32 resource file (.res). + – RESSOURCEN – +-linkresource:<resinfo> Verknüpft die angegebene Datei als eine externe + Assemblyressource. + resinfo:<Datei>[,<Name>[,public|private]] + (Kurzform: -linkres) +-nowin32manifest Das Standardmanifest soll nicht in den + Manifestabschnitt der PE-Ausgabedatei eingebettet werden. +-resource:<resinfo> Fügt die angegebene Datei als eine eingebettete + Assemblyressource hinzu. + resinfo:<Datei>[,<Name>[,public|private]] + (Kurzform: -res) +-win32icon:<Datei> Gibt eine Win32-Symboldatei (ICO-Datei) für die + Win32-Standardressourcen an. +-win32manifest:<Datei> Die angegebene Datei wird im Manifest- + abschnitt der PE-Ausgabedatei eingebettet. +-win32resource:<Datei> Gibt eine Win32-Ressourcendatei (RES-Datei) an. - - CODE GENERATION - --optimize[+|-] Enable optimizations. --removeintchecks[+|-] Remove integer checks. Default off. --debug[+|-] Emit debugging information. --debug:full Emit full debugging information (default). --debug:pdbonly Emit full debugging information. --debug:portable Emit cross-platform debugging information. --debug:embedded Emit cross-platform debugging information into - the target .dll or .exe. --deterministic Produce a deterministic assembly - (including module version GUID and timestamp) --refonly Produce a reference assembly in place of the main output --instrument:TestCoverage Produce an assembly instrumented to collect - coverage information --sourcelink:<file> Source link info to embed into PDB. + – CODEGENERIERUNG – +-optimize[+|-] Aktiviert Optimierungen. +-removeintchecks[+|-] Entfernt Integerüberprüfungen. Standardmäßig deaktiviert. +-debug[+|-] Gibt Debuginformationen aus. +-debug:full Gibt vollständige Debuginformationen aus (Standardeinstellung). +-debug:pdbonly Gibt vollständige Debuginformationen aus. +-debug:portable Gibt plattformübergreifende Debuginformationen aus. +-debug:embedded Gibt plattformübergreifende Debuginformationen in + die Ziel-DLL oder -EXE aus. +-deterministic Generiert eine deterministische Assembly + (einschließlich Modulversion-GUID und Zeitstempel) +-refonly Erstellt eine Referenzassembly anstelle der Hauptausgabe +-instrument:TestCoverage Erstellt eine Assembly, die zum Erfassen von Abdeckungsinformationen + instrumentiert ist. +-sourcelink:<Datei> Quelllinkinformationen, die in die PDB-Datei eingebettet werden sollen. - - ERRORS AND WARNINGS - --nowarn Disable all warnings. --nowarn:<number_list> Disable a list of individual warnings. --warnaserror[+|-] Treat all warnings as errors. --warnaserror[+|-]:<number_list> Treat a list of warnings as errors. --ruleset:<file> Specify a ruleset file that disables specific - diagnostics. --errorlog:<file>[,version=<sarif_version>] - Specify a file to log all compiler and analyzer - diagnostics in SARIF format. - sarif_version:{1|2|2.1} Default is 1. 2 and 2.1 - both mean SARIF version 2.1.0. --reportanalyzer Report additional analyzer information, such as - execution time. --skipanalyzers[+|-] Skip execution of diagnostic analyzers. + – FEHLER UND WARNUNGEN – +-nowarn Deaktiviert alle Warnungen. +-nowarn:<Zahlenliste> Deaktiviert eine Liste einzelner Warnungen. +-warnaserror[+|-] Behandelt alle Warnungen als Fehler. +-warnaserror[+|-]:<Zahlenliste> Behandelt eine Liste von Warnungen als Fehler. +-ruleset:<Datei> Gibt eine Regelsatzdatei an, die bestimmte + Diagnosefunktionen deaktiviert. +-errorlog:<Datei>[,version=<sarif_version>] + Gibt eine Datei an, in der alle Compiler- und Analyzer- + diagnosedaten im SARIF-Format protokolliert werden. + sarif_version:{1|2|2.1} Standardwerte sind 1. 2 und 2.1, + beide beziehen sich auf SARIF-Version 2.1.0. +-reportanalyzer Meldet zusätzliche Analyzerinformationen, z. B. + die Ausführungszeit. +-skipanalyzers[+|-] Überspringt die Ausführung von Diagnoseanalysen. - - LANGUAGE - --define:<symbol_list> Declare global conditional compilation - symbol(s). symbol_list:name=value,... - (Short form: -d) --imports:<import_list> Declare global Imports for namespaces in - referenced metadata files. + – SPRACHE – +-define:<Symbolliste> Deklariert globale bedingte Kompilierung von + Symbolen. symbol_list:name=value,... + (Kurzform: -d) +-imports:<Importliste> Deklariert globale Importe für Namespaces in + Metadatendateien, auf die verwiesen wird. import_list:namespace,... --langversion:? Display the allowed values for language version --langversion:<string> Specify language version such as - `default` (latest major version), or - `latest` (latest version, including minor versions), - or specific versions like `14` or `15.3` --optionexplicit[+|-] Require explicit declaration of variables. --optioninfer[+|-] Allow type inference of variables. --rootnamespace:<string> Specifies the root Namespace for all type - declarations. --optionstrict[+|-] Enforce strict language semantics. --optionstrict:custom Warn when strict language semantics are not - respected. --optioncompare:binary Specifies binary-style string comparisons. - This is the default. --optioncompare:text Specifies text-style string comparisons. +-langversion:? Zeigt die zulässigen Werte für die Sprachversion an. +-langversion:<Zeichenfolge> Gibt die Sprachversion an: + "default" (neueste Hauptversion) oder + "latest" (neueste Version, einschließlich Nebenversionen) + oder bestimmte Versionen wie "14" oder "15.3". +-optionexplicit[+|-] Erfordert die explizite Deklaration von Variablen. +-optioninfer[+|-] Lässt den Typrückschluss von Variablen zu. +-rootnamespace:<Zeichenfolge> Gibt den Stammnamespace für alle Typ- + deklarationen an. +-optionstrict[+|-] Erzwingt strenge Sprachsemantik. +-optionstrict:custom Warnt, wenn die strenge Sprachsemantik nicht + beachtet wird. +-optioncompare:binary Gibt Zeichenfolgenvergleiche im Binärstil an. + Dies ist die Standardeinstellung. +-optioncompare:text Gibt Zeichenfolgenvergleiche im Textstil an. - - MISCELLANEOUS - --help Display this usage message. (Short form: -?) --noconfig Do not auto-include VBC.RSP file. --nologo Do not display compiler copyright banner. --quiet Quiet output mode. --verbose Display verbose messages. --parallel[+|-] Concurrent build. --version Display the compiler version number and exit. + – SONSTIGES – +-help Zeigt diese Syntaxinformationen an. (Kurzform: -?) +-noconfig Schließt die VBC.RSP-Datei nicht automatisch ein. +-nologo Zeigt das Compilercopyrightbanner nicht an. +-quiet Stiller Ausgabemodus. +-verbose Zeigt ausführliche Meldungen an. +-parallel[+|-] Gleichzeitige Erstellung. +-version Zeigt die Compilerversionsnummer und die Beendigung an. - - ADVANCED - --baseaddress:<number> The base address for a library or module - (hex). --checksumalgorithm:<alg> Specify algorithm for calculating source file - checksum stored in PDB. Supported values are: - SHA1 or SHA256 (default). --codepage:<number> Specifies the codepage to use when opening - source files. --delaysign[+|-] Delay-sign the assembly using only the public - portion of the strong name key. --publicsign[+|-] Public-sign the assembly using only the public - portion of the strong name key. --errorreport:<string> Specifies how to handle internal compiler - errors; must be prompt, send, none, or queue - (default). --filealign:<number> Specify the alignment used for output file - sections. --highentropyva[+|-] Enable high-entropy ASLR. --keycontainer:<string> Specifies a strong name key container. --keyfile:<file> Specifies a strong name key file. --libpath:<path_list> List of directories to search for metadata - references. (Semi-colon delimited.) --main:<class> Specifies the Class or Module that contains - Sub Main. It can also be a Class that - inherits from System.Windows.Forms.Form. - (Short form: -m) --moduleassemblyname:<string> Name of the assembly which this module will - be a part of. --netcf Target the .NET Compact Framework. --nostdlib Do not reference standard libraries - (system.dll and VBC.RSP file). + – ERWEITERT – +-baseaddress:<Zahl> Die Basisadresse für eine Bibliothek oder ein Modul + (hexadezimal). +-checksumalgorithm:<alg> Legt den Algorithmus zum Berechnen der Quelldatei- + prüfsumme fest, die in der PDB-Datei gespeichert ist. Unterstützte Werte sind: + SHA1 oder SHA256 (Standard). +-codepage:<Zahl> Gibt die Codepage an, die beim Öffnen von + Quelldateien verwendet werden soll. +-delaysign[+|-] Signiert die Assembly verzögert nur mithilfe des öffentlichen + Teils des Schlüssels für einen starken Namen. +-publicsign[+|-] Signiert die Assembly öffentlich nur mithilfe des öffentlichen + Teils des Schlüssels für einen starken Namen. +-errorreport:<Zeichenfolge> Gibt an, wie interne Compiler- + fehler behandelt werden. Mögliche Werte sind "prompt", "send", "none" oder "queue" + (Standardwert). +-filealign:<Zahl> Gibt die Ausrichtung an, die für die Abschnitte der + Ausgabedatei verwendet wird. +-highentropyva[+|-] Aktiviert ASLR mit hoher Entropie. +-keycontainer:<Zeichenfolge> Gibt einen Schlüsselcontainer mit starkem Namen an. +-keyfile:<Datei> Gibt eine Schlüsseldatei mit starkem Namen an. +-libpath:<Pfadliste> Die Liste der Verzeichnisse, die nach Metadaten- + verweisen durchsucht werden sollen (durch Semikolons getrennt). +-main:<Klasse> Gibt die Klasse oder das Modul an, die bzw. das + "Sub Main" enthält. Es kann sich auch um eine Klasse handeln, + die von "System.Windows.Forms.Form" erbt. + (Kurzform: -m) +-moduleassemblyname:<Zeichenfolge> Der Name der Assembly, zu der dieses Modul + gehören wird. +-netcf Gibt .NET Compact Framework als Ziel an. +-nostdlib Keine Verweise auf Standardbibliotheken + ("system.dll" und VBC.RSP-Datei). -pathmap:<K1>=<V1>,<K2>=<V2>,... - Specify a mapping for source path names output by - the compiler. --platform:<string> Limit which platforms this code can run on; - must be x86, x64, Itanium, arm, arm64 - AnyCPU32BitPreferred or anycpu (default). --preferreduilang Specify the preferred output language name. --nosdkpath Disable searching the default SDK path for standard library assemblies. --sdkpath:<path> Location of the .NET Framework SDK directory + Gibt eine Zuordnung für die Ausgabe der Quellpfadnamen durch + den Compiler an. +-platform:<Zeichenfolge> Schränkt die Plattformen ein, auf denen dieser Code ausgeführt werden kann; + gültige Werte sind "x86", "x64", "Itanium", "arm", "arm64", + "AnyCPU32BitPreferred" oder "anycpu" (Standard). +-preferreduilang Gibt den Namen der bevorzugten Ausgabesprache an. +-nosdkpath Deaktiviert das Durchsuchen des Standard-SDK-Pfads nach Standardbibliotheksassemblys. +-sdkpath:<Pfad> Der Speicherort des .NET Framework SDK-Verzeichnisses (mscorlib.dll). --subsystemversion:<version> Specify subsystem version of the output PE. - version:<number>[.<number>] --utf8output[+|-] Emit compiler output in UTF8 character - encoding. -@<file> Insert command-line settings from a text file --vbruntime[+|-|*] Compile with/without the default Visual Basic - runtime. --vbruntime:<file> Compile with the alternate Visual Basic - runtime in <file>. +-subsystemversion:<Version> Gibt die Subsystemversion der PE-Ausgabedatei an. + version:<Zahl>[.<Zahl>] +-utf8output[+|-] Gibt die Compilerausgabe in UTF8-Zeichen- + codierung aus. +@<Datei> Fügt Befehlszeileneinstellungen aus einer Textdatei ein. +-vbruntime[+|-|*] Kompiliert mit der bzw. ohne die Visual Basic- + Standardruntime. +-vbruntime:<Datei> Kompiliert mit der Visual Basic- + Alternativruntime in <Datei>. @@ -463,6 +463,50 @@ Typargument kann nicht "Nothing" sein + + The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + Die Assembly "{0}" mit dem Typ "{1}" verweist auf das .NET Framework. Dies wird nicht unterstützt. + {1} is the type that was loaded, {0} is the containing assembly. + + + The loaded assembly references .NET Framework, which is not supported. + Die geladene Assembly verweist auf das .NET Framework. Dies wird nicht unterstützt. + + + + Generator '{0}' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + Fehler beim Generieren der Quelle durch den Generator "{0}". Dieser wird bei der Ausgabe nicht berücksichtigt, deshalb kann es zu Kompilierungsfehlern kommen. Ausnahmetyp: {1}. Meldung: {2} + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + Der Generator hat die folgende Ausnahme ausgelöst: +{0} + {0} is the string representation of the exception that was thrown. + + + Generator failed to generate source. + Fehler beim Generieren der Quelle durch den Generator. + + + + Generator '{0}' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + Fehler beim Initialisieren des Generators "{0}". Er wird bei der Ausgabe nicht berücksichtigt, deshalb kann es zu Kompilierungsfehlern kommen. Ausnahmetyp: {1}. Meldung: {2} + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + Der Generator hat die folgende Ausnahme ausgelöst: +{0} + {0} is the string representation of the exception that was thrown. + + + Generator failed to initialize. + Fehler beim Initialisieren des Generators. + + Wrong number of type arguments Falsche Anzahl von Typargumenten. @@ -615,7 +659,7 @@ '{0}' is not a valid value for /moduleassemblyname - '"{0}" ist kein gültiger Wert für /moduleassemblyname + "{0}" ist kein gültiger Wert für /moduleassemblyname @@ -815,12 +859,12 @@ '{0}' is valid only within an instance method. - '"{0}" ist nur innerhalb einer Instanzmethode gültig. + "{0}" ist nur innerhalb einer Instanzmethode gültig. '{0}' is not valid within a structure. - '"{0}" ist innerhalb einer Struktur ungültig. + "{0}" ist innerhalb einer Struktur ungültig. @@ -1055,42 +1099,42 @@ '{0}' is an Enum type and cannot be used as an expression. - '"{0}" ist ein Enumerationstyp und kann nicht als Ausdruck verwendet werden. + "{0}" ist ein Enumerationstyp und kann nicht als Ausdruck verwendet werden. '{0}' is a type and cannot be used as an expression. - '"{0}" ist ein Typ und kann nicht als Ausdruck verwendet werden. + "{0}" ist ein Typ und kann nicht als Ausdruck verwendet werden. '{0}' is a class type and cannot be used as an expression. - '"{0}" ist ein Klassentyp und kann nicht als Ausdruck verwendet werden. + "{0}" ist ein Klassentyp und kann nicht als Ausdruck verwendet werden. '{0}' is a structure type and cannot be used as an expression. - '"{0}" ist ein Strukturtyp und kann nicht als Ausdruck verwendet werden. + "{0}" ist ein Strukturtyp und kann nicht als Ausdruck verwendet werden. '{0}' is an interface type and cannot be used as an expression. - '"{0}" ist ein Schnittstellentyp und kann nicht als Ausdruck verwendet werden. + "{0}" ist ein Schnittstellentyp und kann nicht als Ausdruck verwendet werden. '{0}' is a namespace and cannot be used as an expression. - '"{0}" ist ein Namespace und kann nicht als Ausdruck verwendet werden. + "{0}" ist ein Namespace und kann nicht als Ausdruck verwendet werden. '{0}' is not a valid name and cannot be used as the root namespace name. - '"{0}" ist kein gültiger Name und darf nicht als Stammnamespace-Name verwendet werden. + "{0}" ist kein gültiger Name und darf nicht als Stammnamespace-Name verwendet werden. '{0}' is an XML prefix and cannot be used as an expression. Use the GetXmlNamespace operator to create a namespace object. - '"{0}" ist ein XML-Präfix und kann nicht als Ausdruck verwendet werden. Erstellen Sie mit dem GetXmlNamespace-Operator ein Namespaceobjekt. + "{0}" ist ein XML-Präfix und kann nicht als Ausdruck verwendet werden. Erstellen Sie mit dem GetXmlNamespace-Operator ein Namespaceobjekt. @@ -1350,17 +1394,17 @@ '{0}' is not valid on a constant declaration. - '"{0}" ist in einer Konstantendeklaration ungültig. + "{0}" ist in einer Konstantendeklaration ungültig. '{0}' is not valid on a WithEvents declaration. - '"{0}" ist in einer WithEvents-Deklaration ungültig. + "{0}" ist in einer WithEvents-Deklaration ungültig. '{0}' is not valid on a member variable declaration. - '"{0}" ist in einer Membervariablendeklaration ungültig. + "{0}" ist in einer Membervariablendeklaration ungültig. @@ -1400,27 +1444,27 @@ '{0}' is not valid on a method declaration. - '"{0}" ist in einer Methodendeklaration ungültig. + "{0}" ist in einer Methodendeklaration ungültig. '{0}' is not valid on an event declaration. - '"{0}" ist in einer Ereignisdeklaration ungültig. + "{0}" ist in einer Ereignisdeklaration ungültig. '{0}' is not valid on a Declare. - '"{0}" ist in einer Declare-Anweisung ungültig. + "{0}" ist in einer Declare-Anweisung ungültig. '{0}' is not valid on a local constant declaration. - '"{0}" ist in der Deklaration von lokalen Konstanten ungültig. + "{0}" ist in der Deklaration von lokalen Konstanten ungültig. '{0}' is not valid on a local variable declaration. - '"{0}" ist in der Deklaration von lokalen Variablen ungültig. + "{0}" ist in der Deklaration von lokalen Variablen ungültig. @@ -1474,42 +1518,42 @@ '{0}' is already declared as '{1}' in this {2}. - '"{0}" wurde bereits als "{1}" in dieser {2} deklariert. + "{0}" wurde bereits als "{1}" in dieser {2} deklariert. '{0}' cannot override '{1}' because they have different access levels. - '"{0}" kann "{1}" nicht überschreiben, da sie unterschiedliche Zugriffsebenen haben. + "{0}" kann "{1}" nicht überschreiben, da sie unterschiedliche Zugriffsebenen haben. '{0}' cannot override '{1}' because it is declared 'NotOverridable'. - '"{0}" kann "{1}" nicht überschreiben, da es als "NotOverridable" deklariert ist. + "{0}" kann "{1}" nicht überschreiben, da es als "NotOverridable" deklariert ist. '{0}' has multiple definitions with identical signatures. - '"{0}" hat mehrere Definitionen mit identischen Signaturen. + "{0}" hat mehrere Definitionen mit identischen Signaturen. '{0}' has multiple definitions with identical signatures with different tuple element names, including '{1}'. - '"{0}" besitzt mehrere Definitionen mit identischen Signaturen mit verschiedenen Tupelelementnamen (einschließlich "{1}"). + "{0}" besitzt mehrere Definitionen mit identischen Signaturen mit verschiedenen Tupelelementnamen (einschließlich "{1}"). '{0}' is not valid on an interface method declaration. - '"{0}" ist in einer Schnittstellen-Methodendeklaration ungültig. + "{0}" ist in einer Schnittstellen-Methodendeklaration ungültig. '{0}' is not a parameter of '{1}'. - '"{0}" ist kein Parameter von "{1}". + "{0}" ist kein Parameter von "{1}". '{0}' is not valid on an interface property declaration. - '"{0}" ist in einer Schnittstellen-Eigenschaftendeklaration ungültig. + "{0}" ist in einer Schnittstellen-Eigenschaftendeklaration ungültig. @@ -1519,7 +1563,7 @@ '{0}' is not valid on an interface event declaration. - '"{0}" ist in einer Schnittstellen-Ereignisdeklaration ungültig. + "{0}" ist in einer Schnittstellen-Ereignisdeklaration ungültig. @@ -1618,17 +1662,17 @@ '{0}' cannot inherit from {2} '{1}' because '{1}' is declared 'NotInheritable'. - '"{0}" kann nicht von {2} "{1}" erben, da "{1}" als "NotInheritable" deklariert ist. + "{0}" kann nicht von {2} "{1}" erben, da "{1}" als "NotInheritable" deklariert ist. '{0}' and '{1}' cannot overload each other because they differ only by optional parameters. - '"{0}" und "{1}" können sich nicht gegenseitig überladen, da sie sich nur durch optionale Parameter unterscheiden. + "{0}" und "{1}" können sich nicht gegenseitig überladen, da sie sich nur durch optionale Parameter unterscheiden. '{0}' and '{1}' cannot overload each other because they differ only by return types. - '"{0}" und "{1}" können sich nicht gegenseitig überladen, da sie sich nur durch Rückgabetypen unterscheiden. + "{0}" und "{1}" können sich nicht gegenseitig überladen, da sie sich nur durch Rückgabetypen unterscheiden. @@ -1643,7 +1687,7 @@ '{0}' and '{1}' cannot overload each other because they differ only by the default values of optional parameters. - '"{0}" und "{1}" können sich nicht gegenseitig überladen, da sich nur die Standardwerte der optionalen Parameter unterscheiden. + "{0}" und "{1}" können sich nicht gegenseitig überladen, da sich nur die Standardwerte der optionalen Parameter unterscheiden. @@ -1653,12 +1697,12 @@ '{0}' cannot override '{1}' because they differ by the default values of optional parameters. - '"{0}" kann "{1}" nicht überschreiben, da sie sich durch Standardwerte optionaler Parameter unterscheiden. + "{0}" kann "{1}" nicht überschreiben, da sie sich durch Standardwerte optionaler Parameter unterscheiden. '{0}' cannot override '{1}' because they differ by optional parameters. - '"{0}" kann "{1}" nicht überschreiben, da sie sich durch optionale Parameter unterscheiden. + "{0}" kann "{1}" nicht überschreiben, da sie sich durch optionale Parameter unterscheiden. @@ -1693,7 +1737,7 @@ '{0}' and '{1}' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'. - '"{0}" und "{1}" können sich nicht gegenseitig überladen, da sie sich nur durch Parameter unterscheiden, die als "ByRef" oder "ByVal" deklariert sind. + "{0}" und "{1}" können sich nicht gegenseitig überladen, da sie sich nur durch Parameter unterscheiden, die als "ByRef" oder "ByVal" deklariert sind. @@ -1713,12 +1757,12 @@ '{0}' and '{1}' cannot overload each other because only one is declared 'Default'. - '"{0}" und "{1}" können sich nicht gegenseitig überladen, da nur eine als "Default" deklariert ist. + "{0}" und "{1}" können sich nicht gegenseitig überladen, da nur eine als "Default" deklariert ist. '{0}' cannot override '{1}' because they differ by 'ReadOnly' or 'WriteOnly'. - '"{0}" kann "{1}" nicht überschreiben, da sie sich durch "ReadOnly" oder "WriteOnly" unterscheiden. + "{0}" kann "{1}" nicht überschreiben, da sie sich durch "ReadOnly" oder "WriteOnly" unterscheiden. @@ -1733,7 +1777,7 @@ '{0}' and '{1}' cannot overload each other because they differ only by 'ReadOnly' or 'WriteOnly'. - '"{0}" und "{1}" können sich nicht gegenseitig überladen, da sie sich nur durch "ReadOnly" oder "WriteOnly" unterscheiden. + "{0}" und "{1}" können sich nicht gegenseitig überladen, da sie sich nur durch "ReadOnly" oder "WriteOnly" unterscheiden. @@ -1743,7 +1787,7 @@ '{0}' and '{1}' cannot overload each other because they differ only by parameters declared 'ParamArray'. - '"{0}" und "{1}" können sich nicht gegenseitig überladen, da sie sich nur durch Parameter unterscheiden, die als "ParamArray" deklariert sind. + "{0}" und "{1}" können sich nicht gegenseitig überladen, da sie sich nur durch Parameter unterscheiden, die als "ParamArray" deklariert sind. @@ -1798,7 +1842,7 @@ '{0}' is not valid on a Delegate declaration. - '"{0}" ist in einer Delegatdeklaration ungültig. + "{0}" ist in einer Delegatdeklaration ungültig. @@ -1808,12 +1852,12 @@ '{0}' is not accessible in this context because it is '{1}'. - '"{0}" ist "{1}" und in diesem Kontext nicht zugreifbar. + "{0}" ist "{1}" und in diesem Kontext nicht zugreifbar. '{0}.{1}' is not accessible in this context because it is '{2}'. - '"{0}.{1}" ist "{2}" und in diesem Kontext nicht zugreifbar. + "{0}.{1}" ist "{2}" und in diesem Kontext nicht zugreifbar. @@ -1828,22 +1872,22 @@ '{0}' is not valid on a Structure declaration. - '"{0}" ist in einer Structure-Deklaration ungültig. + "{0}" ist in einer Structure-Deklaration ungültig. '{0}' is not valid on an Enum declaration. - '"{0}" ist in einer Enum-Deklaration ungültig. + "{0}" ist in einer Enum-Deklaration ungültig. '{0}' is not valid on an Interface declaration. - '"{0}" ist in einer Schnittstellendeklaration ungültig. + "{0}" ist in einer Schnittstellendeklaration ungültig. '{0}' cannot override '{1}' because they differ by a parameter that is marked as 'ByRef' versus 'ByVal'. - '"{0}" kann "{1}" nicht überschreiben, da sie sich durch einen als "ByRef" bzw. "ByVal" gekennzeichneten Parameter unterscheiden. + "{0}" kann "{1}" nicht überschreiben, da sie sich durch einen als "ByRef" bzw. "ByVal" gekennzeichneten Parameter unterscheiden. @@ -1853,12 +1897,12 @@ '{0}' cannot implement '{1}' because there is no matching {2} on interface '{3}'. - '"{0}" kann "{1}" nicht implementieren, da keine entsprechende "{2}" in der Schnittstelle "{3}" vorhanden ist. + "{0}" kann "{1}" nicht implementieren, da keine entsprechende "{2}" in der Schnittstelle "{3}" vorhanden ist. '{0}' cannot implement {1} '{2}' on interface '{3}' because the tuple element names in '{4}' do not match those in '{5}'. - '"{0}" kann {1} "{2}" für die Schnittstelle "{3}" nicht implementieren, weil die Tupelelementnamen in "{4}" nicht mit den Namen in "{5}" übereinstimmen. + "{0}" kann {1} "{2}" für die Schnittstelle "{3}" nicht implementieren, weil die Tupelelementnamen in "{4}" nicht mit den Namen in "{5}" übereinstimmen. @@ -1923,12 +1967,12 @@ '{0}' cannot override '{1}' because they differ by their return types. - '"{0}" kann "{1}" nicht überschreiben, da sie sich durch ihre Rückgabetypen unterscheiden. + "{0}" kann "{1}" nicht überschreiben, da sie sich durch ihre Rückgabetypen unterscheiden. '{0}' cannot override '{1}' because they differ by their tuple element names. - '"{0}" kann "{1}" nicht überschreiben, weil sich die Tupelelementnamen unterscheiden. + "{0}" kann "{1}" nicht überschreiben, weil sich die Tupelelementnamen unterscheiden. @@ -1958,7 +2002,7 @@ '{0}' is not declared. It may be inaccessible due to its protection level. - '"{0}" wurde nicht deklariert. Aufgrund der Schutzstufe ist unter Umständen kein Zugriff möglich. + "{0}" wurde nicht deklariert. Aufgrund der Schutzstufe ist unter Umständen kein Zugriff möglich. @@ -1978,7 +2022,7 @@ '{0}' is not a member of '{1}'. - '"{0}" ist kein Member von "{1}". + "{0}" ist kein Member von "{1}". @@ -1998,7 +2042,7 @@ '{1}' for the Imports '{0}' does not refer to a Namespace, Class, Structure, Enum or Module. - '"{1}" für Imports "{0}" verweist weder auf einen Namespace noch auf eine Klasse, Struktur, Enumeration oder ein Modul. + "{1}" für Imports "{0}" verweist weder auf einen Namespace noch auf eine Klasse, Struktur, Enumeration oder ein Modul. @@ -2048,7 +2092,7 @@ 'Default' cannot be combined with '{0}'. - '"{0}" kann nicht mit "Default" kombiniert werden. + "{0}" kann nicht mit "Default" kombiniert werden. @@ -2078,12 +2122,12 @@ 'Shared' cannot be combined with '{0}' on a method declaration. - '"{0}" kann in einer Methodendeklaration nicht mit "Shared" kombiniert werden. + "{0}" kann in einer Methodendeklaration nicht mit "Shared" kombiniert werden. 'Shared' cannot be combined with '{0}' on a property declaration. - '"{0}" kann in einer Eigenschaftendeklaration nicht mit "Shared" kombiniert werden. + "{0}" kann in einer Eigenschaftendeklaration nicht mit "Shared" kombiniert werden. @@ -2103,7 +2147,7 @@ '{0}' cannot inherit from {1} '{2}' because it expands the access of the base {1} to {3} '{4}'. - '"{0}" erweitert den Zugriff der Basis {1} auf {3} "{4}" und kann daher nicht von {1} "{2}" erben. + "{0}" erweitert den Zugriff der Basis {1} auf {3} "{4}" und kann daher nicht von {1} "{2}" erben. @@ -2205,7 +2249,7 @@ '{0}' cannot be indexed because it has no default property. - '"{0}" kann nicht indiziert werden, da sie keine Standardeigenschaft hat. + "{0}" kann nicht indiziert werden, da sie keine Standardeigenschaft hat. @@ -2220,7 +2264,7 @@ '{0}' is ambiguous. - '"{0}" ist mehrdeutig. + "{0}" ist mehrdeutig. @@ -2230,22 +2274,22 @@ '{0}' is ambiguous in the namespace '{1}'. - '"{0}" ist im Namespace "{1}" mehrdeutig. + "{0}" ist im Namespace "{1}" mehrdeutig. '{0}' is ambiguous, imported from the namespaces or types '{1}'. - '"{0}" ist mehrdeutig, importiert aus den Namespaces oder Typen "{1}". + "{0}" ist mehrdeutig, importiert aus den Namespaces oder Typen "{1}". '{0}' is ambiguous between declarations in Modules '{1}'. - '"{0}" ist zwischen Deklarationen in den Modulen "{1}" mehrdeutig. + "{0}" ist zwischen Deklarationen in den Modulen "{1}" mehrdeutig. '{0}' is ambiguous between declarations in namespaces '{1}'. - '"{0}" ist zwischen Deklarationen in den Namespaces "{1}" mehrdeutig. + "{0}" ist zwischen Deklarationen in den Namespaces "{1}" mehrdeutig. @@ -2320,12 +2364,12 @@ '{0}.{1}' cannot be implemented more than once. - '"{0}.{1}" kann nur einmal implementiert werden. + "{0}.{1}" kann nur einmal implementiert werden. '{0}' cannot be inherited more than once. - '"{0}" kann nicht mehrmals geerbt werden. + "{0}" kann nicht mehrmals geerbt werden. @@ -2390,7 +2434,7 @@ '{0}' is a MustOverride event in the base class '{1}'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class '{2}' MustInherit. - '"{0}" ist ein MustOverride-Ereignis in der Basisklasse "{1}". Das Überschreiben von Ereignissen wird in Visual Basic nicht unterstützt. Sie müssen entweder eine Implementierung für das Ereignis in der Basisklasse bereitstellen oder die Klasse "{2}" als MustInherit definieren. + "{0}" ist ein MustOverride-Ereignis in der Basisklasse "{1}". Das Überschreiben von Ereignissen wird in Visual Basic nicht unterstützt. Sie müssen entweder eine Implementierung für das Ereignis in der Basisklasse bereitstellen oder die Klasse "{2}" als MustInherit definieren. @@ -2570,7 +2614,7 @@ '{0}' is an unsupported type. - '"{0}" ist ein Typ, der nicht unterstützt wird. + "{0}" ist ein Typ, der nicht unterstützt wird. @@ -2605,7 +2649,7 @@ '{0}' has a return type that is not supported or parameter types that are not supported. - '"{0}" hat einen Rückgabetyp oder Parametertypen, die nicht unterstützt werden. + "{0}" hat einen Rückgabetyp oder Parametertypen, die nicht unterstützt werden. @@ -2687,7 +2731,7 @@ '{0}' is obsolete: '{1}'. - '"{0}" ist veraltet: "{1}". + "{0}" ist veraltet: "{1}". @@ -2717,7 +2761,7 @@ '{0}' is not an event of '{1}'. - '"{0}" ist kein Ereignis von "{1}". + "{0}" ist kein Ereignis von "{1}". @@ -2752,7 +2796,7 @@ '{0}' is ambiguous across the inherited interfaces '{1}' and '{2}'. - '"{0}" ist innerhalb der geerbten Schnittstellen "{1}" und "{2}" mehrdeutig. + "{0}" ist innerhalb der geerbten Schnittstellen "{1}" und "{2}" mehrdeutig. @@ -2782,7 +2826,7 @@ '{0}' cannot override '{1}' because they differ by the types of optional parameters. - '"{0}" kann "{1}" nicht überschreiben, da sie sich durch optionale Parametertypen unterscheiden. + "{0}" kann "{1}" nicht überschreiben, da sie sich durch optionale Parametertypen unterscheiden. @@ -2802,7 +2846,7 @@ '{0}' is already declared as a parameter of this method. - '"{0}" ist bereits als Parameter dieser Methode deklariert. + "{0}" ist bereits als Parameter dieser Methode deklariert. @@ -2942,7 +2986,7 @@ '{1}' for the Imports alias to '{0}' does not refer to a Namespace, Class, Structure, Interface, Enum or Module. - '"{1}" für den Imports-Alias für "{0}" bezieht sich nicht auf einen Namespace, eine Klasse, eine Struktur, eine Schnittstelle, eine Enumeration oder ein Modul. + "{1}" für den Imports-Alias für "{0}" bezieht sich nicht auf einen Namespace, eine Klasse, eine Struktur, eine Schnittstelle, eine Enumeration oder ein Modul. @@ -3027,7 +3071,7 @@ '{0}' cannot override '{1}' because they differ by parameters declared 'ParamArray'. - '"{0}" kann "{1}" nicht überschreiben, da sie sich durch Parameter unterscheiden, die als ParamArray deklariert sind. + "{0}" kann "{1}" nicht überschreiben, da sie sich durch Parameter unterscheiden, die als ParamArray deklariert sind. @@ -3042,12 +3086,12 @@ '{0}' cannot expose type '{1}' outside the project through {2} '{3}'. - '"{0}" kann den Typ "{1}" nicht außerhalb des Projekts über {2} "{3}" verfügbar machen. + "{0}" kann den Typ "{1}" nicht außerhalb des Projekts über {2} "{3}" verfügbar machen. '{0}' cannot inherit from {1} '{2}' because it expands the access of the base {1} outside the assembly. - '"{0}" erweitert den Zugriff der Basis-{1} außerhalb der Assembly und kann daher nicht von {1} "{2}" erben. + "{0}" erweitert den Zugriff der Basis-{1} außerhalb der Assembly und kann daher nicht von {1} "{2}" erben. @@ -3062,12 +3106,12 @@ '{0}' cannot expose the underlying delegate type '{1}' of the event it is implementing to {2} '{3}' through {4} '{5}'. - '"{0}" kann den zugrunde liegenden Delegattyp "{1}" des Ereignisses, das in {2} "{3}" implementiert wird, nicht über {4} "{5}" verfügbar machen. + "{0}" kann den zugrunde liegenden Delegattyp "{1}" des Ereignisses, das in {2} "{3}" implementiert wird, nicht über {4} "{5}" verfügbar machen. '{0}' cannot expose the underlying delegate type '{1}' of the event it is implementing outside the project through {2} '{3}'. - '"{0}" kann den zugrunde liegenden Delegattyp "{1}" des Ereignisses, das implementiert wird, nicht außerhalb des Projekts über {2} "{3}" verfügbar machen. + "{0}" kann den zugrunde liegenden Delegattyp "{1}" des Ereignisses, das implementiert wird, nicht außerhalb des Projekts über {2} "{3}" verfügbar machen. @@ -3097,12 +3141,12 @@ '{0}' cannot inherit from {1} '{2}' because it expands the access of type '{3}' to {4} '{5}'. - '"{0}" erweitert den Zugriff des Typs "{3}" auf {4} "{5}" und kann daher nicht von {1} "{2}" erben. + "{0}" erweitert den Zugriff des Typs "{3}" auf {4} "{5}" und kann daher nicht von {1} "{2}" erben. '{0}' cannot inherit from {1} '{2}' because it expands the access of type '{3}' outside the assembly. - '"{0}" erweitert den Zugriff von Typ "{3}" außerhalb der Assembly und kann daher nicht von {1} "{2}" erben. + "{0}" erweitert den Zugriff von Typ "{3}" außerhalb der Assembly und kann daher nicht von {1} "{2}" erben. @@ -3213,7 +3257,7 @@ '{0}' in class '{1}' cannot override '{2}' in class '{3}' because an intermediate class '{4}' overrides '{2}' in class '{3}' but is not accessible. - '"{0}" in der {1}-Klasse kann "{2}" in der {3}-Klasse nicht überschreiben, weil "{2}" von der Zwischenklasse "{4}" in der {3}-Klasse überschrieben wird, auf die aber nicht zugegriffen werden kann. + "{0}" in der {1}-Klasse kann "{2}" in der {3}-Klasse nicht überschreiben, weil "{2}" von der Zwischenklasse "{4}" in der {3}-Klasse überschrieben wird, auf die aber nicht zugegriffen werden kann. @@ -3358,7 +3402,7 @@ '{0}' exists in multiple base interfaces. Use the name of the interface that declares '{0}' in the 'Implements' clause instead of the name of the derived interface. - '"{0}" ist in mehreren Basisschnittstellen vorhanden. Verwenden Sie in der Implements-Klausel den Namen der Schnittstelle, die "{0}" deklariert, und nicht den Namen der abgeleiteten Schnittstelle. + "{0}" ist in mehreren Basisschnittstellen vorhanden. Verwenden Sie in der Implements-Klausel den Namen der Schnittstelle, die "{0}" deklariert, und nicht den Namen der abgeleiteten Schnittstelle. @@ -3508,17 +3552,17 @@ '{0}' is obsolete. - '"{0}" ist veraltet. + "{0}" ist veraltet. '{0}' is a module and cannot be referenced as an assembly. - '"{0}" ist ein Modul und kann nicht als Assembly referenziert werden. + "{0}" ist ein Modul und kann nicht als Assembly referenziert werden. '{0}' is an assembly and cannot be referenced as a module. - '"{0}" ist eine Assembly und kann nicht als Modul referenziert werden. + "{0}" ist eine Assembly und kann nicht als Modul referenziert werden. @@ -3528,7 +3572,7 @@ '{0}' is not a local variable or parameter, and so cannot be used as a 'Catch' variable. - '"{0}" ist weder eine lokale Variable noch ein Parameter und kann daher nicht als Catch-Variable verwendet werden. + "{0}" ist weder eine lokale Variable noch ein Parameter und kann daher nicht als Catch-Variable verwendet werden. @@ -3548,7 +3592,7 @@ '{0}' cannot override '{1}' because it is not declared 'Overridable'. - '"{0}" kann "{1}" nicht überschreiben, da es nicht als "Overridable" deklariert ist. + "{0}" kann "{1}" nicht überschreiben, da es nicht als "Overridable" deklariert ist. @@ -3788,7 +3832,7 @@ '{0}' cannot refer to itself through its default instance; use 'Me' instead. - '"{0}" kann nicht durch die Standardinstanz auf sich selbst verweisen. Verwenden Sie stattdessen "Me". + "{0}" kann nicht durch die Standardinstanz auf sich selbst verweisen. Verwenden Sie stattdessen "Me". @@ -3803,7 +3847,7 @@ '{0}' cannot be applied to the 'AddHandler', 'RemoveHandler', or 'RaiseEvent' definitions. If required, apply the attribute directly to the event. - '"{0}" kann nicht auf die Definitionen AddHandler, RemoveHandler oder RaiseEvent angewendet werden. Wenden Sie das Attribut, falls erforderlich, direkt auf das Ereignis an. + "{0}" kann nicht auf die Definitionen AddHandler, RemoveHandler oder RaiseEvent angewendet werden. Wenden Sie das Attribut, falls erforderlich, direkt auf das Ereignis an. @@ -4083,7 +4127,7 @@ '{0}' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. - '"{0}" kann nicht in einen Typ umgewandelt werden, der NULL-Werte zulässt, und nicht als Datentyp eines Arrayelements, eines Felds, eines anonymen Typmembers, eines Typarguments, eines ByRef-Parameters oder einer return-Anweisung verwendet werden. + "{0}" kann nicht in einen Typ umgewandelt werden, der NULL-Werte zulässt, und nicht als Datentyp eines Arrayelements, eines Felds, eines anonymen Typmembers, eines Typarguments, eines ByRef-Parameters oder einer return-Anweisung verwendet werden. @@ -4113,7 +4157,7 @@ '{0}' cannot shadow a method declared 'MustOverride'. - '"{0}" kann kein Shadowing für eine Methode durchführen, die als "MustOverride" deklariert ist. + "{0}" kann kein Shadowing für eine Methode durchführen, die als "MustOverride" deklariert ist. @@ -4123,7 +4167,7 @@ '{0}' and '{1}' cannot be combined. - '"{0}" und "{1}" können nicht kombiniert werden. + "{0}" und "{1}" können nicht kombiniert werden. @@ -4133,7 +4177,7 @@ '{0}' must be declared 'MustInherit' because it contains methods declared 'MustOverride'. - '"{0}" muss als "MustInherit" deklariert werden, da es Methoden enthält, die als "MustOverride" deklariert sind. + "{0}" muss als "MustInherit" deklariert werden, da es Methoden enthält, die als "MustOverride" deklariert sind. @@ -4143,12 +4187,12 @@ '{0}', implicitly declared for {1} '{2}', cannot shadow a 'MustOverride' method in the base {3} '{4}'. - '"{0}", implizit für {1} "{2}" deklariert, kann kein Shadowing für eine MustOverride-Methode in Basis-{3} "{4}" durchführen. + "{0}", implizit für {1} "{2}" deklariert, kann kein Shadowing für eine MustOverride-Methode in Basis-{3} "{4}" durchführen. '{0}' cannot override '{1}' because it is not accessible in this context. - '"{0}" kann "{1}" nicht überschreiben, da in diesem Kontext nicht darauf zugegriffen werden kann. + "{0}" kann "{1}" nicht überschreiben, da in diesem Kontext nicht darauf zugegriffen werden kann. @@ -4163,12 +4207,12 @@ '{0}' conflicts with the reserved member by this name that is implicitly declared in all enums. - '"{0}" verursacht einen Konflikt mit dem gleichnamigen reservierten Member, der in allen Enumerationen explizit deklariert wurde. + "{0}" verursacht einen Konflikt mit dem gleichnamigen reservierten Member, der in allen Enumerationen explizit deklariert wurde. '{0}' is already declared in this {1}. - '"{0}" wurde bereits in dieser {1} deklariert. + "{0}" wurde bereits in dieser {1} deklariert. @@ -4188,7 +4232,7 @@ '{0}' in assembly '{1}' has been forwarded to itself and so is an unsupported type. - '"{0}" in Assembly "{1}" wurde an sich selbst weitergeleitet und ist daher ein nicht unterstützter Typ. + "{0}" in Assembly "{1}" wurde an sich selbst weitergeleitet und ist daher ein nicht unterstützter Typ. @@ -4208,7 +4252,7 @@ '{0}' is ambiguous because multiple kinds of members with this name exist in {1} '{2}'. - '"{0}" ist mehrdeutig, da in {1} "{2}" mehrere Arten von Membern mit diesem Namen vorhanden sind. + "{0}" ist mehrdeutig, da in {1} "{2}" mehrere Arten von Membern mit diesem Namen vorhanden sind. @@ -4243,7 +4287,7 @@ '{0}' cannot be declared 'Partial' because partial methods must be Subs. - '"{0}" kann nicht als "Partial" deklariert werden, da partielle Methoden untergeordnete Methoden sein müssen. + "{0}" kann nicht als "Partial" deklariert werden, da partielle Methoden untergeordnete Methoden sein müssen. @@ -4298,17 +4342,17 @@ '{0}' cannot be used as an attribute because it is not a class. - '"{0}" kann nicht als Attribut verwendet werden, da es keine Klasse ist. + "{0}" kann nicht als Attribut verwendet werden, da es keine Klasse ist. '{0}' cannot be used as an attribute because it does not inherit from 'System.Attribute'. - '"{0}" kann nicht als Attribut verwendet werden, da es nicht von "System.Attribute" erbt. + "{0}" kann nicht als Attribut verwendet werden, da es nicht von "System.Attribute" erbt. '{0}' cannot be used as an attribute because it is declared 'MustInherit'. - '"{0}" kann nicht als Attribut verwendet werden, da es als "MustInherit" deklariert ist. + "{0}" kann nicht als Attribut verwendet werden, da es als "MustInherit" deklariert ist. @@ -4408,7 +4452,7 @@ '{0}' is not valid within a Module. - '"{0}" ist innerhalb eines Moduls ungültig. + "{0}" ist innerhalb eines Moduls ungültig. @@ -4438,7 +4482,7 @@ '{0}' cannot be named as a parameter in an attribute specifier because it is not a field or property. - '"{0}" kann nicht als Parameter in einem Attributspezifizierer verwendet werden, da es kein Feld bzw. keine Eigenschaft ist. + "{0}" kann nicht als Parameter in einem Attributspezifizierer verwendet werden, da es kein Feld bzw. keine Eigenschaft ist. @@ -4458,7 +4502,7 @@ '{0}' has no parameters and its return type cannot be indexed. - '"{0}" hat keine Parameter, und der Rückgabetyp kann nicht indiziert werden. + "{0}" hat keine Parameter, und der Rückgabetyp kann nicht indiziert werden. @@ -4483,7 +4527,7 @@ '{0}' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event. - '"{0}" ist ein Ereignis und kann nicht direkt aufgerufen werden. Verwenden Sie eine RaiseEvent-Anweisung, um ein Ereignis aufzurufen. + "{0}" ist ein Ereignis und kann nicht direkt aufgerufen werden. Verwenden Sie eine RaiseEvent-Anweisung, um ein Ereignis aufzurufen. @@ -4568,7 +4612,7 @@ '{0}' has no type parameters and so cannot have type arguments. - '"{0}" hat keine Typparameter und kann daher keine Typargumente haben. + "{0}" hat keine Typparameter und kann daher keine Typargumente haben. @@ -4608,7 +4652,7 @@ '{0}' has the same name as a type parameter. - '"{0}" hat den gleichen Namen wie ein Typparameter. + "{0}" hat den gleichen Namen wie ein Typparameter. @@ -4633,7 +4677,7 @@ '{0}' cannot be used as a type constraint. - '"{0}" kann nicht als Typeinschränkung verwendet werden. + "{0}" kann nicht als Typeinschränkung verwendet werden. @@ -4688,12 +4732,12 @@ '{0}' cannot override '{1}' because they differ by type parameter constraints. - '"{0}" kann "{1}" nicht überschreiben, da sie unterschiedliche Typparametereinschränkungen aufweisen. + "{0}" kann "{1}" nicht überschreiben, da sie unterschiedliche Typparametereinschränkungen aufweisen. '{0}' cannot implement '{1}.{2}' because they differ by type parameter constraints. - '"{0}" kann "{1}.{2}" nicht implementieren, da sie unterschiedliche Einschränkungen für Typparameter aufweisen. + "{0}" kann "{1}.{2}" nicht implementieren, da sie unterschiedliche Einschränkungen für Typparameter aufweisen. @@ -4748,7 +4792,7 @@ '{0}' is already declared as a type parameter of this method. - '"{0}" ist bereits als Typparameter dieser Methode deklariert. + "{0}" ist bereits als Typparameter dieser Methode deklariert. @@ -4935,7 +4979,7 @@ '{0}' cannot be declared 'Shadows' outside of a class, structure, or interface. - '"{0}" kann nicht außerhalb einer Klasse, einer Struktur oder einer Schnittstelle als "Shadows" deklariert werden. + "{0}" kann nicht außerhalb einer Klasse, einer Struktur oder einer Schnittstelle als "Shadows" deklariert werden. @@ -4970,7 +5014,7 @@ '{0}' cannot be applied because the format of the GUID '{1}' is not correct. - '"{0}" kann nicht angewendet werden, da das Format von GUID "{1}" falsch ist. + "{0}" kann nicht angewendet werden, da das Format von GUID "{1}" falsch ist. @@ -5340,7 +5384,7 @@ '{0}' has the same name as a member used for type '{1}' exposed in a 'My' group. Rename the type or its enclosing namespace. - '"{0}" hat den gleichen Namen wie ein Member, der für den in einer My-Gruppe verfügbar gemachter Typ "{1}" verwendet wird. Benennen Sie den Typ oder den einschließenden Namespace um. + "{0}" hat den gleichen Namen wie ein Member, der für den in einer My-Gruppe verfügbar gemachter Typ "{1}" verwendet wird. Benennen Sie den Typ oder den einschließenden Namespace um. @@ -5440,7 +5484,7 @@ '{0}' is not a member of '{1}'; it does not exist in the current context. - '"{0}" ist kein Member von "{1}" und ist im aktuellen Kontext nicht vorhanden. + "{0}" ist kein Member von "{1}" und ist im aktuellen Kontext nicht vorhanden. @@ -5512,7 +5556,7 @@ '{0}' is not a method parameter. - '"{0}" ist kein Methodenparameter. + "{0}" ist kein Methodenparameter. @@ -5564,7 +5608,7 @@ '{0}' is not a parameter of extension method '{1}' defined in '{2}'. - '"{0}" ist kein Parameter der in "{2}" definierten Erweiterungsmethode "{1}". + "{0}" ist kein Parameter der in "{2}" definierten Erweiterungsmethode "{1}". @@ -5609,7 +5653,7 @@ '{0}{1}' is not valid because '{2}' is inside a scope that defines a variable that is used in a lambda or query expression. - '"{0}{1}" ist ungültig, weil sich "{2}" in einem Bereich befindet, der eine Variable definiert, die in einem Lambdaausdruck oder einem Abfrageausdruck verwendet wird. + "{0}{1}" ist ungültig, weil sich "{2}" in einem Bereich befindet, der eine Variable definiert, die in einem Lambdaausdruck oder einem Abfrageausdruck verwendet wird. @@ -5986,7 +6030,7 @@ '{0}' is obsolete: '{1}'. - '"{0}" ist veraltet: "{1}". + "{0}" ist veraltet: "{1}". @@ -6036,7 +6080,7 @@ '{0}' is obsolete. - '"{0}" ist veraltet. + "{0}" ist veraltet. @@ -6136,7 +6180,7 @@ '{0}' is not CLS-compliant because it derives from '{1}', which is not CLS-compliant. - '"{0}" wird von "{1}" (nicht CLS-kompatibel) abgeleitet und ist daher nicht CLS-kompatibel. + "{0}" wird von "{1}" (nicht CLS-kompatibel) abgeleitet und ist daher nicht CLS-kompatibel. @@ -6166,7 +6210,7 @@ '{0}' is not CLS-compliant because the interface '{1}' it inherits from is not CLS-compliant. - '"{0}" ist nicht CLS-kompatibel, da die {1}-Schnittstelle, von der geerbt wird, nicht CLS-kompatibel ist. + "{0}" ist nicht CLS-kompatibel, da die {1}-Schnittstelle, von der geerbt wird, nicht CLS-kompatibel ist. @@ -6226,7 +6270,7 @@ '{0}' is not CLS-compliant because it overloads '{1}' which differs from it only by array of array parameter types or by the rank of the array parameter types. - '"{0}" überlädt "{1}", unterscheidet sich jedoch nur durch Array-von-Array-Parametertypen oder durch den Rang der Arrayparametertypen davon und ist daher nicht CLS-kompatibel. + "{0}" überlädt "{1}", unterscheidet sich jedoch nur durch Array-von-Array-Parametertypen oder durch den Rang der Arrayparametertypen davon und ist daher nicht CLS-kompatibel. @@ -6366,7 +6410,7 @@ '{0}' in designer-generated type '{1}' should call InitializeComponent method. - '"{0}" im vom Designer generierten Typ "{1}" sollte die InitializeComponent-Methode aufrufen. + "{0}" im vom Designer generierten Typ "{1}" sollte die InitializeComponent-Methode aufrufen. @@ -6816,7 +6860,7 @@ '{0}' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement. - '"{0}" kann nicht für COM als Let-Eigenschaft verfügbar gemacht werden. Sie können dieser Eigenschaft mit der Let-Anweisung keine Werte (z. B. Zahlen oder Zeichenfolgen) aus Visual Basic 6.0 zuweisen, die keine Objekte sind. + "{0}" kann nicht für COM als Let-Eigenschaft verfügbar gemacht werden. Sie können dieser Eigenschaft mit der Let-Anweisung keine Werte (z. B. Zahlen oder Zeichenfolgen) aus Visual Basic 6.0 zuweisen, die keine Objekte sind. @@ -7361,7 +7405,7 @@ '{0}' cannot expose type '{1}' in {2} '{3}' through {4} '{5}'. - '"{0}" kann Typ "{1}" in {2} "{3}" nicht durch {4} "{5}" verfügbar machen. + "{0}" kann Typ "{1}" in {2} "{3}" nicht durch {4} "{5}" verfügbar machen. @@ -7371,7 +7415,7 @@ '{0}' cannot be implemented by a {1} property. - '"{0}" kann nicht von einer {1}-Eigenschaft implementiert werden. + "{0}" kann nicht von einer {1}-Eigenschaft implementiert werden. @@ -7663,12 +7707,12 @@ '{0}' cannot be converted to '{1}'. Consider using '{2}' instead. - '"{0}" kann nicht in "{1}" konvertiert werden. Verwenden Sie stattdessen "{2}". + "{0}" kann nicht in "{1}" konvertiert werden. Verwenden Sie stattdessen "{2}". '{0}' cannot be converted to '{1}'. Consider using '{2}' instead. - '"{0}" kann nicht in "{1}" konvertiert werden. Verwenden Sie stattdessen "{2}". + "{0}" kann nicht in "{1}" konvertiert werden. Verwenden Sie stattdessen "{2}". @@ -7678,12 +7722,12 @@ '{4}' cannot be converted to '{5}' because '{0}' is not derived from '{1}', as required for the 'In' generic parameter '{2}' in '{3}'. - '"{4}" kann nicht in "{5}" konvertiert werden, weil "{0}" nicht von "{1}" abgeleitet wird, wie dies für den generischen In-Parameter "{2}" in "{3}" erforderlich ist. + "{4}" kann nicht in "{5}" konvertiert werden, weil "{0}" nicht von "{1}" abgeleitet wird, wie dies für den generischen In-Parameter "{2}" in "{3}" erforderlich ist. '{4}' cannot be converted to '{5}' because '{0}' is not derived from '{1}', as required for the 'Out' generic parameter '{2}' in '{3}'. - '"{4}" kann nicht in "{5}" konvertiert werden, weil "{0}" nicht von "{1}" abgeleitet wird, wie dies für den generischen Out-Parameter "{2}" in "{3}" erforderlich ist. + "{4}" kann nicht in "{5}" konvertiert werden, weil "{0}" nicht von "{1}" abgeleitet wird, wie dies für den generischen Out-Parameter "{2}" in "{3}" erforderlich ist. @@ -7708,17 +7752,17 @@ '{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an In type parameter, 'In {2}'. - '"{0}" kann nicht in "{1}" konvertiert werden. Ändern Sie "{2}" in der Definition von "{3}" ggf. in einen Parameter vom Typ "In" (In {2}). + "{0}" kann nicht in "{1}" konvertiert werden. Ändern Sie "{2}" in der Definition von "{3}" ggf. in einen Parameter vom Typ "In" (In {2}). '{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an Out type parameter, 'Out {2}'. - '"{0}" kann nicht in "{1}" konvertiert werden. Ändern Sie "{2}" in der Definition von "{3}" ggf. in einen Parameter vom Typ "Out" (Out {2}). + "{0}" kann nicht in "{1}" konvertiert werden. Ändern Sie "{2}" in der Definition von "{3}" ggf. in einen Parameter vom Typ "Out" (Out {2}). '{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an In type parameter, 'In {2}'. - '"{0}" kann nicht in "{1}" konvertiert werden. Ändern Sie "{2}" in der Definition von "{3}" ggf. in einen Parameter vom Typ "In" (In {2}). + "{0}" kann nicht in "{1}" konvertiert werden. Ändern Sie "{2}" in der Definition von "{3}" ggf. in einen Parameter vom Typ "In" (In {2}). @@ -7728,7 +7772,7 @@ '{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an Out type parameter, 'Out {2}'. - '"{0}" kann nicht in "{1}" konvertiert werden. Ändern Sie "{2}" in der Definition von "{3}" ggf. in einen Parameter vom Typ "Out" (Out {2}). + "{0}" kann nicht in "{1}" konvertiert werden. Ändern Sie "{2}" in der Definition von "{3}" ggf. in einen Parameter vom Typ "Out" (Out {2}). @@ -7998,7 +8042,7 @@ '{0}' does not implement '{1}'. - '"{0}" implementiert "{1}" nicht. + "{0}" implementiert "{1}" nicht. @@ -8038,7 +8082,7 @@ '{0}' does not return a Task and cannot be awaited. Consider changing it to an Async Function. - '"{0}" gibt keine Aufgabe zurück und kann nicht abgewartet werden. Erwägen Sie eine Änderung in eine Async-Funktion. + "{0}" gibt keine Aufgabe zurück und kann nicht abgewartet werden. Erwägen Sie eine Änderung in eine Async-Funktion. @@ -8093,7 +8137,7 @@ '{0}' cannot be used as a parameter type for an Iterator or Async method. - '"{0}" kann nicht als Parametertyp einer Iterator- oder Async-Methode verwendet werden. + "{0}" kann nicht als Parametertyp einer Iterator- oder Async-Methode verwendet werden. @@ -8103,7 +8147,7 @@ '{0}' cannot be declared 'Partial' because it has the 'Async' modifier. - '"{0}" kann nicht als "Partial" deklariert werden, da es über den Async-Modifizierer verfügt. + "{0}" kann nicht als "Partial" deklariert werden, da es über den Async-Modifizierer verfügt. @@ -8218,12 +8262,12 @@ '{0}.{1}' from 'implements {2}' is already implemented by the base class '{3}'. Re-implementation of Windows Runtime Interface '{4}' is not allowed - '"{0}.{1}" von "implements {2}" wird bereits durch die Basisklasse "{3}" implementiert. Die erneute Implementierung der Windows-Runtime-Schnittstelle "{4}" ist unzulässig. + "{0}.{1}" von "implements {2}" wird bereits durch die Basisklasse "{3}" implementiert. Die erneute Implementierung der Windows-Runtime-Schnittstelle "{4}" ist unzulässig. '{0}.{1}' is already implemented by the base class '{2}'. Re-implementation of Windows Runtime Interface '{3}' is not allowed - '"{0}.{1}" wird bereits durch die Basisklasse "{2}" implementiert. Die erneute Implementierung der Windows-Runtime-Schnittstelle "{3}" ist unzulässig. + "{0}.{1}" wird bereits durch die Basisklasse "{2}" implementiert. Die erneute Implementierung der Windows-Runtime-Schnittstelle "{3}" ist unzulässig. @@ -8448,12 +8492,12 @@ '{0}' is an unsupported .NET module. - '"{0}" ist ein .NET-Modul, das nicht unterstützt wird. + "{0}" ist ein .NET-Modul, das nicht unterstützt wird. '{0}' is an unsupported event. - '"{0}" ist ein Ereignis, das nicht unterstützt wird. + "{0}" ist ein Ereignis, das nicht unterstützt wird. @@ -8718,7 +8762,7 @@ '{0}' is not a valid format specifier - '"{0}" ist kein gültiger Formatbezeichner. + "{0}" ist kein gültiger Formatbezeichner. @@ -8733,7 +8777,7 @@ '{0}' cannot be made nullable. - '"{0}" kann keine NULL-Werte zulassen. + "{0}" kann keine NULL-Werte zulassen. @@ -9103,7 +9147,7 @@ '{0}' is for evaluation purposes only and is subject to change or removal in future updates. - '"{0}" dient nur zu Testzwecken und kann in zukünftigen Aktualisierungen geändert oder entfernt werden. + "{0}" dient nur zu Testzwecken und kann in zukünftigen Aktualisierungen geändert oder entfernt werden. diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.es.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.es.xlf index a54305325761d..65cccf48c5e75 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.es.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.es.xlf @@ -212,169 +212,169 @@ -vbruntime:<file> Compile with the alternate Visual Basic runtime in <file>. - Visual Basic Compiler Options + Opciones del compilador de Visual Basic - - OUTPUT FILE - --out:<file> Specifies the output file name. --target:exe Create a console application (default). - (Short form: -t) --target:winexe Create a Windows application. --target:library Create a library assembly. --target:module Create a module that can be added to an - assembly. --target:appcontainerexe Create a Windows application that runs in - AppContainer. --target:winmdobj Create a Windows Metadata intermediate file --doc[+|-] Generates XML documentation file. --doc:<file> Generates XML documentation file to <file>. --refout:<file> Reference assembly output to generate + - ARCHIVO DE SALIDA - +-out:<archivo> Especifica el nombre del archivo de salida. +-target:exe Crea una aplicación de consola (predeterminado). + (Forma corta: -t) +-target:winexe Crea una aplicación de Windows. +-target:library Crea un ensamblado de biblioteca. +-target:module Crea un módulo que se puede agregar a un + ensamblado. +-target:appcontainerexe Crea una aplicación de Windows que se ejecuta en + AppContainer +-target:winmdobj Crea un archivo intermedio de metadatos de Windows. +-doc[+|-] Genera un archivo de documentación XML. +-doc:<archivo> Genera un archivo de documentación XML en <archivo>. +-refout:<archivo> Salida del ensamblado de referencia para generar - - INPUT FILES - --addmodule:<file_list> Reference metadata from the specified modules --link:<file_list> Embed metadata from the specified interop - assembly. (Short form: -l) --recurse:<wildcard> Include all files in the current directory - and subdirectories according to the - wildcard specifications. --reference:<file_list> Reference metadata from the specified - assembly. (Short form: -r) --analyzer:<file_list> Run the analyzers from this assembly - (Short form: -a) --additionalfile:<file list> Additional files that don't directly affect code - generation but may be used by analyzers for producing - errors or warnings. + - ARCHIVOS DE ENTRADA - +-addmodule:<lista_archivos> Hace referencia a metadatos desde los módulos especificados +-link:<lista_archivos> Inserta metadatos desde el ensamblado de interoperabilidad + especificado. (Forma corta: -l) +-recurse:<carácter comodín> Incluye todos los archivos en el directorio y los + subdirectorios actuales según las + especificaciones del carácter comodín. +-reference:<lista_archivos> Hace referencia a los metadatos desde el ensamblado + especificado. (Forma corta: -r) +-analyzer:<lista_archivos> Ejecuta los analizadores desde este ensamblado + (Forma corta: -a) +-additionalfile:<lista_archivos> Archivos adicionales que no afectan directamente a la + generación de código, pero que los analizadores pueden usar para producir + errores o advertencias. - - RESOURCES - --linkresource:<resinfo> Links the specified file as an external - assembly resource. - resinfo:<file>[,<name>[,public|private]] - (Short form: -linkres) --nowin32manifest The default manifest should not be embedded - in the manifest section of the output PE. --resource:<resinfo> Adds the specified file as an embedded - assembly resource. - resinfo:<file>[,<name>[,public|private]] - (Short form: -res) --win32icon:<file> Specifies a Win32 icon file (.ico) for the - default Win32 resources. --win32manifest:<file> The provided file is embedded in the manifest - section of the output PE. --win32resource:<file> Specifies a Win32 resource file (.res). + - RECURSOS - +-linkresource:<info recurso> Vincula el archivo especificado como un recurso + de ensamblado externo. + resinfo:<archivo>[,<nombre>[,public|private]] + (Forma corta: -linkres) +-nowin32manifest El manifiesto predeterminado no debe estar insertado + en la sección del manifiesto del PE de salida. +-resource:<info recurso> Agrega el archivo especificado como un recurso + de ensamblado insertado. + resinfo:<archivo>[,<nombre>[,public|private]] + (Forma corta: -res) +-win32icon:<archivo> Especifica un archivo de icono Win32 (.ico) para los + recursos Win32 predeterminados. +-win32manifest:<archivo> El archivo proporcionado está insertado en la sección + del manifiesto del PE de salida. +-win32resource:<archivo> Especifica un archivo de recurso Win32 (.res) . - - CODE GENERATION - --optimize[+|-] Enable optimizations. --removeintchecks[+|-] Remove integer checks. Default off. --debug[+|-] Emit debugging information. --debug:full Emit full debugging information (default). --debug:pdbonly Emit full debugging information. --debug:portable Emit cross-platform debugging information. --debug:embedded Emit cross-platform debugging information into - the target .dll or .exe. --deterministic Produce a deterministic assembly - (including module version GUID and timestamp) --refonly Produce a reference assembly in place of the main output --instrument:TestCoverage Produce an assembly instrumented to collect - coverage information --sourcelink:<file> Source link info to embed into PDB. + - GENERACIÓN DE CÓDIGO - +-optimize[+|-] Habilita las optimizaciones. +-removeintchecks[+|-] Quita las comprobaciones de enteros. Desactivado de forma predeterminada. +-debug[+|-] Emite información de depuración. +-debug:full Emite información de depuración completa (valor predeterminado). +-debug:pdbonly Emite información de depuración completa. +-debug:portable Emite información de depuración multiplataforma. +-debug:embedded Emite información de depuración multiplataforma en el + archivo .dll o .exe de destino. +-deterministic Produce un ensamblado determinista + (que incluye el GUID de la versión y la marca de tiempo del módulo) +-refonly Produce un ensamblado de referencia en lugar de la salida principal +-instrument:TestCoverage Produce un ensamblado instrumentado para recopilar + la información de cobertura +-sourcelink:<archivo> Información del vínculo de origen para insertar en el PDB. - - ERRORS AND WARNINGS - --nowarn Disable all warnings. --nowarn:<number_list> Disable a list of individual warnings. --warnaserror[+|-] Treat all warnings as errors. --warnaserror[+|-]:<number_list> Treat a list of warnings as errors. --ruleset:<file> Specify a ruleset file that disables specific - diagnostics. --errorlog:<file>[,version=<sarif_version>] - Specify a file to log all compiler and analyzer - diagnostics in SARIF format. - sarif_version:{1|2|2.1} Default is 1. 2 and 2.1 - both mean SARIF version 2.1.0. --reportanalyzer Report additional analyzer information, such as - execution time. --skipanalyzers[+|-] Skip execution of diagnostic analyzers. + - ERRORES Y ADVERTENCIAS - +-nowarn Deshabilita todas las advertencias. +-nowarn:<lista_números> Deshabilita una lista de advertencias individuales. +-warnaserror[+|-] Trata todas las advertencias como errores. +-warnaserror[+|-]:<lista_números> Trata una lista de advertencias como errores. +-ruleset:<archivo> Especifica un archivo de conjunto de reglas que deshabilita diagnósticos + específicos. +-errorlog:<archivo>[,version=<versión_de_sarif>] + Especifica un archivo para registrar todos los diagnósticos del + compilador y del analizador en formato SARIF. + versión_de_sarif:{1|2|2.1} El valor predeterminado es 1. 2 y 2.1, + ambos significan SARIF versión 2.1.0. +-reportanalyzer Notifica información adicional del analizador, como + el tiempo de ejecución. +-skipanalyzers[+|-] Omite la ejecución de los analizadores de diagnóstico. - - LANGUAGE - --define:<symbol_list> Declare global conditional compilation - symbol(s). symbol_list:name=value,... - (Short form: -d) --imports:<import_list> Declare global Imports for namespaces in - referenced metadata files. - import_list:namespace,... --langversion:? Display the allowed values for language version --langversion:<string> Specify language version such as - `default` (latest major version), or - `latest` (latest version, including minor versions), - or specific versions like `14` or `15.3` --optionexplicit[+|-] Require explicit declaration of variables. --optioninfer[+|-] Allow type inference of variables. --rootnamespace:<string> Specifies the root Namespace for all type - declarations. --optionstrict[+|-] Enforce strict language semantics. --optionstrict:custom Warn when strict language semantics are not - respected. --optioncompare:binary Specifies binary-style string comparisons. - This is the default. --optioncompare:text Specifies text-style string comparisons. + - LENGUAJE - +-define:<lista_símbolos> Declara símbolos de compilación condicional + global. lista_símbolos:name=value,... + (Forma corta: -d) +-imports:<lista_importaciones> Declara las importaciones globales para los espacios de nombres de + los archivos de metadatos a los que se hace referencia. + lista_importaciones:namespace,... +-langversion:? Muestra los valores permitidos para la versión del lenguaje +-langversion:<cadena> Especifica una versión del lenguaje, como + “predeterminada” (versión principal más reciente) o + “última” (última versión, incluidas las versiones secundarias) + o versiones específicas, como “14” o “15.3” +-optionexplicit[+|-] Requiere la declaración explícita de las variables. +-optioninfer[+|-] Permite la inferencia de tipos de variables. +-rootnamespace:<cadena> Especifica el espacio de nombres raíz para todas las declaraciones + de tipos. +-optionstrict[+|-] Exige semántica de lenguaje estricta. +-optionstrict:custom Advierte cuando no se respeta la semántica del lenguaje + estricta. +-optioncompare:binary Especifica comparaciones de cadenas de estilo binario. + Es el valor predeterminado. +-optioncompare:text Especifica comparaciones de cadenas de estilo de texto. - - MISCELLANEOUS - --help Display this usage message. (Short form: -?) --noconfig Do not auto-include VBC.RSP file. --nologo Do not display compiler copyright banner. --quiet Quiet output mode. --verbose Display verbose messages. --parallel[+|-] Concurrent build. --version Display the compiler version number and exit. + - VARIOS - +-help Muestra este mensaje de uso. (Forma corta: -?) +-noconfig No incluir automáticamente el archivo VBC.RSP. +-nologo No mostrar pancarta de copyright del compilador. +-quiet Modo de salida silencioso. +-verbose Mostrar mensajes detallados. +-parallel[+|-] Compilación simultánea. +-version Mostrar el número de versión del compilador y salir. - - ADVANCED - --baseaddress:<number> The base address for a library or module + - AVANZADO - +-baseaddress:<número> Dirección base de una biblioteca o módulo (hex). --checksumalgorithm:<alg> Specify algorithm for calculating source file - checksum stored in PDB. Supported values are: - SHA1 or SHA256 (default). --codepage:<number> Specifies the codepage to use when opening - source files. --delaysign[+|-] Delay-sign the assembly using only the public - portion of the strong name key. --publicsign[+|-] Public-sign the assembly using only the public - portion of the strong name key. --errorreport:<string> Specifies how to handle internal compiler - errors; must be prompt, send, none, or queue - (default). --filealign:<number> Specify the alignment used for output file - sections. --highentropyva[+|-] Enable high-entropy ASLR. --keycontainer:<string> Specifies a strong name key container. --keyfile:<file> Specifies a strong name key file. --libpath:<path_list> List of directories to search for metadata - references. (Semi-colon delimited.) --main:<class> Specifies the Class or Module that contains - Sub Main. It can also be a Class that - inherits from System.Windows.Forms.Form. - (Short form: -m) --moduleassemblyname:<string> Name of the assembly which this module will - be a part of. --netcf Target the .NET Compact Framework. --nostdlib Do not reference standard libraries - (system.dll and VBC.RSP file). +-checksumalgorithm:<algoritmo> Especifica el algoritmo para calcular la suma de comprobación + del archivo de origen almacenado en PDB. Los valores admitidos son: + SHA1 o SHA256 (predeterminado). +-codepage:<número> Especifica la página de códigos que se va a usar al abrir + los archivos de código fuente. +-delaysign[+|-] Retrasa la firma del ensamblado con solo la parte pública + de la clave de nombre seguro. +-publicsign[+|-] Publica la firma del ensamblado con solo la parte pública + de la clave de nombre seguro. +-errorreport:<cadena> Especifica cómo tratar los errores internos del + compilador: avisar, enviar, ninguno o poner en cola + (predeterminado). +-filealign:<número> Especifica la alineación que se usa para las secciones del archivo de + salida. +-highentropyva[+|-] Habilita ASLR de alta entropía. +-keycontainer:<cadena> Especifica un contenedor de claves de nombre seguro. +-keyfile:<archivo> Especifica un archivo de claves de nombre seguro. +-libpath:<lista_rutas> Lista de directorios para buscar referencias de + metadatos. (Delimitada por punto y coma). +-main:<clase> Especifica la clase o el módulo que contiene + Sub Main. También puede ser una clase que + herede de System.Windows.Forms.Form. + (Forma corta: -m) +-moduleassemblyname:<cadena> Nombre del ensamblado del que este módulo + formará parte. +-netcf Destino de .NET Compact Framework. +-nostdlib No hacer referencia a las bibliotecas estándar + (archivo system.dll y VBC.RSP). -pathmap:<K1>=<V1>,<K2>=<V2>,... - Specify a mapping for source path names output by - the compiler. --platform:<string> Limit which platforms this code can run on; - must be x86, x64, Itanium, arm, arm64 - AnyCPU32BitPreferred or anycpu (default). --preferreduilang Specify the preferred output language name. --nosdkpath Disable searching the default SDK path for standard library assemblies. --sdkpath:<path> Location of the .NET Framework SDK directory + Especifica una asignación para los nombres de ruta de acceso de origen + producidos por el compilador. +-platform:<cadena> Limita en qué plataformas se puede ejecutar este código. + Debe ser x86, x64, Itanium, arm, arm64, + AnyCPU32BitPreferred o anycpu (valor predeterminado). +-preferreduilang Especifica el nombre del lenguaje de salida preferido. +-nosdkpath Deshabilita la búsqueda de la ruta de acceso del SDK predeterminado para ensamblados de biblioteca estándar. +-sdkpath:<ruta de acceso> Ubicación del directorio de .NET Framework SDK (mscorlib.dll). --subsystemversion:<version> Specify subsystem version of the output PE. - version:<number>[.<number>] --utf8output[+|-] Emit compiler output in UTF8 character - encoding. -@<file> Insert command-line settings from a text file --vbruntime[+|-|*] Compile with/without the default Visual Basic - runtime. --vbruntime:<file> Compile with the alternate Visual Basic - runtime in <file>. +-subsystemversion:<versión> Especifica la versión del subsistema del PE de salida. + version:<número>[.<número>] +-utf8output[+|-] Emite la salida del compilador en codificación de caracteres + UTF8. +@<archivo> Inserta la configuración de línea de comandos desde un archivo de texto +-vbruntime[+|-|*] Compila con o sin el entorno de ejecución predeterminado de + Visual Basic. +-vbruntime:<archivo> Compila con el entorno de ejecución alternativo de + Visual Basic en <archivo>. @@ -463,6 +463,50 @@ El argumento de tipo no puede ser Nothing + + The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + El ensamblado "{0}" que contiene el tipo "{1}" hace referencia a .NET Framework, lo cual no se admite. + {1} is the type that was loaded, {0} is the containing assembly. + + + The loaded assembly references .NET Framework, which is not supported. + El ensamblado que se ha cargado hace referencia a .NET Framework, lo cual no se admite. + + + + Generator '{0}' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + Error del generador "{0}" al crear código fuente. No contribuirá a la salida y pueden producirse errores de compilación como resultado. Se produjo la excepción de tipo "{1}" con el mensaje "{2}" + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + El generador produjo la excepción siguiente: +"{0}". + {0} is the string representation of the exception that was thrown. + + + Generator failed to generate source. + Error del generador al crear código fuente. + + + + Generator '{0}' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + Error de inicialización del generador "{0}". No contribuirá a la salida y pueden producirse errores de compilación como resultado. Se produjo la excepción de tipo "{1}" con el mensaje "{2}" + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + El generador produjo la excepción siguiente: +"{0}". + {0} is the string representation of the exception that was thrown. + + + Generator failed to initialize. + Error de inicialización del generador. + + Wrong number of type arguments Número de argumentos de tipo incorrecto @@ -2922,7 +2966,7 @@ No accessible '{0}' is most specific: {1} - {0}' al que no se puede obtener acceso es más específico: {1} + '{0}' al que no se puede obtener acceso es más específico: {1} @@ -7428,12 +7472,12 @@ Friend access was granted by '{0}', but the public key of the output assembly does not match that specified by the attribute in the granting assembly. - {0}' ha concedido acceso de confianza, pero la clave pública del ensamblado de salida no coincide con la especificada por el atributo en el ensamblado de concesión. + '{0}' ha concedido acceso de confianza, pero la clave pública del ensamblado de salida no coincide con la especificada por el atributo en el ensamblado de concesión. Friend access was granted by '{0}', but the strong name signing state of the output assembly does not match that of the granting assembly. - {0}' ha concedido acceso de confianza, pero el nombre seguro que firma el estado del ensamblado de salida no coincide con el del ensamblado de concesión. + '{0}' ha concedido acceso de confianza, pero el nombre seguro que firma el estado del ensamblado de salida no coincide con el del ensamblado de concesión. @@ -9103,7 +9147,7 @@ '{0}' is for evaluation purposes only and is subject to change or removal in future updates. - '"{0}" se incluye con fines de evaluación y está sujeto a cambios o a que se elimine en próximas actualizaciones. + "{0}" se incluye con fines de evaluación y está sujeto a cambios o a que se elimine en próximas actualizaciones. diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.fr.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.fr.xlf index bbb265ea4e746..537566ac37b2e 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.fr.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.fr.xlf @@ -212,169 +212,169 @@ -vbruntime:<file> Compile with the alternate Visual Basic runtime in <file>. - Visual Basic Compiler Options + Options du compilateur Visual Basic - - OUTPUT FILE - --out:<file> Specifies the output file name. --target:exe Create a console application (default). - (Short form: -t) --target:winexe Create a Windows application. --target:library Create a library assembly. --target:module Create a module that can be added to an + - FICHIER DE SORTIE - +-out:<fichier> Spécifie le nom du fichier de sortie. +-target:exe Créer une application console (par défaut). + (Forme abrégée : -t) +-target:winexe Créer une application Windows. +-target:library Créer un assembly de bibliothèque. +-target:module Créer un module qui peut être ajouté à un assembly. --target:appcontainerexe Create a Windows application that runs in +-target:appcontainerexe Créer une application Windows qui s'exécute dans AppContainer. --target:winmdobj Create a Windows Metadata intermediate file --doc[+|-] Generates XML documentation file. --doc:<file> Generates XML documentation file to <file>. --refout:<file> Reference assembly output to generate +-target:winmdobj Créer un fichier intermédiaire de métadonnées Windows +-doc[+|-] Génère un fichier de documentation XML. +-doc:<fichier> Génère un fichier de documentation XML dans <fichier>. +-refout:<fichier> Sortie de l'assembly de référence à générer - - INPUT FILES - --addmodule:<file_list> Reference metadata from the specified modules --link:<file_list> Embed metadata from the specified interop - assembly. (Short form: -l) --recurse:<wildcard> Include all files in the current directory - and subdirectories according to the - wildcard specifications. --reference:<file_list> Reference metadata from the specified - assembly. (Short form: -r) --analyzer:<file_list> Run the analyzers from this assembly - (Short form: -a) --additionalfile:<file list> Additional files that don't directly affect code - generation but may be used by analyzers for producing - errors or warnings. + - FICHIERS D'ENTRÉE - +-addmodule:<liste_fichiers> Référencer les métadonnées à partir des modules spécifiés +-link:<liste_fichiers> Incorporer les métadonnées à partir de + l'assembly d'interopérabilité spécifié. (Forme abrégée : -l) +-recurse:<générique> Inclure tous les fichiers dans le répertoire + et les sous-répertoires actifs en fonction des + spécifications des caractères génériques. +-reference:<liste_fichiers> Référencer les métadonnées à partir de + l'assembly spécifié. (Forme abrégée : -r) +-analyzer:<liste_fichiers> Exécuter les analyseurs à partir de cet assembly + (Forme abrégée : -a) +-additionalfile:<liste_fichiers> Fichiers supplémentaires qui n'affectent pas directement + la génération de code mais qui peuvent être utilisés par les analyseurs pour produire + des erreurs ou des avertissements. - - RESOURCES - --linkresource:<resinfo> Links the specified file as an external - assembly resource. - resinfo:<file>[,<name>[,public|private]] - (Short form: -linkres) --nowin32manifest The default manifest should not be embedded - in the manifest section of the output PE. --resource:<resinfo> Adds the specified file as an embedded - assembly resource. - resinfo:<file>[,<name>[,public|private]] - (Short form: -res) --win32icon:<file> Specifies a Win32 icon file (.ico) for the - default Win32 resources. --win32manifest:<file> The provided file is embedded in the manifest - section of the output PE. --win32resource:<file> Specifies a Win32 resource file (.res). + - RESSOURCES - +-linkresource:<resinfo> Lie le fichier spécifié sous forme de + ressource d'assembly externe. + resinfo:<fichier>[,<nom>[,public|private]] + (Forme abrégée : -linkres) +-nowin32manifest Le manifeste par défaut ne doit pas être incorporé + dans la section manifest du PE de sortie. +-resource:<resinfo> Ajoute le fichier spécifié en tant que + ressource d'assembly incorporée. + resinfo:<fichier>[,<nom>[,public|private]] + (Forme abrégée : -res) +-win32icon:<fichier> Spécifie un fichier icône Win32 (.ico) pour les + ressources Win32 par défaut. +-win32manifest:<fichier> Le fichier fourni est incorporé dans la section manifest + du PE de sortie. +-win32resource:<fichier> Spécifie un fichier de ressources Win32 (.res). - - CODE GENERATION - --optimize[+|-] Enable optimizations. --removeintchecks[+|-] Remove integer checks. Default off. --debug[+|-] Emit debugging information. --debug:full Emit full debugging information (default). --debug:pdbonly Emit full debugging information. --debug:portable Emit cross-platform debugging information. --debug:embedded Emit cross-platform debugging information into - the target .dll or .exe. --deterministic Produce a deterministic assembly - (including module version GUID and timestamp) --refonly Produce a reference assembly in place of the main output --instrument:TestCoverage Produce an assembly instrumented to collect - coverage information --sourcelink:<file> Source link info to embed into PDB. + - GÉNÉRATION DE CODE - +-optimize[+|-] Activer les optimisations. +-removeintchecks[+|-] Supprimer les contrôles sur les entiers. La valeur par défaut est off. +-debug[+|-] Émettre des informations de débogage. +-debug:full Émettre des informations de débogage complètes (par défaut). +-debug:pdbonly Émettre des informations de débogage complètes. +-debug:portable Émettre des informations de débogage multiplateformes. +-debug:embedded Émettre des informations de débogage multiplateformes dans + le fichier .dll ou .exe cible. +-deterministic Produire un assembly déterministe + (en incluant le GUID et l'horodatage de la version du module) +-refonly Produire un assembly de référence à la place de la sortie principale +-instrument:TestCoverage Produire un assembly instrumenté pour collecter + les informations de couverture +-sourcelink:<fichier> Informations du lien source à incorporer dans le fichier PDB. - - ERRORS AND WARNINGS - --nowarn Disable all warnings. --nowarn:<number_list> Disable a list of individual warnings. --warnaserror[+|-] Treat all warnings as errors. --warnaserror[+|-]:<number_list> Treat a list of warnings as errors. --ruleset:<file> Specify a ruleset file that disables specific - diagnostics. --errorlog:<file>[,version=<sarif_version>] - Specify a file to log all compiler and analyzer - diagnostics in SARIF format. - sarif_version:{1|2|2.1} Default is 1. 2 and 2.1 - both mean SARIF version 2.1.0. --reportanalyzer Report additional analyzer information, such as - execution time. --skipanalyzers[+|-] Skip execution of diagnostic analyzers. + - ERREURS ET AVERTISSEMENTS - +-nowarn Désactiver tous les avertissements. +-nowarn:<liste_numéros> Désactiver une liste d'avertissements individuels. +-warnaserror[+|-] Traiter tous les avertissements comme des erreurs. +-warnaserror[+|-]:<liste_numéros> Traiter une liste d'avertissements comme des erreurs. +-ruleset:<fichier> Spécifier un fichier ruleset qui désactive des + diagnostics spécifiques. +-errorlog:<fichier>[,version=<version_sarif>] + Spécifier un fichier pour journaliser tous les diagnostics du compilateur + et de l'analyseur au format SARIF. + version_sarif :{1|2|2.1} La valeur par défaut est 1. 2 et 2.1 + Les deux signifient SARIF version 2.1.0. +-reportanalyzer Signaler des informations supplémentaires sur l'analyseur, par exemple + la durée d'exécution. +-skipanalyzers[+|-] Ignorer l'exécution des analyseurs de diagnostic. - - LANGUAGE - --define:<symbol_list> Declare global conditional compilation - symbol(s). symbol_list:name=value,... - (Short form: -d) --imports:<import_list> Declare global Imports for namespaces in - referenced metadata files. - import_list:namespace,... --langversion:? Display the allowed values for language version --langversion:<string> Specify language version such as - `default` (latest major version), or - `latest` (latest version, including minor versions), - or specific versions like `14` or `15.3` --optionexplicit[+|-] Require explicit declaration of variables. --optioninfer[+|-] Allow type inference of variables. --rootnamespace:<string> Specifies the root Namespace for all type - declarations. --optionstrict[+|-] Enforce strict language semantics. --optionstrict:custom Warn when strict language semantics are not - respected. --optioncompare:binary Specifies binary-style string comparisons. - This is the default. --optioncompare:text Specifies text-style string comparisons. + - LANGAGE - +-define:<liste_symboles> Déclarer des symboles de compilation + conditionnelle globale. liste_symboles:name=value,... + (Forme abrégée : -d) +-imports:<liste_importations> Déclarer des importations globales pour les espaces de noms dans + les fichiers de métadonnées référencés. + liste_importations:namespace,... +-langversion:? Afficher les valeurs autorisées pour la version du langage +-langversion:<chaîne> Spécifier la version du langage, par exemple + 'default' (dernière version principale) ou + 'latest' (dernière version, en incluant les versions mineures), + ou des versions spécifiques comme '14' ou '15.3' +-optionexplicit[+|-] Imposer une déclaration explicite des variables. +-optioninfer[+|-] Autoriser l'inférence de type des variables. +-rootnamespace:<chaîne> Spécifie l'espace de noms racine pour toutes les + déclarations de type. +-optionstrict[+|-] Appliquer une sémantique stricte du langage. +-optionstrict:custom Avertir quand la sémantique stricte du langage n'est pas + respectée. +-optioncompare:binary Spécifie des comparaisons de chaînes de style binaire. + Il s'agit de la valeur par défaut. +-optioncompare:text Spécifie des comparaisons de chaînes de style texte. - - MISCELLANEOUS - --help Display this usage message. (Short form: -?) --noconfig Do not auto-include VBC.RSP file. --nologo Do not display compiler copyright banner. --quiet Quiet output mode. --verbose Display verbose messages. --parallel[+|-] Concurrent build. --version Display the compiler version number and exit. + - DIVERS - +-help Afficher ce message d'utilisation. (Forme abrégée : -?) +-noconfig Ne pas inclure automatiquement un fichier VBC.RSP. +-nologo Ne pas afficher la bannière de copyright du compilateur. +-quiet Mode de sortie silencieux. +-verbose Afficher des messages documentés. +-parallel[+|-] Build simultanée. +-version Afficher le numéro de version du compilateur et quitter le processus. - - ADVANCED - --baseaddress:<number> The base address for a library or module - (hex). --checksumalgorithm:<alg> Specify algorithm for calculating source file - checksum stored in PDB. Supported values are: - SHA1 or SHA256 (default). --codepage:<number> Specifies the codepage to use when opening - source files. --delaysign[+|-] Delay-sign the assembly using only the public - portion of the strong name key. --publicsign[+|-] Public-sign the assembly using only the public - portion of the strong name key. --errorreport:<string> Specifies how to handle internal compiler - errors; must be prompt, send, none, or queue - (default). --filealign:<number> Specify the alignment used for output file - sections. --highentropyva[+|-] Enable high-entropy ASLR. --keycontainer:<string> Specifies a strong name key container. --keyfile:<file> Specifies a strong name key file. --libpath:<path_list> List of directories to search for metadata - references. (Semi-colon delimited.) --main:<class> Specifies the Class or Module that contains - Sub Main. It can also be a Class that - inherits from System.Windows.Forms.Form. - (Short form: -m) --moduleassemblyname:<string> Name of the assembly which this module will - be a part of. --netcf Target the .NET Compact Framework. --nostdlib Do not reference standard libraries - (system.dll and VBC.RSP file). + - AVANCÉ - +-baseaddress:<numéro> Adresse de base d'une bibliothèque ou d'un module + (en hexadécimal). +-checksumalgorithm:<alg> Spécifier l'algorithme de calcul de la somme de contrôle + de fichier source stockée dans le fichier PDB. Valeurs prises en charge : + SHA1 ou SHA256 (par défaut). +-codepage:<numéro> Spécifie la page de codes à utiliser à l'ouverture + des fichiers sources. +-delaysign[+|-] Différer la signature de l'assembly en utilisant uniquement + la partie publique de la clé de nom fort. +-publicsign[+|-] Signer publiquement l'assembly en utilisant uniquement + la partie publique de la clé de nom fort. +-errorreport:<chaîne> Spécifie comment prendre en charge les erreurs internes du + compilateur ; doit avoir la valeur prompt, send, none ou queue + (par défaut). +-filealign:<numéro> Spécifier l'alignement utilisé pour les + sections du fichier de sortie. +-highentropyva[+|-] Activer la randomisation du format d'espace d'adresse d'entropie élevée. +-keycontainer:<chaîne> Spécifie un conteneur de clé de nom fort. +-keyfile:<fichier> Spécifie un fichier de clé de nom fort. +-libpath:<liste_chemins> Liste de répertoires où rechercher des + références de métadonnées. (Valeurs délimitées par des points-virgules.) +-main:<classe> Spécifie la classe ou le module qui contient + Sub Main. Il peut également s'agir d'une classe qui + hérite de System.Windows.Forms.Form. + (Forme abrégée : -m) +-moduleassemblyname:<chaîne> Nom de l'assembly dont ce module + doit faire partie. +-netcf Cibler le .NET Compact Framework. +-nostdlib Ne pas référencer les bibliothèques standard + (fichiers system.dll et VBC.RSP). -pathmap:<K1>=<V1>,<K2>=<V2>,... - Specify a mapping for source path names output by - the compiler. --platform:<string> Limit which platforms this code can run on; - must be x86, x64, Itanium, arm, arm64 - AnyCPU32BitPreferred or anycpu (default). --preferreduilang Specify the preferred output language name. --nosdkpath Disable searching the default SDK path for standard library assemblies. --sdkpath:<path> Location of the .NET Framework SDK directory + Spécifier un mappage pour les noms de chemins sources sortis par + le compilateur. +-platform:<chaîne> Limiter les plateformes sur lesquelles ce code peut s'exécuter ; + doit correspondre à x86, x64, Itanium, arm, arm64 + AnyCPU32BitPreferred ou anycpu (par défaut). +-preferreduilang Spécifier le nom du langage de sortie préféré. +-nosdkpath Désactivez la recherche du chemin du kit SDK par défaut pour les assemblys de bibliothèque standard. +-sdkpath:<chemin> Emplacement du répertoire du SDK .NET Framework (mscorlib.dll). --subsystemversion:<version> Specify subsystem version of the output PE. - version:<number>[.<number>] --utf8output[+|-] Emit compiler output in UTF8 character - encoding. -@<file> Insert command-line settings from a text file --vbruntime[+|-|*] Compile with/without the default Visual Basic - runtime. --vbruntime:<file> Compile with the alternate Visual Basic - runtime in <file>. +-subsystemversion:<version> Spécifier la version du sous-système du PE de sortie. + version:<numéro>[.<numéro>] +-utf8output[+|-] Émettre la sortie du compilateur au format + d'encodage de caractères UTF8. +@<fichier> Insérer les paramètres de ligne de commande à partir d'un fichier texte +-vbruntime[+|-|*] Compiler avec/sans le + runtime Visual Basic par défaut. +-vbruntime:<fichier> Compiler avec le + runtime Visual Basic de remplacement dans <fichier>. @@ -463,6 +463,50 @@ L'argument de type ne peut pas être Nothing + + The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + L'assembly '{0}' contenant le type '{1}' référence le .NET Framework, ce qui n'est pas pris en charge. + {1} is the type that was loaded, {0} is the containing assembly. + + + The loaded assembly references .NET Framework, which is not supported. + L'assembly chargé référence le .NET Framework, ce qui n'est pas pris en charge. + + + + Generator '{0}' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + Le générateur '{0}' n'a pas pu générer la source. Dans la mesure où il ne va pas contribuer à la sortie, des erreurs de compilation peuvent se produire. Exception levée de type '{1}' avec le message '{2}' + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + Le générateur a levé l'exception suivante : +'{0}'. + {0} is the string representation of the exception that was thrown. + + + Generator failed to generate source. + Le générateur n'a pas pu générer la source. + + + + Generator '{0}' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + Échec de l'initialisation du générateur '{0}'. Dans la mesure où il ne va pas contribuer à la sortie, des erreurs de compilation peuvent se produire. Exception levée de type '{1}' avec le message '{2}' + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + Le générateur a levé l'exception suivante : +'{0}'. + {0} is the string representation of the exception that was thrown. + + + Generator failed to initialize. + Échec de l'initialisation du générateur. + + Wrong number of type arguments Nombre incorrect d'arguments de type diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.it.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.it.xlf index fd609c72ecf15..bb17a775b497c 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.it.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.it.xlf @@ -212,169 +212,169 @@ -vbruntime:<file> Compile with the alternate Visual Basic runtime in <file>. - Visual Basic Compiler Options + Opzioni del compilatore Visual Basic - - OUTPUT FILE - --out:<file> Specifies the output file name. --target:exe Create a console application (default). - (Short form: -t) --target:winexe Create a Windows application. --target:library Create a library assembly. --target:module Create a module that can be added to an - assembly. --target:appcontainerexe Create a Windows application that runs in + - FILE DI OUTPUT - +-out:<file> Consente di specificare il nome del file di output. +-target:exe Crea un'applicazione console (impostazione predefinita). + Forma breve: -t +-target:winexe Consente di creare un'applicazione Windows. +-target:library Consente di creare un assembly di librerie. +-target:module Consente di creare un modulo che può essere aggiunto a un + assembly. +-target:appcontainerexe Consente di creare un'applicazione Windows che viene eseguita in AppContainer. --target:winmdobj Create a Windows Metadata intermediate file --doc[+|-] Generates XML documentation file. --doc:<file> Generates XML documentation file to <file>. --refout:<file> Reference assembly output to generate +-target:winmdobj Consente di creare un file intermedio di metadati di Windows. +-doc[+|-] Genera un file di documentazione XML. +-doc:<file> Genera un file di documentazione XML in <file>. +-refout:<file> Output dell'assembly di riferimento da generare - - INPUT FILES - --addmodule:<file_list> Reference metadata from the specified modules --link:<file_list> Embed metadata from the specified interop - assembly. (Short form: -l) --recurse:<wildcard> Include all files in the current directory - and subdirectories according to the - wildcard specifications. --reference:<file_list> Reference metadata from the specified - assembly. (Short form: -r) --analyzer:<file_list> Run the analyzers from this assembly - (Short form: -a) --additionalfile:<file list> Additional files that don't directly affect code - generation but may be used by analyzers for producing - errors or warnings. + - FILE DI INPUT - +-addmodule:<elenco_file> Crea un riferimento ai metadati dai moduli specificati. +-link:<elenco_file> Incorpora metadati dall'assembly di interoperabilità + specificato. Forma breve: -l +-recurse:<caratteri_jolly> Include tutti i file presenti nella directory corrente + e nelle relative sottodirectory in base + ai caratteri jolly specificati. +-reference:<elenco_file> Crea un riferimento ai metadati dall'assembly + specificato. Forma breve: -r +-analyzer:<elenco_file> Esegue gli analizzatori dall'assembly. + Forma breve: -a +-additionalfile:<elenco file> File aggiuntivi che non influiscono + direttamente sulla generazione del codice ma possono essere usati + dagli analizzatori per produrre errori o avvisi. - - RESOURCES - --linkresource:<resinfo> Links the specified file as an external - assembly resource. - resinfo:<file>[,<name>[,public|private]] - (Short form: -linkres) --nowin32manifest The default manifest should not be embedded - in the manifest section of the output PE. --resource:<resinfo> Adds the specified file as an embedded - assembly resource. - resinfo:<file>[,<name>[,public|private]] - (Short form: -res) --win32icon:<file> Specifies a Win32 icon file (.ico) for the - default Win32 resources. --win32manifest:<file> The provided file is embedded in the manifest - section of the output PE. --win32resource:<file> Specifies a Win32 resource file (.res). + - RISORSE - +-linkresource:<info_risorsa> Collega il file specificato come + risorsa di assembly esterna. + resinfo:<file>[,<nome>[,public|private]] + Forma breve: -linkres +-nowin32manifest Il manifesto predefinito non deve essere incorporato nella + sezione manifesto del file PE di output. +-resource:<info_risorsa> Aggiunge il file specificato come + risorsa di assembly incorporata. + resinfo:<file>[,<nome>[,public|private]] + Forma breve: -res +-win32icon:<file> Consente di specificare un file di icona Win32 (.ico) per le risorse + Win32 predefinite. +-win32manifest:<file> Il file fornito è incorporato nella sezione manifesto + del file PE di output. +-win32resource:<file> Consente di specificare un file di risorse Win32 (.res). - - CODE GENERATION - --optimize[+|-] Enable optimizations. --removeintchecks[+|-] Remove integer checks. Default off. --debug[+|-] Emit debugging information. --debug:full Emit full debugging information (default). --debug:pdbonly Emit full debugging information. --debug:portable Emit cross-platform debugging information. --debug:embedded Emit cross-platform debugging information into - the target .dll or .exe. --deterministic Produce a deterministic assembly - (including module version GUID and timestamp) --refonly Produce a reference assembly in place of the main output --instrument:TestCoverage Produce an assembly instrumented to collect - coverage information --sourcelink:<file> Source link info to embed into PDB. + - GENERAZIONE DEL CODICE - +-optimize[+|-] Abilita le ottimizzazioni. +-removeintchecks[+|-] Rimuove il controllo dei numeri interi. Per impostazione predefinita, è disattivato. +-debug[+|-] Crea le informazioni di debug. +-debug:full Crea le informazioni di debug complete (impostazione predefinita). +-debug:pdbonly Crea le informazioni di debug complete. +-debug:portable Crea informazioni di debug multipiattaforma. +-debug:embedded Crea informazioni di debug multipiattaforma nel file + DLL o EXE di destinazione. +-deterministic Produce un assembly deterministico + (che include GUID e timestamp della versione del modulo) +-refonly Produce un assembly di riferimento al posto dell'output principale +-instrument:TestCoverage Produce un assembly instrumentato per raccogliere + informazioni sul code coverage +-sourcelink:<file> Informazioni sul collegamento all'origine da incorporare nel file PDB. - - ERRORS AND WARNINGS - --nowarn Disable all warnings. --nowarn:<number_list> Disable a list of individual warnings. --warnaserror[+|-] Treat all warnings as errors. --warnaserror[+|-]:<number_list> Treat a list of warnings as errors. --ruleset:<file> Specify a ruleset file that disables specific - diagnostics. --errorlog:<file>[,version=<sarif_version>] - Specify a file to log all compiler and analyzer - diagnostics in SARIF format. - sarif_version:{1|2|2.1} Default is 1. 2 and 2.1 - both mean SARIF version 2.1.0. --reportanalyzer Report additional analyzer information, such as - execution time. --skipanalyzers[+|-] Skip execution of diagnostic analyzers. + - ERRORI E AVVISI - +-nowarn Disabilita tutti gli avvisi. +-nowarn:<elenco_numeri> Disabilita un elenco di avvisi singoli. +-warnaserror[+|-] Considera tutti gli avvisi come errori. +-warnaserror[+|-]:<elenco_numeri> Considera un elenco di avvisi come errori. +-ruleset:<file> Consente di specificare un file di set di regole che disabilita + diagnostica specifica. +-errorlog:<file>[,version=<versione _SARIF>] + Consente di specificare un file in cui registrare tutte le diagnostiche del + compilatore e dell'analizzatore in formato SARIF. + versione_SARIF:{1|2|2.1} L'impostazione predefinita è 1. 2 e 2.1 + si riferiscono entrambi a SARIF versione 2.1.0. +-reportanalyzer Restituisce informazioni aggiuntive dell'analizzatore, ad + esempio il tempo di esecuzione. +-skipanalyzers[+|-] Ignora l'esecuzione degli analizzatore diagnostici. - - LANGUAGE - --define:<symbol_list> Declare global conditional compilation - symbol(s). symbol_list:name=value,... - (Short form: -d) --imports:<import_list> Declare global Imports for namespaces in - referenced metadata files. - import_list:namespace,... --langversion:? Display the allowed values for language version --langversion:<string> Specify language version such as - `default` (latest major version), or - `latest` (latest version, including minor versions), - or specific versions like `14` or `15.3` --optionexplicit[+|-] Require explicit declaration of variables. --optioninfer[+|-] Allow type inference of variables. --rootnamespace:<string> Specifies the root Namespace for all type - declarations. --optionstrict[+|-] Enforce strict language semantics. --optionstrict:custom Warn when strict language semantics are not - respected. --optioncompare:binary Specifies binary-style string comparisons. - This is the default. --optioncompare:text Specifies text-style string comparisons. + - LINGUAGGIO - +-define:<elenco_simboli> Dichiara simboli di compilazione condizionale + globale. elenco_simboli:nome=valore,... + Forma breve: -d +-imports:<elenco_importazioni> Dichiara importazioni globali per spazi dei nomi in + file di metadati a cui viene fatto riferimento. + elenco_importazioni:spazio dei nomi,... +-langversion:? Visualizza i valori consentiti per la versione del linguaggio +-langversion:<stringa> Consente di specificare la versione del linguaggio, ad esempio + `default` (ultima versione principale), o + `latest` (ultima versione che include versioni secondarie), + oppure versioni specifiche, come `14` o `15.3` +-optionexplicit[+|-] Richiede la dichiarazione esplicita delle variabili. +-optioninfer[+|-] Consente l'inferenza del tipo delle variabili. +-rootnamespace:<stringa> Consente di specificare lo spazio dei nomi radice per tutte le dichiarazioni + di tipo. +-optionstrict[+|-] Attiva la semantica del linguaggio strict. +-optionstrict:custom Avvisa quando la semantica del linguaggio strict non + viene rispettata. +-optioncompare:binary Consente di specificare i confronti fra stringhe binarie. + Impostazione predefinita. +-optioncompare:text Consente di specificare i confronti fra stringhe di testo. - - MISCELLANEOUS - --help Display this usage message. (Short form: -?) --noconfig Do not auto-include VBC.RSP file. --nologo Do not display compiler copyright banner. --quiet Quiet output mode. --verbose Display verbose messages. --parallel[+|-] Concurrent build. --version Display the compiler version number and exit. + - VARIE - +-help Visualizza questo messaggio relativo alla sintassi. Forma breve: -? +-noconfig Non include automaticamente il file VBC.RSP. +-nologo Non visualizza le informazioni sul copyright del compilatore. +-quiet Modalità di output non interattiva. +-verbose Visualizza messaggi dettagliati. +-parallel[+|-] Compilazione simultanea. +-version Visualizza il numero di versione del compilatore ed esce. - - ADVANCED - --baseaddress:<number> The base address for a library or module + - AVANZATE - +-baseaddress:<numero> Indirizzo di base di una libreria o di un modulo (hex). --checksumalgorithm:<alg> Specify algorithm for calculating source file - checksum stored in PDB. Supported values are: - SHA1 or SHA256 (default). --codepage:<number> Specifies the codepage to use when opening - source files. --delaysign[+|-] Delay-sign the assembly using only the public - portion of the strong name key. --publicsign[+|-] Public-sign the assembly using only the public - portion of the strong name key. --errorreport:<string> Specifies how to handle internal compiler - errors; must be prompt, send, none, or queue - (default). --filealign:<number> Specify the alignment used for output file - sections. --highentropyva[+|-] Enable high-entropy ASLR. --keycontainer:<string> Specifies a strong name key container. --keyfile:<file> Specifies a strong name key file. --libpath:<path_list> List of directories to search for metadata - references. (Semi-colon delimited.) --main:<class> Specifies the Class or Module that contains - Sub Main. It can also be a Class that - inherits from System.Windows.Forms.Form. - (Short form: -m) --moduleassemblyname:<string> Name of the assembly which this module will - be a part of. --netcf Target the .NET Compact Framework. --nostdlib Do not reference standard libraries - (system.dll and VBC.RSP file). +-checksumalgorithm:<alg> Consente di specificare l'algoritmo per calcolare il checksum + del file di origine archiviato nel file PDB. I valori supportati sono: + SHA1 o SHA256 (impostazione predefinita). +-codepage:<numero> Consente di specificare la tabella codici da usare all'apertura dei file + di origine. +-delaysign[+|-] Ritarda la firma dell'assembly usando solo la parte pubblica della + chiave con nome sicuro. +-publicsign[+|-] Firma pubblicamente l'assembly usando solo la parte pubblica + della chiave con nome sicuro. +-errorreport:<stringa> Consente di specificare come gestire gli errori interni del compilatore. + I valori devono essere prompt, send, none o queue + (impostazione predefinita). +-filealign:<numero> Consente di specificare l'allineamento usato per le sezioni del file di + output. +-highentropyva[+|-] Abilita ASLR a entropia elevata. +-keycontainer:<stringa> Consente di specificare un contenitore di chiavi con nome sicuro. +-keyfile:<file> Consente di specificare un file di chiave con nome sicuro. +-libpath:<elenco_percorsi> Elenco di directory delimitate da punti e virgola in cui cercare + riferimenti ai metadati. +-main:<classe> Consente di specificare la classe o il modulo che contiene + Sub Main. Può essere anche una classe che + eredita da System.Windows.Forms.Form. + Forma breve: -m +-moduleassemblyname:<stringa> Nome dell'assembly di cui farà parte questo + modulo. +-netcf Destinato a .NET Compact Framework. +-nostdlib Omette i riferimenti alle librerie standard + (system.dll e VBC.RSP file). -pathmap:<K1>=<V1>,<K2>=<V2>,... - Specify a mapping for source path names output by - the compiler. --platform:<string> Limit which platforms this code can run on; - must be x86, x64, Itanium, arm, arm64 - AnyCPU32BitPreferred or anycpu (default). --preferreduilang Specify the preferred output language name. --nosdkpath Disable searching the default SDK path for standard library assemblies. --sdkpath:<path> Location of the .NET Framework SDK directory + Consente di specificare un mapping per i nomi di percorso di origine + visualizzati dal compilatore. +-platform:<stringa> Limita le piattaforme in cui è possibile eseguire questo codice. + Il valore deve essere x86, x64, Itanium, arm, arm64, + AnyCPU32BitPreferred o anycpu (impostazione predefinita). +-preferreduilang Consente di specificare il nome del linguaggio di output preferito. +-nosdkpath Disabilita la ricerca di assembly di librerie standard nel percorso predefinito dell'SDK. +-sdkpath:<percorso> Percorso della directory di .NET Framework SDK (mscorlib.dll). --subsystemversion:<version> Specify subsystem version of the output PE. - version:<number>[.<number>] --utf8output[+|-] Emit compiler output in UTF8 character - encoding. -@<file> Insert command-line settings from a text file --vbruntime[+|-|*] Compile with/without the default Visual Basic - runtime. --vbruntime:<file> Compile with the alternate Visual Basic - runtime in <file>. +-subsystemversion:<versione> Consente di specificare la versione del sottosistema del file PE di output. + version:<numero>[.<numero>] +-utf8output[+|-] Crea l'output del compilatore con codifica dei caratteri + UTF8. +@<file> Inserisce le impostazioni della riga di comando da un file di testo. +-vbruntime[+|-|*] Compila con-senza il runtime di Visual Basic + predefinito. +-vbruntime:<file> Compila con il runtime di Visual Basic alternativo + in <file>. @@ -463,6 +463,50 @@ L'argomento di tipo non può essere Nothing + + The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + L'assembly '{0}' che contiene il tipo '{1}' fa riferimento a .NET Framework, che non è supportato. + {1} is the type that was loaded, {0} is the containing assembly. + + + The loaded assembly references .NET Framework, which is not supported. + L'assembly caricato fa riferimento a .NET Framework, che non è supportato. + + + + Generator '{0}' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + Il generatore '{0}' non è riuscito a generare l'origine. Non verrà aggiunto come contributo all'output e potrebbero verificarsi errori di compilazione. Eccezione di tipo '{1}'. Messaggio '{2}' + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + Il generatore dell'analizzatore ha generato l'eccezione seguente: +'{0}'. + {0} is the string representation of the exception that was thrown. + + + Generator failed to generate source. + Il generatore non è riuscito a generare l'origine. + + + + Generator '{0}' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + Non è stato possibile inizializzare il generatore '{0}'. Non verrà aggiunto come contributo all'output e potrebbero verificarsi errori di compilazione. Eccezione di tipo '{1}'. Messaggio '{2}' + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + Il generatore dell'analizzatore ha generato l'eccezione seguente: +'{0}'. + {0} is the string representation of the exception that was thrown. + + + Generator failed to initialize. + Non è stato possibile inizializzare il generatore. + + Wrong number of type arguments Il numero di argomenti di tipo è errato @@ -470,7 +514,7 @@ file '{0}' could not be found - Il file '{0}' non è stato trovato. + Il file '{0}' non è stato trovato @@ -3223,7 +3267,7 @@ Type of '{0}' is ambiguous because the loop bounds and the step clause do not convert to the same type. - {0}' è di tipo ambiguo perché i limiti del ciclo e la clausola step non eseguono la conversione nello stesso tipo. + '{0}' è di tipo ambiguo perché i limiti del ciclo e la clausola step non eseguono la conversione nello stesso tipo. @@ -4143,7 +4187,7 @@ '{0}', implicitly declared for {1} '{2}', cannot shadow a 'MustOverride' method in the base {3} '{4}'. - '{0}, dichiarato in modo implicito per {1} '{2}', non può nascondere un metodo 'MustOverride' nell'elemento {3} base '{4}'. + '{0}', dichiarato in modo implicito per {1} '{2}', non può nascondere un metodo 'MustOverride' nell'elemento {3} base '{4}'. @@ -6206,7 +6250,7 @@ Non CLS-compliant '{0}' is not allowed in a CLS-compliant interface. - {0}' non conforme a CLS non è consentito in un'interfaccia conforme a CLS. + '{0}' non conforme a CLS non è consentito in un'interfaccia conforme a CLS. @@ -7438,7 +7482,7 @@ Public sign was specified and requires a public key, but no public key was specified - È stata specificata la firma pubblica per la quale è necessaria una chiave pubblica, che però non è stata specificata. + È stata specificata la firma pubblica per la quale è necessaria una chiave pubblica, che però non è stata specificata @@ -8358,7 +8402,7 @@ Referenced assembly targets a different processor - L'assembly di riferimento ha come destinazione un processore diverso. + L'assembly di riferimento ha come destinazione un processore diverso @@ -8478,7 +8522,7 @@ The system cannot find the path specified - Il percorso specificato non è stato trovato. + Il percorso specificato non è stato trovato diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.ja.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.ja.xlf index afde707d91047..05c4385a09fe0 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.ja.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.ja.xlf @@ -212,169 +212,169 @@ -vbruntime:<file> Compile with the alternate Visual Basic runtime in <file>. - Visual Basic Compiler Options + Visual Basic コンパイラのオプション - - OUTPUT FILE - --out:<file> Specifies the output file name. --target:exe Create a console application (default). - (Short form: -t) --target:winexe Create a Windows application. --target:library Create a library assembly. --target:module Create a module that can be added to an - assembly. --target:appcontainerexe Create a Windows application that runs in - AppContainer. --target:winmdobj Create a Windows Metadata intermediate file --doc[+|-] Generates XML documentation file. --doc:<file> Generates XML documentation file to <file>. --refout:<file> Reference assembly output to generate + - 出力ファイル - +-out:<file> 出力ファイル名を指定します。 +-target:exe コンソール アプリケーションを作成します (既定)。 + (短い形式: -t) +-target:winexe Windows アプリケーションを作成します。 +-target:library ライブラリ アセンブリを作成します。 +-target:module アセンブリに追加できるモジュールを作成 + します。 +-target:appcontainerexe AppContainer で実行される Windows アプリケーションを + 作成します。 +-target:winmdobj Windows メタデータ中間ファイルを作成します +-doc[+|-] XML ドキュメント ファイルを生成します。 +-doc:<file> XML ドキュメント ファイルを <file> に生成します。 +-refout:<file> 生成する参照アセンブリの出力 - - INPUT FILES - --addmodule:<file_list> Reference metadata from the specified modules --link:<file_list> Embed metadata from the specified interop - assembly. (Short form: -l) --recurse:<wildcard> Include all files in the current directory - and subdirectories according to the - wildcard specifications. --reference:<file_list> Reference metadata from the specified - assembly. (Short form: -r) --analyzer:<file_list> Run the analyzers from this assembly - (Short form: -a) --additionalfile:<file list> Additional files that don't directly affect code - generation but may be used by analyzers for producing - errors or warnings. + - 入力ファイル - +-addmodule:<file_list> 指定されたモジュールからメタデータを参照します +-link:<file_list> 指定された相互運用アセンブリから + メタデータを埋め込みます。(短い形式: -l) +-recurse:<wildcard> ワイルドカードの指定に従い、 + 現在のディレクトリとサブディレクトリ内の + すべてのファイルをインクルードします。 +-reference:<file_list> 指定されたアセンブリから + メタデータを参照します。(短い形式: -r) +-analyzer:<file_list> このアセンブリからアナライザーを実行します + (短い形式: -a) +-additionalfile:<file list> コード生成には直接影響しないものの、 + アナライザーがエラーまたは警告を + 生成するために使用する可能性のある追加ファイル。 - - RESOURCES - --linkresource:<resinfo> Links the specified file as an external - assembly resource. + - リソース - +-linkresource:<resinfo> 指定されたファイルを外部のアセンブリ リソースとして + リンクします。 resinfo:<file>[,<name>[,public|private]] - (Short form: -linkres) --nowin32manifest The default manifest should not be embedded - in the manifest section of the output PE. --resource:<resinfo> Adds the specified file as an embedded - assembly resource. + (短い形式: -linkres) +-nowin32manifest 出力 PE のマニフェスト セクションに既定の + マニフェストを埋め込まないでください。 +-resource:<resinfo> 指定されたファイルを + 埋め込みアセンブリ リソースとして追加します。 resinfo:<file>[,<name>[,public|private]] - (Short form: -res) --win32icon:<file> Specifies a Win32 icon file (.ico) for the - default Win32 resources. --win32manifest:<file> The provided file is embedded in the manifest - section of the output PE. --win32resource:<file> Specifies a Win32 resource file (.res). + (短い形式: -res) +-win32icon:<file> Win32 アイコン ファイル (.ico) を + 既定の Win32 リソースに指定します。 +-win32manifest:<file> 指定されたファイルは出力 PE の + マニフェスト セクションに埋め込まれています。 +-win32resource:<file> Win32 リソース ファイル (.res) を指定します。 - - CODE GENERATION - --optimize[+|-] Enable optimizations. --removeintchecks[+|-] Remove integer checks. Default off. --debug[+|-] Emit debugging information. --debug:full Emit full debugging information (default). --debug:pdbonly Emit full debugging information. --debug:portable Emit cross-platform debugging information. --debug:embedded Emit cross-platform debugging information into - the target .dll or .exe. --deterministic Produce a deterministic assembly - (including module version GUID and timestamp) --refonly Produce a reference assembly in place of the main output --instrument:TestCoverage Produce an assembly instrumented to collect - coverage information --sourcelink:<file> Source link info to embed into PDB. + - コード生成 - +-optimize[+|-] 最適化を有効にします。 +-removeintchecks[+|-] 整数のチェックを削除します。既定値は Off です。 +-debug[+|-] デバッグ情報を生成します。 +-debug:full 完全なデバッグ情報を生成します (既定値)。 +-debug:pdbonly 完全なデバッグ情報を生成します。 +-debug:portable クロスプラットフォーム デバッグ情報を生成します。 +-debug:embedded クロスプラットフォーム デバッグ情報を + ターゲット .dll または .exe 内に生成します。 +-deterministic 決定論的アセンブリを作成します + (モジュール バージョン GUID やタイムスタンプなど) +-refonly メイン出力の代わりに参照アセンブリを生成します +-instrument:TestCoverage カバレッジ情報を収集するようにインストルメント + されたアセンブリを生成します +-sourcelink:<file> PDB に埋め込むソース リンク情報。 - - ERRORS AND WARNINGS - --nowarn Disable all warnings. --nowarn:<number_list> Disable a list of individual warnings. --warnaserror[+|-] Treat all warnings as errors. --warnaserror[+|-]:<number_list> Treat a list of warnings as errors. --ruleset:<file> Specify a ruleset file that disables specific - diagnostics. + - エラーと警告 - +-nowarn すべての警告を無効にします。 +-nowarn:<number_list> 個々の警告リストを無効にします。 +-warnaserror[+|-] すべての警告をエラーとして扱います。 +-warnaserror[+|-]:<number_list> 警告リストをエラーとして扱います。 +-ruleset:<file> 特定の診断を無効にするルールセット ファイルを + 指定します。 -errorlog:<file>[,version=<sarif_version>] - Specify a file to log all compiler and analyzer - diagnostics in SARIF format. - sarif_version:{1|2|2.1} Default is 1. 2 and 2.1 - both mean SARIF version 2.1.0. --reportanalyzer Report additional analyzer information, such as - execution time. --skipanalyzers[+|-] Skip execution of diagnostic analyzers. + すべてのコンパイラおよびアナライザーの診断を + SARIF 形式でログに記録するためのファイルを指定します。 + sarif_version:{1|2|2.1} 既定値は 1 です。2 と 2.1 は + どちらも SARIF バージョン 2.1.0 を意味します。 +-reportanalyzer 追加のアナライザー情報を報告します + (実行時間など)。 +-skipanalyzers[+|-] アナライザーの診断の実行をスキップします。 - - LANGUAGE - --define:<symbol_list> Declare global conditional compilation - symbol(s). symbol_list:name=value,... - (Short form: -d) --imports:<import_list> Declare global Imports for namespaces in - referenced metadata files. + - 言語 - +-define:<symbol_list> 条件付きコンパイル シンボルをグローバルに宣言 + します。symbol_list:name=value,... + (短い形式: -d) +-imports:<import_list> 参照されたメタデータ ファイルの + 名前空間に対して Imports をグローバルに宣言します。 import_list:namespace,... --langversion:? Display the allowed values for language version --langversion:<string> Specify language version such as - `default` (latest major version), or - `latest` (latest version, including minor versions), - or specific versions like `14` or `15.3` --optionexplicit[+|-] Require explicit declaration of variables. --optioninfer[+|-] Allow type inference of variables. --rootnamespace:<string> Specifies the root Namespace for all type - declarations. --optionstrict[+|-] Enforce strict language semantics. --optionstrict:custom Warn when strict language semantics are not - respected. --optioncompare:binary Specifies binary-style string comparisons. - This is the default. --optioncompare:text Specifies text-style string comparisons. +-langversion:? 言語バージョンに許容される値を表示します +-langversion:<string> `default` (最新のメジャー バージョン) や + `latest` (マイナー バージョンを含む最新バージョン) + または、`14` や `15.3`などの特定バージョン + で言語バージョンを指定します。 +-optionexplicit[+|-] 変数の明示的な宣言が必要です。 +-optioninfer[+|-] 変数の型の推定を許可します。 +-rootnamespace:<string> すべての型宣言に対して + ルート名前空間を指定します。 +-optionstrict[+|-] 厳密な言語セマンティクスを適用します。 +-optionstrict:custom 厳密な言語セマンティクスが + 守られていないときに警告します。 +-optioncompare:binary バイナリ スタイルの文字列比較を指定します。 + これは既定値です。 +-optioncompare:text テキスト スタイルの文字列比較を指定します。 - - MISCELLANEOUS - --help Display this usage message. (Short form: -?) --noconfig Do not auto-include VBC.RSP file. --nologo Do not display compiler copyright banner. --quiet Quiet output mode. --verbose Display verbose messages. --parallel[+|-] Concurrent build. --version Display the compiler version number and exit. + - その他 - +-help 使用法に関するメッセージを表示します。(短い形式: -?) +-noconfig VBC.RSP ファイルを自動的にはインクルードしません。 +-nologo コンパイラの著作権情報を表示しません。 +-quiet 非表示出力モードです。 +-verbose 詳細メッセージを表示します。 +-parallel[+|-] ビルドを並列処理します。 +-version コンパイラのバージョン番号を出力して終了します。 - - ADVANCED - --baseaddress:<number> The base address for a library or module - (hex). --checksumalgorithm:<alg> Specify algorithm for calculating source file - checksum stored in PDB. Supported values are: - SHA1 or SHA256 (default). --codepage:<number> Specifies the codepage to use when opening - source files. --delaysign[+|-] Delay-sign the assembly using only the public - portion of the strong name key. --publicsign[+|-] Public-sign the assembly using only the public - portion of the strong name key. --errorreport:<string> Specifies how to handle internal compiler - errors; must be prompt, send, none, or queue - (default). --filealign:<number> Specify the alignment used for output file - sections. --highentropyva[+|-] Enable high-entropy ASLR. --keycontainer:<string> Specifies a strong name key container. --keyfile:<file> Specifies a strong name key file. --libpath:<path_list> List of directories to search for metadata - references. (Semi-colon delimited.) --main:<class> Specifies the Class or Module that contains - Sub Main. It can also be a Class that - inherits from System.Windows.Forms.Form. - (Short form: -m) --moduleassemblyname:<string> Name of the assembly which this module will - be a part of. --netcf Target the .NET Compact Framework. --nostdlib Do not reference standard libraries - (system.dll and VBC.RSP file). + - 詳細 - +-baseaddress:<number> ライブラリまたはモジュールのベース アドレス + (16 進数)。 +-checksumalgorithm:<alg> PDB に格納されているソース ファイルのチェックサム + を計算するアルゴリズムを指定します。サポートされる値: + SHA1 や SHA256 (既定)。 +-codepage:<number> ソース ファイルを開くときに使用するコードページを + 指定します。 +-delaysign[+|-] アセンブリの遅延署名には厳密な名前キーのうち + 公開された部分のみを使用します。 +-publicsign[+|-] 厳密な名前キーの公開部分のみを使ってアセンブリ + を公開署名します。 +-errorreport:<string> 内部コンパイラ エラーの処理方法を指定 + します。prompt、send、none、queue + (既定) のいずれかでなければなりません。 +-filealign:<number> 出力ファイル セクションで使う配置 + を指定します。 +-highentropyva[+|-] 高エントロピ ASLR を有効化します。 +-keycontainer:<string> 厳密な名前キーのコンテナーを指定します。 +-keyfile:<file> 厳密な名前キーのファイルを指定します。 +-libpath:<path_list> メタデータ参照を検索する + ディレクトリの (セミコロン区切りの) リスト。 +-main:<class> Sub Main を含むクラスまたはモジュール + を指定します。System.Windows.Forms.Form から継承 + されるクラスにすることもできます。 + (短い形式: -m) +-moduleassemblyname:<string> このモジュールが一部となる + アセンブリ名です。 +-netcf .NET Compact Framework をターゲットにします。 +-nostdlib 標準ライブラリ + (system.dll と VBC.RSP ファイル) を参照しません。 -pathmap:<K1>=<V1>,<K2>=<V2>,... - Specify a mapping for source path names output by - the compiler. --platform:<string> Limit which platforms this code can run on; - must be x86, x64, Itanium, arm, arm64 - AnyCPU32BitPreferred or anycpu (default). --preferreduilang Specify the preferred output language name. --nosdkpath Disable searching the default SDK path for standard library assemblies. --sdkpath:<path> Location of the .NET Framework SDK directory - (mscorlib.dll). --subsystemversion:<version> Specify subsystem version of the output PE. + コンパイラが出力するソース パス名のマッピングを + 指定します。 +-platform:<string> このコードを実行できるプラットフォームは + x86、x64、Itanium、arm、arm64、 + AnyCPU32BitPreferred、anycpu (既定) のいずれかでなければなりません。 +-preferreduilang 出力用の優先する言語名を指定します。 +-nosdkpath 標準ライブラリ アセンブリの既定の SDK パスの検索を無効にします。 +-sdkpath:<path> .NET Framework SDK ディレクトリ (mscorlib.dll) + の場所。 +-subsystemversion:<version> 出力 PE のサブシステム バージョンを指定します。 version:<number>[.<number>] --utf8output[+|-] Emit compiler output in UTF8 character - encoding. -@<file> Insert command-line settings from a text file --vbruntime[+|-|*] Compile with/without the default Visual Basic - runtime. --vbruntime:<file> Compile with the alternate Visual Basic - runtime in <file>. +-utf8output[+|-] コンパイラ出力を UTF-8 文字エンコード + で作成します。 +@<file> コマンド ライン設定をテキスト ファイルから挿入します +-vbruntime[+|-|*] 既定の Visual Basic ランタイムを使用して、または使用せずに + コンパイルします。 +-vbruntime:<file> <file> の別の Visual Basic ランタイムを使用して + コンパイルします。 @@ -405,7 +405,7 @@ Syntax tree already present - 構文ツリーが既に存在しています。 + 構文ツリーが既に存在しています @@ -420,7 +420,7 @@ SyntaxTree '{0}' not found to remove - 削除する構文ツリー '{0}' が見つかりません。 + 削除する構文ツリー '{0}' が見つかりません @@ -460,17 +460,61 @@ Type argument cannot be Nothing - 型引数に Nothing は使用できません。 + 型引数に Nothing は使用できません + + + + The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + 型 '{1}' を含むアセンブリ '{0}' が .NET Framework を参照しています。これはサポートされていません。 + {1} is the type that was loaded, {0} is the containing assembly. + + + The loaded assembly references .NET Framework, which is not supported. + 読み込まれたアセンブリが .NET Framework を参照しています。これはサポートされていません。 + + + + Generator '{0}' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + ジェネレーター '{0}' でソースを生成できませんでした。出力には寄与しません。結果として、コンパイル エラーが発生する可能性があります。例外の型: '{1}'。メッセージ: '{2}' + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + ジェネレーターで次の例外がスローされました: +'{0}'。 + {0} is the string representation of the exception that was thrown. + + + Generator failed to generate source. + ジェネレーターはソースを生成できませんでした。 + + + + Generator '{0}' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + ジェネレーター '{0}' を初期化できませんでした。出力には寄与しません。結果として、コンパイル エラーが発生する可能性があります。例外の型: '{1}'。メッセージ: '{2}' + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + ジェネレーターで次の例外がスローされました: +'{0}'。 + {0} is the string representation of the exception that was thrown. + + + Generator failed to initialize. + ジェネレーターを初期化できませんでした。 Wrong number of type arguments - 型引数の数が正しくありません。 + 型引数の数が正しくありません file '{0}' could not be found - ファイル '{0}' が見つかりませんでした。 + ファイル '{0}' が見つかりませんでした @@ -485,7 +529,7 @@ option '{0}' can be followed only by '+' or '-' - オプション '{0}' の後には '+' または '-' のみを指定できます。 + オプション '{0}' の後には '+' または '-' のみを指定できます @@ -515,12 +559,12 @@ Command-line syntax error: Invalid Guid format '{0}' for option '{1}' - コマンドラインの構文エラー: オプション '{1}' の GUID 形式 '{0}' が無効です。 + コマンドラインの構文エラー: オプション '{1}' の GUID 形式 '{0}' が無効です Command-line syntax error: Missing Guid for option '{1}' - コマンドラインの構文エラー: オプション '{1}' の GUID がありません。 + コマンドラインの構文エラー: オプション '{1}' の GUID がありません @@ -540,12 +584,12 @@ no input sources specified - 入力ソースが指定されていません。 + 入力ソースが指定されていません source file '{0}' specified multiple times - ソース ファイル '{0}' が複数回指定されています。 + ソース ファイル '{0}' が複数回指定されています @@ -560,17 +604,17 @@ code page '{0}' is invalid or not installed - コード ページ '{0}' は無効か、またはインストールされていません。 + コード ページ '{0}' は無効か、またはインストールされていません the file '{0}' is not a text file - ファイル '{0}' はテキスト ファイルではありません。 + ファイル '{0}' はテキスト ファイルではありません could not find library '{0}' - ライブラリ '{0}' が見つかりませんでした。 + ライブラリ '{0}' が見つかりませんでした @@ -580,12 +624,12 @@ cannot specify both /win32icon and /win32resource - /win32icon と /win32resource を両方指定することはできません。 + /win32icon と /win32resource を両方指定することはできません ignoring /noconfig option because it was specified in a response file - /noconfig オプションは、応答ファイルで指定されているため無視されます。 + /noconfig オプションは、応答ファイルで指定されているため無視されます @@ -595,7 +639,7 @@ warning number '{0}' for the option '{1}' is either not configurable or not valid - 警告番号 '{0}' (オプション '{1}' ) は、構成できないか無効です。 + 警告番号 '{0}' (オプション '{1}' ) は、構成できないか無効です @@ -605,17 +649,17 @@ cannot infer an output file name from resource only input files; provide the '/out' option - リソースのみの入力ファイルから出力ファイル名を生成することはできません。'/out' オプションを指定してください。 + リソースのみの入力ファイルから出力ファイル名を生成することはできません。'/out' オプションを指定してください the /moduleassemblyname option may only be specified when building a target of type 'module' - /moduleassemblyname オプションは 'module' 型のターゲットをビルドするときのみ指定できます。 + /moduleassemblyname オプションは 'module' 型のターゲットをビルドするときのみ指定できます '{0}' is not a valid value for /moduleassemblyname - '{0}' は /moduleassemblyname の有効な値ではありません。 + '{0}' は /moduleassemblyname の有効な値ではありません @@ -680,7 +724,7 @@ Inheriting from '{0}' is not valid. - {0}' からの継承は、有効ではありません。 + '{0}' からの継承は、有効ではありません。 @@ -725,7 +769,7 @@ Statement is not valid inside '{0}' block. - {0}' ブロックの内部では有効でないステートメントです。 + '{0}' ブロックの内部では有効でないステートメントです。 @@ -860,7 +904,7 @@ Too many arguments to '{0}'. - {0}' の引数が多すぎます。 + '{0}' の引数が多すぎます。 @@ -1135,7 +1179,7 @@ First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class '{0}' of '{1}' does not have an accessible 'Sub New' that can be called with no arguments. - {1}' の基底クラス '{0}' には、引数なしで呼び出される、アクセス可能な 'Sub New' がないため、この 'Sub New' の最初のステートメントは、'MyBase.New' または 'MyClass.New' に対して呼び出さなければなりません。 + '{1}' の基底クラス '{0}' には、引数なしで呼び出される、アクセス可能な 'Sub New' がないため、この 'Sub New' の最初のステートメントは、'MyBase.New' または 'MyClass.New' に対して呼び出さなければなりません。 @@ -1514,7 +1558,7 @@ Parameter '{0}' of '{1}' already has a matching argument. - {1}' のパラメーター '{0}' には、一致する引数が既に存在します。 + '{1}' のパラメーター '{0}' には、一致する引数が既に存在します。 @@ -1559,7 +1603,7 @@ Cannot update '{0}'; attribute '{1}' is missing. - {0}' を更新できません。属性 '{1}' がありません。 + '{0}' を更新できません。属性 '{1}' がありません。 @@ -1663,7 +1707,7 @@ Cannot refer to '{0}' because it is a member of the value-typed field '{1}' of class '{2}' which has 'System.MarshalByRefObject' as a base class. - {0}' は、'System.MarshalByRefObject' を基本クラスとして持つクラス '{2}' の値付きフィールド '{1}' のメンバーであるため、参照できません。 + '{0}' は、'System.MarshalByRefObject' を基本クラスとして持つクラス '{2}' の値付きフィールド '{1}' のメンバーであるため、参照できません。 @@ -1678,12 +1722,12 @@ Value of type '{0}' cannot be converted to '{1}' because '{2}' is not derived from '{3}'. - {2}' は '{3}' から派生していないため、型 '{0}' の値を '{1}' に変換できません。 + '{2}' は '{3}' から派生していないため、型 '{0}' の値を '{1}' に変換できません。 Value of type '{0}' cannot be converted to '{1}' because '{2}' is not a reference type. - {2}' が参照型でないため、'{0}' 型の値を '{1}' に変換できません。 + '{2}' が参照型でないため、'{0}' 型の値を '{1}' に変換できません。 @@ -1973,7 +2017,7 @@ Argument not specified for parameter '{0}' of '{1}'. - {1}' のパラメーター '{0}' に対して引数が指定されていません。 + '{1}' のパラメーター '{0}' に対して引数が指定されていません。 @@ -2118,7 +2162,7 @@ Overload resolution failed because no '{0}' is accessible. - {0}' にアクセスできないため、オーバーロードの解決に失敗しました。 + '{0}' にアクセスできないため、オーバーロードの解決に失敗しました。 @@ -2667,7 +2711,7 @@ Attribute '{0}' in '{1}' cannot be applied multiple times. - {1}' 内の属性 '{0}' を複数回適用することはできません。 + '{1}' 内の属性 '{0}' を複数回適用することはできません。 @@ -2932,12 +2976,12 @@ None of the accessible 'Main' methods with the appropriate signatures found in '{0}' can be the startup method since they are all either generic or nested in generic types. - {0}' で見つかった正しいシグネチャを持つ、アクセス可能な 'Main' メソッドは、スタートアップ メソッドにはなりません。それらの 'Main' メソッドはすべてジェネリックまたはジェネリック型の中に入れ子にされているためです。 + '{0}' で見つかった正しいシグネチャを持つ、アクセス可能な 'Main' メソッドは、スタートアップ メソッドにはなりません。それらの 'Main' メソッドはすべてジェネリックまたはジェネリック型の中に入れ子にされているためです。 Error in project-level import '{0}' at '{1}' : {2} - {1}' でのプロジェクト レベル インポート '{0}' でエラーが発生しました: {2} + '{1}' でのプロジェクト レベル インポート '{0}' でエラーが発生しました: {2} @@ -3087,12 +3131,12 @@ First statement of this 'Sub New' must be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete. - {2}' の基底クラス '{1}' にある '{0}' には廃止マークが付けられているため、この 'Sub New' の最初のステートメントは、明示的な 'MyBase.New' または 'MyClass.New' への呼び出しでなければなりません。 + '{2}' の基底クラス '{1}' にある '{0}' には廃止マークが付けられているため、この 'Sub New' の最初のステートメントは、明示的な 'MyBase.New' または 'MyClass.New' への呼び出しでなければなりません。 First statement of this 'Sub New' must be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete: '{3}'. - {2}' の基底クラス '{1}' の '{0}' には廃止マークが付けられているため、この 'Sub New' の最初のステートメントは、明示的な 'MyBase.New' または 'MyClass.New' への呼び出しでなければなりません: '{3}' + '{2}' の基底クラス '{1}' の '{0}' には廃止マークが付けられているため、この 'Sub New' の最初のステートメントは、明示的な 'MyBase.New' または 'MyClass.New' への呼び出しでなければなりません: '{3}' @@ -3107,7 +3151,7 @@ Specified access '{0}' for '{1}' does not match the access '{2}' specified on one of its other partial types. - {1}' に指定されたアクセス '{0}' は、その他の partial 型の 1 つで指定されたアクセス '{2}' と一致しません。 + '{1}' に指定されたアクセス '{0}' は、その他の partial 型の 1 つで指定されたアクセス '{2}' と一致しません。 @@ -3188,7 +3232,7 @@ No accessible method '{0}' has a signature compatible with delegate '{1}':{2} - デリゲート '{1}':{2} と互換性のあるシグネチャを持つアクセス可能なメソッド '{0}' がありません。 + デリゲート '{1}':{2} と互換性のあるシグネチャを持つアクセス可能なメソッド '{0}' がありません @@ -3208,7 +3252,7 @@ Type of '{0}' cannot be inferred from an expression containing '{0}'. - {0}' の型を '{0}' を含んでいる式から推論することはできません。 + '{0}' の型を '{0}' を含んでいる式から推論することはできません。 @@ -3248,7 +3292,7 @@ Multiple initializations of '{0}'. Fields and properties can be initialized only once in an object initializer expression. - {0}' を複数回初期化しています。フィールドまたはプロパティは、オブジェクト初期化子式で複数回初期化することはできません。 + '{0}' を複数回初期化しています。フィールドまたはプロパティは、オブジェクト初期化子式で複数回初期化することはできません。 @@ -4018,7 +4062,7 @@ Cannot convert '{0}' to '{1}'. You can use the 'Value' property to get the string value of the first element of '{2}'. - {0}' を '{1}' に変換できません。'{2}' の最初の要素の文字列値は、'Value' プロパティを使用して取得できます。 + '{0}' を '{1}' に変換できません。'{2}' の最初の要素の文字列値は、'Value' プロパティを使用して取得できます。 @@ -4043,12 +4087,12 @@ The value '{0}' is not a valid subsystem version. The version must be 6.02 or greater for ARM or AppContainerExe, and 4.00 or greater otherwise. - {0}' は有効なサブシステム バージョンの値ではありません。バージョンは、ARM または AppContainerExe では 6.02 以上、その他の場合は 4.00 以上であることが必要です。 + '{0}' は有効なサブシステム バージョンの値ではありません。バージョンは、ARM または AppContainerExe では 6.02 以上、その他の場合は 4.00 以上であることが必要です。 Invalid file section alignment '{0}' - {0}' は無効なファイル セクションの配置です。 + '{0}' は無効なファイル セクションの配置です @@ -4143,7 +4187,7 @@ '{0}', implicitly declared for {1} '{2}', cannot shadow a 'MustOverride' method in the base {3} '{4}'. - '{1} '{2}' で暗黙のうちに宣言された '{0}' が、基底 {3} '{4}' の 'MustOverride' メソッドをシャドウすることはできません。 + {1} '{2}' で暗黙のうちに宣言された '{0}' が、基底 {3} '{4}' の 'MustOverride' メソッドをシャドウすることはできません。 @@ -4208,7 +4252,7 @@ '{0}' is ambiguous because multiple kinds of members with this name exist in {1} '{2}'. - '{1} '{2}' に同じ名前のメンバーが多種類存在するため、'{0}' があいまいです。 + {1} '{2}' に同じ名前のメンバーが多種類存在するため、'{0}' があいまいです。 @@ -4233,7 +4277,7 @@ Method '{0}' cannot implement partial method '{1}' because '{2}' already implements it. Only one method can implement a partial method. - {2}' によって既に実装されているため、メソッド '{0}' は部分メソッド '{1}' を実装できません。部分メソッドを実装できるのは 1 つのメソッドだけです。 + '{2}' によって既に実装されているため、メソッド '{0}' は部分メソッド '{1}' を実装できません。部分メソッドを実装できるのは 1 つのメソッドだけです。 @@ -4478,7 +4522,7 @@ Parameter '{0}' in '{1}' already has a matching omitted argument. - {1}' のパラメーター '{0}' には、一致する省略された引数が既に存在します。 + '{1}' のパラメーター '{0}' には、一致する省略された引数が既に存在します。 @@ -4533,7 +4577,7 @@ First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class '{0}' of '{1}' has more than one accessible 'Sub New' that can be called with no arguments. - {1}' の基底クラス '{0}' には、引数なしで呼び出せるアクセス可能な 'Sub New' が 2 つ以上指定されているため、この 'Sub New' の最初のステートメントは、'MyBase.New' または 'MyClass.New' への呼び出しでなければなりません。 + '{1}' の基底クラス '{0}' には、引数なしで呼び出せるアクセス可能な 'Sub New' が 2 つ以上指定されているため、この 'Sub New' の最初のステートメントは、'MyBase.New' または 'MyClass.New' への呼び出しでなければなりません。 @@ -4543,7 +4587,7 @@ The '{0}' keyword is used to overload inherited members; do not use the '{0}' keyword when overloading 'Sub New'. - {0}' キーワードは、継承されたメンバーをオーバーロードするために使用されます。'Sub New' をオーバーロードするときには '{0}' を使用しないでください。 + '{0}' キーワードは、継承されたメンバーをオーバーロードするために使用されます。'Sub New' をオーバーロードするときには '{0}' を使用しないでください。 @@ -4553,12 +4597,12 @@ Too few type arguments to '{0}'. - {0}' の型引数が少なすぎます。 + '{0}' の型引数が少なすぎます。 Too many type arguments to '{0}'. - {0}' の型引数が多すぎます。 + '{0}' の型引数が多すぎます。 @@ -4593,7 +4637,7 @@ Type parameter '{0}' for '{1}' cannot be inferred. - {1}' の型パラメーター '{0}' を推論できません。 + '{1}' の型パラメーター '{0}' を推論できません。 @@ -5175,12 +5219,12 @@ Matching '{0}' operator is required for '{1}'. - {1}' には対応する '{0}' 演算子が必要です。 + '{1}' には対応する '{0}' 演算子が必要です。 Return and parameter types of '{0}' must be '{1}' to be used in a '{2}' expression. - {0}' の戻り値およびパラメーターの型を '{2}' 式で使用するには、'{1}' にしなければなりません。 + '{0}' の戻り値およびパラメーターの型を '{2}' 式で使用するには、'{1}' にしなければなりません。 @@ -5200,7 +5244,7 @@ Return and parameter types of '{0}' must be '{1}' to be used in a 'For' statement. - {0}' の戻り値型およびパラメーター型は、'For' ステートメントで使用するためには '{1}' でなければなりません。 + '{0}' の戻り値型およびパラメーター型は、'For' ステートメントで使用するためには '{1}' でなければなりません。 @@ -5450,7 +5494,7 @@ Anonymous type member property '{0}' cannot be used to infer the type of another member property because the type of '{0}' is not yet established. - {0}' の型がまだ確立されていないため、匿名型メンバーのプロパティ '{0}' を使用して別のメンバーのプロパティの型を推論することはできません。 + '{0}' の型がまだ確立されていないため、匿名型メンバーのプロパティ '{0}' を使用して別のメンバーのプロパティの型を推論することはできません。 @@ -5549,17 +5593,17 @@ Too many arguments to extension method '{0}' defined in '{1}'. - {1}' で定義された拡張メソッド '{0}' の引数が多すぎます。 + '{1}' で定義された拡張メソッド '{0}' の引数が多すぎます。 Parameter '{0}' in extension method '{1}' defined in '{2}' already has a matching omitted argument. - {2}' で定義された拡張メソッド '{1}' のパラメーター '{0}' には、一致する省略された引数が既に存在します。 + '{2}' で定義された拡張メソッド '{1}' のパラメーター '{0}' には、一致する省略された引数が既に存在します。 Parameter '{0}' of extension method '{1}' defined in '{2}' already has a matching argument. - {2}' で定義された拡張メソッド '{1}' のパラメーター '{0}' には、一致する引数が既に存在します。 + '{2}' で定義された拡張メソッド '{1}' のパラメーター '{0}' には、一致する引数が既に存在します。 @@ -5569,22 +5613,22 @@ Argument not specified for parameter '{0}' of extension method '{1}' defined in '{2}'. - {2}' で定義された拡張メソッド '{1}' のパラメーター '{0}' に対して引数が指定されていません。 + '{2}' で定義された拡張メソッド '{1}' のパラメーター '{0}' に対して引数が指定されていません。 Type parameter '{0}' for extension method '{1}' defined in '{2}' cannot be inferred. - {2}' で定義された拡張メソッド '{1}' の型パラメーター '{0}' を推論できません。 + '{2}' で定義された拡張メソッド '{1}' の型パラメーター '{0}' を推論できません。 Too few type arguments to extension method '{0}' defined in '{1}'. - {1}' で定義された拡張メソッド '{0}' の型引数が少なすぎます。 + '{1}' で定義された拡張メソッド '{0}' の型引数が少なすぎます。 Too many type arguments to extension method '{0}' defined in '{1}'. - {1}' で定義されている拡張メソッド '{0}' の型引数が多すぎます。 + '{1}' で定義されている拡張メソッド '{0}' の型引数が多すぎます。 @@ -5719,12 +5763,12 @@ Lambda expression cannot be converted to '{0}' because '{0}' is not a delegate type. - {0}' は、デリゲート型でないため、ラムダ式を '{0}' に変換できません。 + '{0}' は、デリゲート型でないため、ラムダ式を '{0}' に変換できません。 Lambda expression cannot be converted to '{0}' because type '{0}' is declared 'MustInherit' and cannot be created. - {0}' は 'MustInherit' として宣言されていて作成することができないので、ラムダ式を '{0}' に変換することはできません。 + '{0}' は 'MustInherit' として宣言されていて作成することができないので、ラムダ式を '{0}' に変換することはできません。 @@ -5814,7 +5858,7 @@ Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. - {1}' で定義されている拡張メソッド '{0}' 内の型パラメーターのデータ型をこれらの引数から推論することはできません。データ型を明示的に指定することによって、このエラーを修正できる可能性があります。 + '{1}' で定義されている拡張メソッド '{0}' 内の型パラメーターのデータ型をこれらの引数から推論することはできません。データ型を明示的に指定することによって、このエラーを修正できる可能性があります。 @@ -5829,7 +5873,7 @@ Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments. - {1}' で定義された拡張メソッド '{0}' 内の型パラメーターのデータ型を、これらの引数から推論することはできません。 + '{1}' で定義された拡張メソッド '{0}' 内の型パラメーターのデータ型を、これらの引数から推論することはできません。 @@ -5844,7 +5888,7 @@ Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error. - {1}' で定義されている拡張メソッド '{0}' 内の型パラメーターのデータ型をこれらの引数から推論しようとしても、複数の型の可能性があるため、できません。データ型を明示的に指定することによって、このエラーを修正できる場合があります。 + '{1}' で定義されている拡張メソッド '{0}' 内の型パラメーターのデータ型をこれらの引数から推論しようとしても、複数の型の可能性があるため、できません。データ型を明示的に指定することによって、このエラーを修正できる場合があります。 @@ -5859,7 +5903,7 @@ Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because more than one type is possible. - {1}' で定義されている拡張メソッド '{0}' 内の型パラメーターのデータ型をこれらの引数から推論しようとしても、複数の型の可能性があるため、できません。 + '{1}' で定義されている拡張メソッド '{0}' 内の型パラメーターのデータ型をこれらの引数から推論しようとしても、複数の型の可能性があるため、できません。 @@ -5874,7 +5918,7 @@ Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error. - {1}' で定義されている拡張メソッド '{0}' 内の型パラメーターのデータ型をこれらの引数から推論しようとしても、複数の型の可能性があるため、できません。データ型を明示的に指定することによって、このエラーを修正できる場合があります。 + '{1}' で定義されている拡張メソッド '{0}' 内の型パラメーターのデータ型をこれらの引数から推論しようとしても、複数の型の可能性があるため、できません。データ型を明示的に指定することによって、このエラーを修正できる場合があります。 @@ -5889,7 +5933,7 @@ Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because they do not convert to the same type. - {1}' で定義されている拡張メソッド '{0}' 内の型パラメーターのデータ型をこれらの引数から推論しようとしても、同じ型に変換されないため、できません。 + '{1}' で定義されている拡張メソッド '{0}' 内の型パラメーターのデータ型をこれらの引数から推論しようとしても、同じ型に変換されないため、できません。 @@ -5919,7 +5963,7 @@ Extension Method '{0}' defined in '{2}' does not have a signature compatible with delegate '{1}'. - {2}' で定義された拡張メソッド '{0}' に、デリゲート '{1}' と互換性があるシグネチャがありません。 + '{2}' で定義された拡張メソッド '{0}' に、デリゲート '{1}' と互換性があるシグネチャがありません。 @@ -5956,7 +6000,7 @@ Extension method '{0}' defined in '{1}' is not generic (or has no free type parameters) and so cannot have type arguments. - {1}' で定義された拡張メソッド '{0}' はジェネリックではない (または自由型パラメーターがない) ため、型引数を指定できません。 + '{1}' で定義された拡張メソッド '{0}' はジェネリックではない (または自由型パラメーターがない) ため、型引数を指定できません。 @@ -6376,7 +6420,7 @@ Casing of namespace name '{0}' does not match casing of namespace name '{1}' in '{2}'. - {2}' で、名前空間の名前 '{0}' の大文字と小文字の指定が、名前空間の名前 '{1}' の大文字と小文字の指定と一致しません。 + '{2}' で、名前空間の名前 '{0}' の大文字と小文字の指定が、名前空間の名前 '{1}' の大文字と小文字の指定と一致しません。 @@ -6436,7 +6480,7 @@ First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete. - {2}' の基本クラス '{1}' にある '{0}' が古い形式に設定されているため、この 'Sub New' の最初のステートメントは、明示的な 'MyBase.New' または 'MyClass.New' への呼び出しでなければなりません。 + '{2}' の基本クラス '{1}' にある '{0}' が古い形式に設定されているため、この 'Sub New' の最初のステートメントは、明示的な 'MyBase.New' または 'MyClass.New' への呼び出しでなければなりません。 @@ -6446,7 +6490,7 @@ First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete: '{3}' - {2}' の基本クラス '{1}' にある '{0}' が古い形式に設定されているため、この 'Sub New' の最初のステートメントは、明示的な 'MyBase.New' または 'MyClass.New' への呼び出しでなければなりません: '{3}' + '{2}' の基本クラス '{1}' にある '{0}' が古い形式に設定されているため、この 'Sub New' の最初のステートメントは、明示的な 'MyBase.New' または 'MyClass.New' への呼び出しでなければなりません: '{3}' @@ -6536,7 +6580,7 @@ Implicit conversion from '{0}' to '{1}'. - {0}' から '{1}' への暗黙的な変換。 + '{0}' から '{1}' への暗黙的な変換。 @@ -7126,7 +7170,7 @@ Runtime errors might occur when converting '{0}' to '{1}'. - {0}' から '{1}' への変換時にランタイム エラーが発生する可能性があります。 + '{0}' から '{1}' への変換時にランタイム エラーが発生する可能性があります。 @@ -7538,7 +7582,7 @@ The assembly name '{0}' is reserved and cannot be used as a reference in an interactive session - アセンブリ名 '{0}' は予約されており、対話形式のセッションで参照として使用することはできません。 + アセンブリ名 '{0}' は予約されており、対話形式のセッションで参照として使用することはできません @@ -7553,7 +7597,7 @@ You cannot use '{0}' in top-level script code - トップ レベル スクリプト コードでは '{0}' を使用できません。 + トップ レベル スクリプト コードでは '{0}' を使用できません @@ -7638,7 +7682,7 @@ Data type of '{0}' in '{1}' could not be inferred. '{2}' assumed. - {1}' 内にある '{0}' のデータ型を推論できませんでした。'{2}' と見なされます。 + '{1}' 内にある '{0}' のデータ型を推論できませんでした。'{2}' と見なされます。 @@ -7653,7 +7697,7 @@ Conversion from '{0}' to '{1}' may be ambiguous. - {0}' から '{1}' への変換はあいまいな可能性があります。 + '{0}' から '{1}' への変換はあいまいな可能性があります。 @@ -7688,7 +7732,7 @@ Implicit conversion from '{4}' to '{5}'; this conversion may fail because '{0}' is not derived from '{1}', as required for the 'In' generic parameter '{2}' in '{3}'. - {4}' から '{5}' への暗黙の型変換です。'{0}' は、'{3}' の 'In' ジェネリック パラメーター '{2}' に求められるように '{1}' から派生していないため、この変換は失敗する可能性があります。 + '{4}' から '{5}' への暗黙の型変換です。'{0}' は、'{3}' の 'In' ジェネリック パラメーター '{2}' に求められるように '{1}' から派生していないため、この変換は失敗する可能性があります。 @@ -7698,7 +7742,7 @@ Implicit conversion from '{4}' to '{5}'; this conversion may fail because '{0}' is not derived from '{1}', as required for the 'Out' generic parameter '{2}' in '{3}'. - {4}' から '{5}' への暗黙の型変換です。'{0}' は、'{3}' の 'Out' ジェネリック パラメーター '{2}' に求められるように '{1}' から派生していないため、この変換は失敗する可能性があります。 + '{4}' から '{5}' への暗黙の型変換です。'{0}' は、'{3}' の 'Out' ジェネリック パラメーター '{2}' に求められるように '{1}' から派生していないため、この変換は失敗する可能性があります。 @@ -7768,37 +7812,37 @@ Type '{0}' cannot be used in this context because '{0}' is an 'In' type parameter. - {0}' は 'In' 型パラメーターであるため、このコンテキストでは型 '{0}' を使用できません。 + '{0}' は 'In' 型パラメーターであるため、このコンテキストでは型 '{0}' を使用できません。 Type '{0}' cannot be used for the '{1}' in '{2}' in this context because '{0}' is an 'In' type parameter. - {0}' は 'In' 型パラメーターであるため、このコンテキストで '{2}' の '{1}' に対して型 '{0}' を使用することはできません。 + '{0}' は 'In' 型パラメーターであるため、このコンテキストで '{2}' の '{1}' に対して型 '{0}' を使用することはできません。 Type '{0}' cannot be used in '{1}' in this context because '{0}' is an 'In' type parameter. - {0}' は 'In' 型パラメーターであるため、このコンテキストの '{1}' で型 '{0}' を使用することはできません。 + '{0}' は 'In' 型パラメーターであるため、このコンテキストの '{1}' で型 '{0}' を使用することはできません。 Type '{0}' cannot be used for the '{2}' of '{3}' in '{1}' in this context because '{0}' is an 'In' type parameter. - {0}' は 'In' 型パラメーターであるため、このコンテキストで '{1}' 内の '{3}' の '{2}' に対して型 '{0}' を使用することはできません。 + '{0}' は 'In' 型パラメーターであるため、このコンテキストで '{1}' 内の '{3}' の '{2}' に対して型 '{0}' を使用することはできません。 Type '{0}' cannot be used as a property type in this context because '{0}' is an 'In' type parameter and the property is not marked WriteOnly. - {0}' は 'In' 型パラメーターであり、プロパティは WriteOnly として指定されていないため、このコンテキストでは型 '{0}' をプロパティ型として使用することはできません。 + '{0}' は 'In' 型パラメーターであり、プロパティは WriteOnly として指定されていないため、このコンテキストでは型 '{0}' をプロパティ型として使用することはできません。 Type '{0}' cannot be used as a ReadOnly property type because '{0}' is an 'In' type parameter. - {0}' は 'In' 型パラメーターであるため、型 '{0}' を ReadOnly プロパティ型として使用することはできません。 + '{0}' は 'In' 型パラメーターであるため、型 '{0}' を ReadOnly プロパティ型として使用することはできません。 Type '{0}' cannot be used as a return type because '{0}' is an 'In' type parameter. - {0}' は 'In' 型パラメーターであるため、型 '{0}' を戻り値の型として使用することはできません。 + '{0}' は 'In' 型パラメーターであるため、型 '{0}' を戻り値の型として使用することはできません。 @@ -7808,12 +7852,12 @@ Type '{0}' cannot be used as a ByVal parameter type because '{0}' is an 'Out' type parameter. - {0}' は 'Out' 型パラメーターであるため、型 '{0}' を ByVal パラメーター型として使用することはできません。 + '{0}' は 'Out' 型パラメーターであるため、型 '{0}' を ByVal パラメーター型として使用することはできません。 Type '{0}' cannot be used as a generic type constraint because '{0}' is an 'Out' type parameter. - {0}' は 'Out' 型パラメーターであるため、型 '{0}' をジェネリック型の制約として使用することはできません。 + '{0}' は 'Out' 型パラメーターであるため、型 '{0}' をジェネリック型の制約として使用することはできません。 @@ -7823,32 +7867,32 @@ Type '{0}' cannot be used in this context because '{0}' is an 'Out' type parameter. - {0}' は 'Out' 型パラメーターであるため、このコンテキストでは型 '{0}' を使用できません。 + '{0}' は 'Out' 型パラメーターであるため、このコンテキストでは型 '{0}' を使用できません。 Type '{0}' cannot be used for the '{1}' in '{2}' in this context because '{0}' is an 'Out' type parameter. - {0}' は 'Out' 型パラメーターであるため、このコンテキストで '{2}' の '{1}' に対して型 '{0}' を使用することはできません。 + '{0}' は 'Out' 型パラメーターであるため、このコンテキストで '{2}' の '{1}' に対して型 '{0}' を使用することはできません。 Type '{0}' cannot be used in '{1}' in this context because '{0}' is an 'Out' type parameter. - {0}' は 'Out' 型パラメーターであるため、このコンテキストの '{1}' で型 '{0}' を使用することはできません。 + '{0}' は 'Out' 型パラメーターであるため、このコンテキストの '{1}' で型 '{0}' を使用することはできません。 Type '{0}' cannot be used for the '{2}' of '{3}' in '{1}' in this context because '{0}' is an 'Out' type parameter. - {0}' は 'Out' 型パラメーターであるため、このコンテキストで '{1}' 内の '{3}' の '{2}' に対して型 '{0}' を使用することはできません。 + '{0}' は 'Out' 型パラメーターであるため、このコンテキストで '{1}' 内の '{3}' の '{2}' に対して型 '{0}' を使用することはできません。 Type '{0}' cannot be used as a property type in this context because '{0}' is an 'Out' type parameter and the property is not marked ReadOnly. - {0}' は 'Out' 型パラメーターであり、プロパティは ReadOnly として指定されていないため、このコンテキストでは型 '{0}' をプロパティ型として使用することはできません。 + '{0}' は 'Out' 型パラメーターであり、プロパティは ReadOnly として指定されていないため、このコンテキストでは型 '{0}' をプロパティ型として使用することはできません。 Type '{0}' cannot be used as a WriteOnly property type because '{0}' is an 'Out' type parameter. - {0}' は 'Out' 型パラメーターであるため、型 '{0}' を WriteOnly プロパティ型として使用することはできません。 + '{0}' は 'Out' 型パラメーターであるため、型 '{0}' を WriteOnly プロパティ型として使用することはできません。 @@ -8278,7 +8322,7 @@ Module name '{0}' stored in '{1}' must match its filename. - {1}' に格納されているモジュール名 '{0}' はファイル名と一致する必要があります。 + '{1}' に格納されているモジュール名 '{0}' はファイル名と一致する必要があります。 @@ -8388,7 +8432,7 @@ Reference to '{0}' netmodule missing. - {0}' netmodule への参照がありません。 + '{0}' netmodule への参照がありません。 @@ -8558,7 +8602,7 @@ Cannot link resource files when building a module - モジュールをビルド中にリソース ファイルにリンクできません。 + モジュールをビルド中にリソース ファイルにリンクできません @@ -8718,7 +8762,7 @@ '{0}' is not a valid format specifier - '{0}' は有効な形式指定子ではありません。 + '{0}' は有効な形式指定子ではありません @@ -8818,7 +8862,7 @@ Error reading debug information for '{0}' - {0}' のデバッグ情報の読み取りエラー + '{0}' のデバッグ情報の読み取りエラー @@ -9153,7 +9197,7 @@ File name '{0}' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long - ファイル名 '{0}' は、空である、無効な文字を含んでいる、絶対パスが指定されていないドライブ指定がある、または長すぎるかのいずれかです。 + ファイル名 '{0}' は、空である、無効な文字を含んでいる、絶対パスが指定されていないドライブ指定がある、または長すぎるかのいずれかです diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.ko.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.ko.xlf index 3a471c48bc5bf..cef47d7a1328c 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.ko.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.ko.xlf @@ -212,169 +212,169 @@ -vbruntime:<file> Compile with the alternate Visual Basic runtime in <file>. - Visual Basic Compiler Options + Visual Basic 컴파일러 옵션 - - OUTPUT FILE - --out:<file> Specifies the output file name. --target:exe Create a console application (default). - (Short form: -t) --target:winexe Create a Windows application. --target:library Create a library assembly. --target:module Create a module that can be added to an - assembly. --target:appcontainerexe Create a Windows application that runs in - AppContainer. --target:winmdobj Create a Windows Metadata intermediate file --doc[+|-] Generates XML documentation file. --doc:<file> Generates XML documentation file to <file>. --refout:<file> Reference assembly output to generate + - 출력 파일 - +-out:<file> 출력 파일 이름을 지정합니다. +-target:exe 콘솔 애플리케이션을 만듭니다(기본값). + (약식: -t) +-target:winexe Windows 애플리케이션을 만듭니다. +-target:library 라이브러리 어셈블리를 만듭니다. +-target:module 어셈블리에 추가할 수 있는 모듈을 + 만듭니다. +-target:appcontainerexe AppContainer에서 실행되는 Windows 애플리케이션을 + 만듭니다. +-target:winmdobj Windows 메타데이터 중간 파일을 만듭니다. +-doc[+|-] XML 문서 파일을 생성합니다. +-doc:<file> XML 문서 파일을 <file>에 생성합니다. +-refout:<file> 생성할 참조 어셈블리 출력입니다. - - INPUT FILES - --addmodule:<file_list> Reference metadata from the specified modules --link:<file_list> Embed metadata from the specified interop - assembly. (Short form: -l) --recurse:<wildcard> Include all files in the current directory - and subdirectories according to the - wildcard specifications. --reference:<file_list> Reference metadata from the specified - assembly. (Short form: -r) --analyzer:<file_list> Run the analyzers from this assembly - (Short form: -a) --additionalfile:<file list> Additional files that don't directly affect code - generation but may be used by analyzers for producing - errors or warnings. + - 입력 파일 - +-addmodule:<file_list> 지정한 모듈의 메타데이터를 참조합니다. +-link:<file_list> 지정한 interop 어셈블리의 메타데이터를 + 포함합니다. (약식: -l) +-recurse:<wildcard> 와일드카드 지정에 따라 현재 디렉터리와 + 하위 디렉터리에 있는 모든 파일을 + 포함합니다. +-reference:<file_list> 지정한 어셈블리 파일의 메타데이터를 + 참조합니다. (약식: -r) +-analyzer:<file_list> 이 어셈블리에서 분석기를 실행합니다. + (약식: -a) +-additionalfile:<file list> 코드 생성에 직접적인 영향을 주지 않지만 + 오류 또는 경고 생성을 위해 분석기에서 사용될 수 있는 + 추가 파일입니다. - - RESOURCES - --linkresource:<resinfo> Links the specified file as an external - assembly resource. + - 리소스 - +-linkresource:<resinfo> 지정한 파일을 외부 어셈블리 + 리소스로 연결합니다. resinfo:<file>[,<name>[,public|private]] - (Short form: -linkres) --nowin32manifest The default manifest should not be embedded - in the manifest section of the output PE. --resource:<resinfo> Adds the specified file as an embedded - assembly resource. + (약식: -linkres) +-nowin32manifest 기본 매니페스트는 출력 PE의 매니페스트 섹션에 + 포함하면 안 됩니다. +-resource:<resinfo> 지정한 파일을 포함된 어셈블리 + 리소스로 추가합니다. resinfo:<file>[,<name>[,public|private]] - (Short form: -res) --win32icon:<file> Specifies a Win32 icon file (.ico) for the - default Win32 resources. --win32manifest:<file> The provided file is embedded in the manifest - section of the output PE. --win32resource:<file> Specifies a Win32 resource file (.res). + (약식: -res) +-win32icon:<file> 기본 Win32 리소스에 사용되는 Win32 아이콘 파일(.ico)을 + 지정합니다. +-win32manifest:<file> 제공한 파일이 출력 PE의 매니페스트 + 섹션에 포함됩니다. +-win32resource:<file> Win32 리소스 파일(.res)을 지정합니다. - - CODE GENERATION - --optimize[+|-] Enable optimizations. --removeintchecks[+|-] Remove integer checks. Default off. --debug[+|-] Emit debugging information. --debug:full Emit full debugging information (default). --debug:pdbonly Emit full debugging information. --debug:portable Emit cross-platform debugging information. --debug:embedded Emit cross-platform debugging information into - the target .dll or .exe. --deterministic Produce a deterministic assembly - (including module version GUID and timestamp) --refonly Produce a reference assembly in place of the main output --instrument:TestCoverage Produce an assembly instrumented to collect - coverage information --sourcelink:<file> Source link info to embed into PDB. + - 코드 생성 - +-optimize[+|-] 최적화를 사용하도록 설정합니다. +-removeintchecks[+|-] 정수 오류 검사를 제거합니다. 기본값은 off입니다. +-debug[+|-] 디버깅 정보를 내보냅니다. +-debug:full 전체 디버깅 정보를 내보냅니다(기본값). +-debug:pdbonly 전체 디버깅 정보를 내보냅니다. +-debug:portable 플랫폼 간 디버깅 정보를 내보냅니다. +-debug:embedded 플랫폼 간 디버깅 정보를 대상 .dll 또는 .exe로 + 내보냅니다. +-deterministic 결정적 어셈블리를 생성합니다 + (모듈 버전 GUID 및 타임스탬프 포함). +-refonly 주 출력 대신 참조 어셈블리를 생성합니다. +-instrument:TestCoverage 검사 정보를 수집하기 위해 계측한 + 어셈블리를 생성합니다. +-sourcelink:<file> PDB에 포함할 소스 링크 정보입니다. - - ERRORS AND WARNINGS - --nowarn Disable all warnings. --nowarn:<number_list> Disable a list of individual warnings. --warnaserror[+|-] Treat all warnings as errors. --warnaserror[+|-]:<number_list> Treat a list of warnings as errors. --ruleset:<file> Specify a ruleset file that disables specific - diagnostics. + - 오류 및 경고 - +-nowarn 모든 경고를 사용하지 않도록 설정합니다. +-nowarn:<number_list> 개별 경고 목록을 사용하지 않도록 설정합니다. +-warnaserror[+|-] 모든 경고를 오류로 처리합니다. +-warnaserror[+|-]:<number_list> 경고 목록을 오류로 처리합니다. +-ruleset:<file> 특정 진단을 사용하지 않도록 설정하는 규칙 집합 파일을 + 지정합니다. -errorlog:<file>[,version=<sarif_version>] - Specify a file to log all compiler and analyzer - diagnostics in SARIF format. - sarif_version:{1|2|2.1} Default is 1. 2 and 2.1 - both mean SARIF version 2.1.0. --reportanalyzer Report additional analyzer information, such as - execution time. --skipanalyzers[+|-] Skip execution of diagnostic analyzers. + 모든 컴파일러 및 분석기 진단을 기록할 파일을 + SARIF 형식으로 지정합니다. + sarif_version:{1|2|2.1} 기본값 1. 2와 2.1은 모두 + SARIF 버전 2.1.0을 의미합니다. +-reportanalyzer 추가 분석기 정보(예: 실행 시간)를 + 보고합니다. +-skipanalyzers[+|-] 진단 분석기의 실행을 건너뜁니다. - - LANGUAGE - --define:<symbol_list> Declare global conditional compilation - symbol(s). symbol_list:name=value,... - (Short form: -d) --imports:<import_list> Declare global Imports for namespaces in - referenced metadata files. + - 언어 - +-define:<symbol_list> 전역 조건부 컴파일 기호를 + 선언합니다. symbol_list:name=value,... + (약식: -d) +-imports:<import_list> 참조된 메타데이터 파일에 있는 네임스페이스의 + 전역 가져오기를 선언합니다. import_list:namespace,... --langversion:? Display the allowed values for language version --langversion:<string> Specify language version such as - `default` (latest major version), or - `latest` (latest version, including minor versions), - or specific versions like `14` or `15.3` --optionexplicit[+|-] Require explicit declaration of variables. --optioninfer[+|-] Allow type inference of variables. --rootnamespace:<string> Specifies the root Namespace for all type - declarations. --optionstrict[+|-] Enforce strict language semantics. --optionstrict:custom Warn when strict language semantics are not - respected. --optioncompare:binary Specifies binary-style string comparisons. - This is the default. --optioncompare:text Specifies text-style string comparisons. +-langversion:? 언어 버전에 허용되는 값을 표시합니다. +-langversion:<string> 언어 버전을 + 'default'(최신 주 버전), + 'latest'(최신 버전, 부 버전 포함), + '14' 또는 '15.3' 같은 특정 버전으로 지정합니다. +-optionexplicit[+|-] 변수의 명시적 선언을 요구합니다. +-optioninfer[+|-] 변수의 형식 유추를 허용합니다. +-rootnamespace:<string> 모든 형식 선언의 루트 네임스페이스를 + 지정합니다. +-optionstrict[+|-] 엄격한 언어 의미 체계를 적용합니다. +-optionstrict:custom 엄격한 언어 의미 체계가 적용되지 않을 경우 + 경고합니다. +-optioncompare:binary 이진 스타일 문자열 비교를 지정합니다. + 기본값입니다. +-optioncompare:text 텍스트 스타일 문자열 비교를 지정합니다. - - MISCELLANEOUS - --help Display this usage message. (Short form: -?) --noconfig Do not auto-include VBC.RSP file. --nologo Do not display compiler copyright banner. --quiet Quiet output mode. --verbose Display verbose messages. --parallel[+|-] Concurrent build. --version Display the compiler version number and exit. + - 기타 - +-help 사용법 메시지를 표시합니다. (약식: -?) +-noconfig VBC.RSP 파일을 자동으로 포함하지 않습니다. +-nologo 컴파일러 저작권 배너를 표시하지 않습니다. +-quiet 자동 출력 모드입니다. +-verbose 자세한 메시지를 표시합니다. +-parallel[+|-] 동시 빌드입니다. +-version 컴파일러 버전 번호를 표시하고 종료합니다. - - ADVANCED - --baseaddress:<number> The base address for a library or module - (hex). --checksumalgorithm:<alg> Specify algorithm for calculating source file - checksum stored in PDB. Supported values are: - SHA1 or SHA256 (default). --codepage:<number> Specifies the codepage to use when opening - source files. --delaysign[+|-] Delay-sign the assembly using only the public - portion of the strong name key. --publicsign[+|-] Public-sign the assembly using only the public - portion of the strong name key. --errorreport:<string> Specifies how to handle internal compiler - errors; must be prompt, send, none, or queue - (default). --filealign:<number> Specify the alignment used for output file - sections. --highentropyva[+|-] Enable high-entropy ASLR. --keycontainer:<string> Specifies a strong name key container. --keyfile:<file> Specifies a strong name key file. --libpath:<path_list> List of directories to search for metadata - references. (Semi-colon delimited.) --main:<class> Specifies the Class or Module that contains - Sub Main. It can also be a Class that - inherits from System.Windows.Forms.Form. - (Short form: -m) --moduleassemblyname:<string> Name of the assembly which this module will - be a part of. --netcf Target the .NET Compact Framework. --nostdlib Do not reference standard libraries - (system.dll and VBC.RSP file). + - 고급 - +-baseaddress:<number> 라이브러리 또는 모듈의 기준 + 주소(16진수)입니다. +-checksumalgorithm:<alg> PDB에 저장된 소스 파일 체크섬을 계산하기 위한 + 알고리즘을 지정합니다. 지원되는 값은 + SHA1 또는 SHA256(기본값)입니다. +-codepage:<number> 소스 파일을 열 때 사용할 코드 페이지를 + 지정합니다. +-delaysign[+|-] 강력한 이름 키의 공개 부분만 사용하여 + 어셈블리 서명을 연기합니다. +-publicsign[+|-] 강력한 이름 키의 공개 부분만 사용하여 + 어셈블리에 공개 서명합니다. +-errorreport:<string> 내부 컴파일러 오류를 처리하는 방법을 + prompt, send, none 또는 queue(기본값)로 + 지정합니다. +-filealign:<number> 출력 파일 섹션에 사용되는 맞춤을 + 지정합니다. +-highentropyva[+|-] 높은 엔트로피 ASLR을 사용하도록 설정합니다. +-keycontainer:<string> 강력한 이름의 키 컨테이너를 지정합니다. +-keyfile:<file> 강력한 이름의 키 파일을 지정합니다. +-libpath:<path_list> 메타데이터 참조를 검색할 디렉터리 + 목록이며 세미콜론으로 구분됩니다. +-main:<class> Sub Main을 포함하는 클래스 또는 모듈을 + 지정합니다. System.Windows.Forms.Form에서 상속하는 + 클래스를 사용할 수도 있습니다. + (약식: -m) +-moduleassemblyname:<string> 이 모듈이 속할 어셈블리의 + 이름입니다. +-netcf .NET Compact Framework를 대상으로 지정합니다. +-nostdlib 표준 라이브러리(system.dll 및 VBC.RSP 파일)를 + 참조하지 않습니다. -pathmap:<K1>=<V1>,<K2>=<V2>,... - Specify a mapping for source path names output by - the compiler. --platform:<string> Limit which platforms this code can run on; - must be x86, x64, Itanium, arm, arm64 - AnyCPU32BitPreferred or anycpu (default). --preferreduilang Specify the preferred output language name. --nosdkpath Disable searching the default SDK path for standard library assemblies. --sdkpath:<path> Location of the .NET Framework SDK directory - (mscorlib.dll). --subsystemversion:<version> Specify subsystem version of the output PE. + 컴파일러에서 출력된 소스 경로 이름에 대한 + 매핑을 지정합니다. +-platform:<string> 이 코드를 실행할 수 있는 플랫폼을 + x86, x64, Itanium, arm, arm64, + AnyCPU32BitPreferred 또는 anycpu(기본값)로 제한합니다. +-preferreduilang 기본 출력 언어 이름을 지정합니다. +-nosdkpath 기본 SDK 경로에서 표준 라이브러리 어셈블리를 검색하지 않도록 설정합니다. +-sdkpath:<path> .NET Framework SDK 디렉터리(mscorlib.dll)의 + 위치입니다. +-subsystemversion:<version> 출력 PE의 하위 시스템 버전을 지정합니다. version:<number>[.<number>] --utf8output[+|-] Emit compiler output in UTF8 character - encoding. -@<file> Insert command-line settings from a text file --vbruntime[+|-|*] Compile with/without the default Visual Basic - runtime. --vbruntime:<file> Compile with the alternate Visual Basic - runtime in <file>. +-utf8output[+|-] 컴파일러 출력을 UTF8 문자 인코딩으로 + 내보냅니다. +@<file> 텍스트 파일에서 명령줄 설정을 삽입합니다. +-vbruntime[+|-|*] 기본 Visual Basic 런타임을 사용하거나 사용하지 않고 + 컴파일합니다. +-vbruntime:<file> <file>의 대체 Visual Basic 런타임을 사용하여 + 컴파일합니다. @@ -463,6 +463,50 @@ 형식 인수는 Nothing일 수 없습니다. + + The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + '{1}' 형식을 포함하는 '{0}' 어셈블리가 지원되지 않는 .NET Framework를 참조합니다. + {1} is the type that was loaded, {0} is the containing assembly. + + + The loaded assembly references .NET Framework, which is not supported. + 로드된 어셈블리가 지원되지 않는 .NET Framework를 참조합니다. + + + + Generator '{0}' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + 생성기 '{0}'이(가) 소스를 생성하지 못했습니다. 출력에 기여하지 않으므로 컴파일 오류가 발생할 수 있습니다. 예외의 형식은 '{1}'이고 메시지는 '{2}'입니다. + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + 생성기에서 다음 예외를 throw했습니다. +'{0}'. + {0} is the string representation of the exception that was thrown. + + + Generator failed to generate source. + 생성기가 소스를 생성하지 못했습니다. + + + + Generator '{0}' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + 생성기 '{0}'이(가) 초기화하지 못했습니다. 출력에 기여하지 않으므로 컴파일 오류가 발생할 수 있습니다. 예외의 형식은 '{1}'이고 메시지는 '{2}'입니다. + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + 생성기에서 다음 예외를 throw했습니다. +'{0}'. + {0} is the string representation of the exception that was thrown. + + + Generator failed to initialize. + 생성기가 초기화하지 못했습니다. + + Wrong number of type arguments 형식 인수 수가 잘못되었습니다. @@ -470,27 +514,27 @@ file '{0}' could not be found - {0}' 파일을 찾을 수 없습니다. + '{0}' 파일을 찾을 수 없습니다. unable to open response file '{0}' - {0}' 응답 파일을 열 수 없습니다. + '{0}' 응답 파일을 열 수 없습니다. option '{0}' requires '{1}' - {0}' 옵션을 사용하려면 '{1}'이(가) 필요합니다. + '{0}' 옵션을 사용하려면 '{1}'이(가) 필요합니다. option '{0}' can be followed only by '+' or '-' - {0}' 옵션 뒤에는 '+' 또는 '-'만 올 수 있습니다. + '{0}' 옵션 뒤에는 '+' 또는 '-'만 올 수 있습니다. the value '{1}' is invalid for option '{0}' - {1}' 값은 '{0}' 옵션에 사용할 수 없습니다. + '{1}' 값은 '{0}' 옵션에 사용할 수 없습니다. @@ -500,7 +544,7 @@ The language name '{0}' is invalid. - {0}' 언어 이름이 잘못되었습니다. + '{0}' 언어 이름이 잘못되었습니다. @@ -525,7 +569,7 @@ Algorithm '{0}' is not supported - {0}' 알고리즘은 지원되지 않습니다. + '{0}' 알고리즘은 지원되지 않습니다. @@ -545,7 +589,7 @@ source file '{0}' specified multiple times - {0}' 소스 파일을 여러 번 지정했습니다. + '{0}' 소스 파일을 여러 번 지정했습니다. @@ -555,22 +599,22 @@ can't open '{0}' for writing: {1} - {0}'을(를) 쓰기용으로 열 수 없습니다('{1}'). + '{0}'을(를) 쓰기용으로 열 수 없습니다('{1}'). code page '{0}' is invalid or not installed - {0}' 코드 페이지가 잘못되었거나 설치되어 있지 않습니다. + '{0}' 코드 페이지가 잘못되었거나 설치되어 있지 않습니다. the file '{0}' is not a text file - {0}' 파일은 텍스트 파일이 아닙니다. + '{0}' 파일은 텍스트 파일이 아닙니다. could not find library '{0}' - {0}' 라이브러리가 없습니다. + '{0}' 라이브러리가 없습니다. @@ -595,7 +639,7 @@ warning number '{0}' for the option '{1}' is either not configurable or not valid - {1}' 옵션에 대한 '{0}' 경고 번호를 구성할 수 없거나 잘못되었습니다. + '{1}' 옵션에 대한 '{0}' 경고 번호를 구성할 수 없거나 잘못되었습니다. @@ -640,7 +684,7 @@ Type '{0}' is not defined. - {0}' 형식이 정의되지 않았습니다. + '{0}' 형식이 정의되지 않았습니다. @@ -655,12 +699,12 @@ Reference required to assembly '{0}' containing the definition for event '{1}'. Add one to your project. - {1}' 이벤트에 대한 정의를 포함하는 '{0}' 어셈블리에 대한 참조를 찾을 수 없습니다. 프로젝트에 추가하세요. + '{1}' 이벤트에 대한 정의를 포함하는 '{0}' 어셈블리에 대한 참조를 찾을 수 없습니다. 프로젝트에 추가하세요. Reference required to module '{0}' containing the definition for event '{1}'. Add one to your project. - {1}' 이벤트에 대한 정의를 포함하는 '{0}' 모듈에 대한 참조를 찾을 수 없습니다. 프로젝트에 추가하세요. + '{1}' 이벤트에 대한 정의를 포함하는 '{0}' 모듈에 대한 참조를 찾을 수 없습니다. 프로젝트에 추가하세요. @@ -680,7 +724,7 @@ Inheriting from '{0}' is not valid. - {0}'에서 상속할 수 없습니다. + '{0}'에서 상속할 수 없습니다. @@ -725,7 +769,7 @@ Statement is not valid inside '{0}' block. - {0}' 블록 내부에서는 문이 유효하지 않습니다. + '{0}' 블록 내부에서는 문이 유효하지 않습니다. @@ -860,7 +904,7 @@ Too many arguments to '{0}'. - {0}'에 대한 인수가 너무 많습니다. + '{0}'에 대한 인수가 너무 많습니다. @@ -1005,7 +1049,7 @@ Label '{0}' is already defined in the current method. - {0}' 레이블이 현재 메서드에 이미 정의되었습니다. + '{0}' 레이블이 현재 메서드에 이미 정의되었습니다. @@ -1115,12 +1159,12 @@ Attribute '{0}' is not valid: Incorrect argument value. - {0}' 특성이 잘못되었습니다. 잘못된 인수 값입니다. + '{0}' 특성이 잘못되었습니다. 잘못된 인수 값입니다. Label '{0}' is not defined. - {0}' 레이블이 정의되지 않았습니다. + '{0}' 레이블이 정의되지 않았습니다. @@ -1135,7 +1179,7 @@ First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class '{0}' of '{1}' does not have an accessible 'Sub New' that can be called with no arguments. - {1}'의 기본 클래스 '{0}'에 인수 없이 호출할 수 있는 액세스 가능한 'Sub New'가 없으므로 이 'Sub New'의 첫째 문은 'MyBase.New' 또는 'MyClass.New'에 대한 호출이어야 합니다. + '{1}'의 기본 클래스 '{0}'에 인수 없이 호출할 수 있는 액세스 가능한 'Sub New'가 없으므로 이 'Sub New'의 첫째 문은 'MyBase.New' 또는 'MyClass.New'에 대한 호출이어야 합니다. @@ -1320,7 +1364,7 @@ Delegate class '{0}' has no Invoke method, so an expression of this type cannot be the target of a method call. - {0}' 대리자 클래스에는 Invoke 메서드가 없으므로 이러한 형식의 식은 메서드 호출의 대상일 수 없습니다. + '{0}' 대리자 클래스에는 Invoke 메서드가 없으므로 이러한 형식의 식은 메서드 호출의 대상일 수 없습니다. @@ -1435,7 +1479,7 @@ Type '{0}' has no constructors. - {0}' 형식에 생성자가 없습니다. + '{0}' 형식에 생성자가 없습니다. @@ -1464,7 +1508,7 @@ Class '{0}' cannot inherit from itself: {1} - {0}' 클래스는 자체 클래스({1})에서 상속할 수 없습니다. + '{0}' 클래스는 자체 클래스({1})에서 상속할 수 없습니다. @@ -1514,7 +1558,7 @@ Parameter '{0}' of '{1}' already has a matching argument. - {1}'의 '{0}' 매개 변수와 일치하는 인수가 이미 있습니다. + '{1}'의 '{0}' 매개 변수와 일치하는 인수가 이미 있습니다. @@ -1524,7 +1568,7 @@ Type character '{0}' does not match declared data type '{1}'. - {0}' 형식 문자가 선언된 '{1}' 데이터 형식과 일치하지 않습니다. + '{0}' 형식 문자가 선언된 '{1}' 데이터 형식과 일치하지 않습니다. @@ -1559,7 +1603,7 @@ Cannot update '{0}'; attribute '{1}' is missing. - {0}'을(를) 업데이트할 수 없습니다. 특성 '{1}'이(가) 없습니다. + '{0}'을(를) 업데이트할 수 없습니다. 특성 '{1}'이(가) 없습니다. @@ -1574,7 +1618,7 @@ Local variable '{0}' is already declared in the current block. - {0}' 지역 변수가 현재 블록에 이미 선언되었습니다. + '{0}' 지역 변수가 현재 블록에 이미 선언되었습니다. @@ -1596,12 +1640,12 @@ Structure '{0}' cannot contain an instance of itself: {1} - {0}' 구조체는 자체 인스턴스({1})를 포함할 수 없습니다. + '{0}' 구조체는 자체 인스턴스({1})를 포함할 수 없습니다. Interface '{0}' cannot inherit from itself: {1} - {0}' 인터페이스는 자체 인터페이스({1})에서 상속할 수 있습니다. + '{0}' 인터페이스는 자체 인터페이스({1})에서 상속할 수 있습니다. @@ -1613,7 +1657,7 @@ Constructor '{0}' cannot call itself: {1} - {0}' 생성자는 자신({1})을 호출할 수 없습니다. + '{0}' 생성자는 자신({1})을 호출할 수 없습니다. @@ -1663,12 +1707,12 @@ Cannot refer to '{0}' because it is a member of the value-typed field '{1}' of class '{2}' which has 'System.MarshalByRefObject' as a base class. - {0}'은(는) 'System.MarshalByRefObject'를 기본 클래스로 사용하는 '{2}' 클래스의 값 형식 필드 '{1}'의 멤버이므로 참조할 수 없습니다. + '{0}'은(는) 'System.MarshalByRefObject'를 기본 클래스로 사용하는 '{2}' 클래스의 값 형식 필드 '{1}'의 멤버이므로 참조할 수 없습니다. Value of type '{0}' cannot be converted to '{1}'. - {0}' 형식의 변수는 '{1}'(으)로 변환할 수 없습니다. + '{0}' 형식의 변수는 '{1}'(으)로 변환할 수 없습니다. @@ -1678,12 +1722,12 @@ Value of type '{0}' cannot be converted to '{1}' because '{2}' is not derived from '{3}'. - {2}'이(가) '{3}'에서 파생되지 않으므로 '{0}' 형식의 값을 '{1}'(으)로 변환할 수 없습니다. + '{2}'이(가) '{3}'에서 파생되지 않으므로 '{0}' 형식의 값을 '{1}'(으)로 변환할 수 없습니다. Value of type '{0}' cannot be converted to '{1}' because '{2}' is not a reference type. - {2}'이(가) 참조 형식이 아니므로 '{0}' 형식의 값을 '{1}'(으)로 변환할 수 없습니다. + '{2}'이(가) 참조 형식이 아니므로 '{0}' 형식의 값을 '{1}'(으)로 변환할 수 없습니다. @@ -1738,7 +1782,7 @@ Class '{0}' cannot be indexed because it has no default property. - {0}' 클래스는 기본 속성이 없으므로 인덱싱될 수 없습니다. + '{0}' 클래스는 기본 속성이 없으므로 인덱싱될 수 없습니다. @@ -1758,7 +1802,7 @@ Module '{0}' cannot be used as a type. - {0}' 모듈은 형식으로 사용할 수 없습니다. + '{0}' 모듈은 형식으로 사용할 수 없습니다. @@ -1803,7 +1847,7 @@ Class '{0}' must declare a 'Sub New' because its base class '{1}' does not have an accessible 'Sub New' that can be called with no arguments. - {0}' 클래스의 기본 클래스 '{1}'에는 인수 없이 호출할 수 있는 액세스 가능한 'Sub New'가 두 개 이상 있으므로 'Sub New'를 선언해야 합니다. + '{0}' 클래스의 기본 클래스 '{1}'에는 인수 없이 호출할 수 있는 액세스 가능한 'Sub New'가 두 개 이상 있으므로 'Sub New'를 선언해야 합니다. @@ -1963,7 +2007,7 @@ Operator '{0}' is not defined for types '{1}' and '{2}'. - {1}' 및 '{2}' 형식에 대한 '{0}' 연산자가 정의되지 않았습니다. + '{1}' 및 '{2}' 형식에 대한 '{0}' 연산자가 정의되지 않았습니다. @@ -1973,7 +2017,7 @@ Argument not specified for parameter '{0}' of '{1}'. - {1}'의 '{0}' 매개 변수에는 인수가 지정되어 있지 않습니다. + '{1}'의 '{0}' 매개 변수에는 인수가 지정되어 있지 않습니다. @@ -2043,7 +2087,7 @@ Operator '{0}' is not defined for type '{1}'. - {1}' 형식에 대한 '{0}' 연산자가 정의되지 않았습니다. + '{1}' 형식에 대한 '{0}' 연산자가 정의되지 않았습니다. @@ -2073,7 +2117,7 @@ Constant '{0}' cannot depend on its own value. - {0}' 상수는 자신의 값에 종속될 수 없습니다. + '{0}' 상수는 자신의 값에 종속될 수 없습니다. @@ -2138,7 +2182,7 @@ Argument matching parameter '{0}' narrows from '{1}' to '{2}'. - {0}' 매개 변수와 일치하는 인수는 '{1}'에서 '{2}'(으)로 한정됩니다. + '{0}' 매개 변수와 일치하는 인수는 '{1}'에서 '{2}'(으)로 한정됩니다. @@ -2160,12 +2204,12 @@ Property '{0}' is 'WriteOnly'. - {0}' 속성은 'WriteOnly'입니다. + '{0}' 속성은 'WriteOnly'입니다. Property '{0}' is 'ReadOnly'. - {0}' 속성이 'ReadOnly'입니다. + '{0}' 속성이 'ReadOnly'입니다. @@ -2210,12 +2254,12 @@ Attribute '{0}' cannot be applied to an assembly. - {0}' 특성을 어셈블리에 적용할 수 없습니다. + '{0}' 특성을 어셈블리에 적용할 수 없습니다. Attribute '{0}' cannot be applied to a module. - {0}' 특성을 모듈에 적용할 수 없습니다. + '{0}' 특성을 모듈에 적용할 수 없습니다. @@ -2225,7 +2269,7 @@ Default member of '{0}' is not a property. - {0}'의 기본 멤버는 속성이 아닙니다. + '{0}'의 기본 멤버는 속성이 아닙니다. @@ -2275,7 +2319,7 @@ Alias '{0}' is already declared. - {0}' 별칭이 이미 선언되었습니다. + '{0}' 별칭이 이미 선언되었습니다. @@ -2345,7 +2389,7 @@ Event '{0}' cannot be found. - {0}' 이벤트가 없습니다. + '{0}' 이벤트가 없습니다. @@ -2385,7 +2429,7 @@ Class '{0}' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): {1}. - {0}' 클래스를 'MustInherit'으로 선언하거나, 상속된 'MustOverride' 멤버인 '{1}'을(를) 재정의해야 합니다. + '{0}' 클래스를 'MustInherit'으로 선언하거나, 상속된 'MustOverride' 멤버인 '{1}'을(를) 재정의해야 합니다. @@ -2410,7 +2454,7 @@ Variable '{0}' hides a variable in an enclosing block. - {0}' 변수는 바깥쪽 블록에 있는 변수를 숨깁니다. + '{0}' 변수는 바깥쪽 블록에 있는 변수를 숨깁니다. @@ -2550,12 +2594,12 @@ Property '{0}' is of an unsupported type. - {0}' 속성은 지원되지 않는 형식입니다. + '{0}' 속성은 지원되지 않는 형식입니다. Attribute '{0}' cannot be applied to a method with optional parameters. - {0}' 특성을 선택적 매개 변수가 있는 메서드에 적용할 수 없습니다. + '{0}' 특성을 선택적 매개 변수가 있는 메서드에 적용할 수 없습니다. @@ -2585,12 +2629,12 @@ Reference required to assembly '{0}' containing the type '{1}'. Add one to your project. - {1}' 형식을 포함하는 '{0}' 어셈블리에 대한 참조를 찾을 수 없습니다. 프로젝트에 추가하세요. + '{1}' 형식을 포함하는 '{0}' 어셈블리에 대한 참조를 찾을 수 없습니다. 프로젝트에 추가하세요. Reference required to module '{0}' containing the type '{1}'. Add one to your project. - {1}' 형식을 포함하는 '{0}' 모듈에 대한 참조를 찾을 수 없습니다. 프로젝트에 추가하세요. + '{1}' 형식을 포함하는 '{0}' 모듈에 대한 참조를 찾을 수 없습니다. 프로젝트에 추가하세요. @@ -2600,7 +2644,7 @@ Field '{0}' is of an unsupported type. - {0}' 필드는 지원되지 않는 형식입니다. + '{0}' 필드는 지원되지 않는 형식입니다. @@ -2615,7 +2659,7 @@ Property or field '{0}' does not have a valid attribute type. - {0}' 속성 또는 필드의 특성 형식이 잘못되었습니다. + '{0}' 속성 또는 필드의 특성 형식이 잘못되었습니다. @@ -2625,7 +2669,7 @@ Field or property '{0}' is not found. - {0}' 속성 또는 필드를 찾을 수 없습니다. + '{0}' 속성 또는 필드를 찾을 수 없습니다. @@ -2640,12 +2684,12 @@ Class '{0}' cannot reference its nested type '{1}' in Inherits clause. - {0}' 클래스는 상속 절에서 '{1}' 중첩 형식을 참조할 수 없습니다. + '{0}' 클래스는 상속 절에서 '{1}' 중첩 형식을 참조할 수 없습니다. Class '{0}' cannot reference itself in Inherits clause. - {0}' 클래스는 상속 절에서 자신을 참조할 수 없습니다. + '{0}' 클래스는 상속 절에서 자신을 참조할 수 없습니다. @@ -2662,12 +2706,12 @@ Attribute '{0}' cannot be applied multiple times. - {0}' 특성을 여러 번 적용할 수 없습니다. + '{0}' 특성을 여러 번 적용할 수 없습니다. Attribute '{0}' in '{1}' cannot be applied multiple times. - {1}'에서 '{0}' 특성을 여러 번 적용할 수 없습니다. + '{1}'에서 '{0}' 특성을 여러 번 적용할 수 없습니다. @@ -2772,7 +2816,7 @@ Structure '{0}' cannot be indexed because it has no default property. - {0}' 구조체는 기본 속성이 없으므로 인덱싱될 수 없습니다. + '{0}' 구조체는 기본 속성이 없으므로 인덱싱될 수 없습니다. @@ -2807,7 +2851,7 @@ Variable '{0}' is already declared as a parameter of this or an enclosing lambda expression. - {0}' 변수가 이미 이 항목의 매개 변수 또는 바깥쪽 람다 식으로 선언되어 있습니다. + '{0}' 변수가 이미 이 항목의 매개 변수 또는 바깥쪽 람다 식으로 선언되어 있습니다. @@ -2817,7 +2861,7 @@ No accessible 'Main' method with an appropriate signature was found in '{0}'. - {0}'에 적절한 시그니처가 있는 액세스 가능한 'Main' 메서드가 없습니다. + '{0}'에 적절한 시그니처가 있는 액세스 가능한 'Main' 메서드가 없습니다. @@ -2827,7 +2871,7 @@ Value '{0}' cannot be converted to '{1}'. - {0}' 변수는 '{1}'(으)로 변환할 수 없습니다. + '{0}' 변수는 '{1}'(으)로 변환할 수 없습니다. @@ -2932,12 +2976,12 @@ None of the accessible 'Main' methods with the appropriate signatures found in '{0}' can be the startup method since they are all either generic or nested in generic types. - {0}'에 있는 적절한 시그니처가 포함된 액세스 가능한 'Main' 메서드는 모두 제네릭이거나 제네릭 형식에 중첩되어 있으므로 시작 메서드일 수 없습니다. + '{0}'에 있는 적절한 시그니처가 포함된 액세스 가능한 'Main' 메서드는 모두 제네릭이거나 제네릭 형식에 중첩되어 있으므로 시작 메서드일 수 없습니다. Error in project-level import '{0}' at '{1}' : {2} - {1}'에 있는 프로젝트 수준의 가져오기 '{0}'에서 오류가 발생했습니다({2}). + '{1}'에 있는 프로젝트 수준의 가져오기 '{0}'에서 오류가 발생했습니다({2}). @@ -3072,27 +3116,27 @@ Type '{0}' is not supported because it either directly or indirectly inherits from itself. - {0}' 형식은 직접 또는 간접적으로 자신에게서 상속되므로 지원되지 않습니다. + '{0}' 형식은 직접 또는 간접적으로 자신에게서 상속되므로 지원되지 않습니다. Class '{0}' must declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete. - {0}' 클래스는 기본 클래스 '{2}'의 '{1}'이(가) obsolete로 표시되어 있으므로 'Sub New'를 선언해야 합니다. + '{0}' 클래스는 기본 클래스 '{2}'의 '{1}'이(가) obsolete로 표시되어 있으므로 'Sub New'를 선언해야 합니다. Class '{0}' must declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete: '{3}'. - {0}' 클래스는 기본 클래스 '{2}'의 '{1}'이(가) obsolete로 표시되어 있으므로 'Sub New'를 선언해야 합니다('{3}'). + '{0}' 클래스는 기본 클래스 '{2}'의 '{1}'이(가) obsolete로 표시되어 있으므로 'Sub New'를 선언해야 합니다('{3}'). First statement of this 'Sub New' must be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete. - {2}'의 기본 클래스 '{1}'에 있는 '{0}'이(가) obsolete로 표시되어 있으므로 이 'Sub New'의 첫째 문은 'MyBase.New' 또는 'MyClass.New'에 대한 명시적 호출이어야 합니다. + '{2}'의 기본 클래스 '{1}'에 있는 '{0}'이(가) obsolete로 표시되어 있으므로 이 'Sub New'의 첫째 문은 'MyBase.New' 또는 'MyClass.New'에 대한 명시적 호출이어야 합니다. First statement of this 'Sub New' must be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete: '{3}'. - {2}'의 기본 클래스 '{1}'에 있는 '{0}'이(가) obsolete로 표시되어 있으므로 이 'Sub New'의 첫째 문은 'MyBase.New' 또는 'MyClass.New'에 대한 명시적 호출이어야 합니다. '{3}' + '{2}'의 기본 클래스 '{1}'에 있는 '{0}'이(가) obsolete로 표시되어 있으므로 이 'Sub New'의 첫째 문은 'MyBase.New' 또는 'MyClass.New'에 대한 명시적 호출이어야 합니다. '{3}' @@ -3107,7 +3151,7 @@ Specified access '{0}' for '{1}' does not match the access '{2}' specified on one of its other partial types. - {1}'에 지정된 '{0}' 액세스가 다른 부분 형식(Partial Type) 중 하나에 지정된 '{2}' 액세스와 일치하지 않습니다. + '{1}'에 지정된 '{0}' 액세스가 다른 부분 형식(Partial Type) 중 하나에 지정된 '{2}' 액세스와 일치하지 않습니다. @@ -3122,12 +3166,12 @@ Base class '{0}' specified for class '{1}' cannot be different from the base class '{2}' of one of its other partial types. - {1}' 클래스에 지정된 기본 클래스 '{0}'은(는) 다른 부분 형식(Partial Type) 중 하나의 기본 클래스 '{2}'과(와) 다르면 안 됩니다. + '{1}' 클래스에 지정된 기본 클래스 '{0}'은(는) 다른 부분 형식(Partial Type) 중 하나의 기본 클래스 '{2}'과(와) 다르면 안 됩니다. Type parameter name '{0}' does not match the name '{1}' of the corresponding type parameter defined on one of the other partial types of '{2}'. - {0}' 형식 매개 변수 이름이 '{2}'의 다른 부분 형식(Partial Type) 중 하나에 정의된 해당 '{1}' 형식 매개 변수의 이름과 일치하지 않습니다. + '{0}' 형식 매개 변수 이름이 '{2}'의 다른 부분 형식(Partial Type) 중 하나에 정의된 해당 '{1}' 형식 매개 변수의 이름과 일치하지 않습니다. @@ -3147,7 +3191,7 @@ Member '{0}' that matches this signature cannot be overridden because the class '{1}' contains multiple members with this same name and signature: {2} - {1}' 클래스에 이름과 시그니처가 같은 여러 멤버가 포함되어 있으므로 이 시그니처와 일치하는 '{0}' 멤버를 재정의할 수 없습니다({2}). + '{1}' 클래스에 이름과 시그니처가 같은 여러 멤버가 포함되어 있으므로 이 시그니처와 일치하는 '{0}' 멤버를 재정의할 수 없습니다({2}). @@ -3161,7 +3205,7 @@ Member '{0}.{1}' that matches this signature cannot be implemented because the interface '{2}' contains multiple members with this same name and signature: '{3}' '{4}' - {2}' 인터페이스에 이름과 시그니처가 같은 여러 멤버가 포함되어 있으므로 이 시그니처와 일치하는 '{0}.{1}' 멤버를 구현할 수 없습니다. + '{2}' 인터페이스에 이름과 시그니처가 같은 여러 멤버가 포함되어 있으므로 이 시그니처와 일치하는 '{0}.{1}' 멤버를 구현할 수 없습니다. '{3}' '{4}' @@ -3188,7 +3232,7 @@ No accessible method '{0}' has a signature compatible with delegate '{1}':{2} - {1}':{2} 대리자와 호환되는 시그니처를 포함하는 액세스 가능한 '{0}' 메서드가 없습니다. + '{1}':{2} 대리자와 호환되는 시그니처를 포함하는 액세스 가능한 '{0}' 메서드가 없습니다. @@ -3198,7 +3242,7 @@ Range variable '{0}' hides a variable in an enclosing block or a range variable previously defined in the query expression. - {0}' 범위 변수가 바깥쪽 블록의 변수를 숨기거나 이전에 쿼리 식에 정의한 범위 변수를 숨깁니다. + '{0}' 범위 변수가 바깥쪽 블록의 변수를 숨기거나 이전에 쿼리 식에 정의한 범위 변수를 숨깁니다. @@ -3208,7 +3252,7 @@ Type of '{0}' cannot be inferred from an expression containing '{0}'. - {0}'이(가) 포함된 식에서 '{0}' 형식을 유추할 수 없습니다. + '{0}'이(가) 포함된 식에서 '{0}' 형식을 유추할 수 없습니다. @@ -3248,17 +3292,17 @@ Multiple initializations of '{0}'. Fields and properties can be initialized only once in an object initializer expression. - {0}'을(를) 여러 번 초기화했습니다. 개체 이니셜라이저 식에서 필드와 속성은 한 번만 초기화할 수 있습니다. + '{0}'을(를) 여러 번 초기화했습니다. 개체 이니셜라이저 식에서 필드와 속성은 한 번만 초기화할 수 있습니다. Member '{0}' cannot be initialized in an object initializer expression because it is not a field or property. - {0}' 멤버는 필드 또는 속성이 아니므로 개체 이니셜라이저 식에서 초기화할 수 없습니다. + '{0}' 멤버는 필드 또는 속성이 아니므로 개체 이니셜라이저 식에서 초기화할 수 없습니다. Member '{0}' cannot be initialized in an object initializer expression because it is shared. - {0}' 멤버를 공유하고 있으므로 개체 이니셜라이저 식에서 초기화할 수 없습니다. + '{0}' 멤버를 공유하고 있으므로 개체 이니셜라이저 식에서 초기화할 수 없습니다. @@ -3288,7 +3332,7 @@ Unable to load module file '{0}': {1} - {0}' 모듈 파일을 로드할 수 없습니다({1}). + '{0}' 모듈 파일을 로드할 수 없습니다({1}). @@ -3298,7 +3342,7 @@ Method '{0}' cannot handle event '{1}' because they do not have a compatible signature. - {0}' 메서드에 호환되는 시그니처가 없으므로 '{1}' 이벤트를 처리할 수 없습니다. + '{0}' 메서드에 호환되는 시그니처가 없으므로 '{1}' 이벤트를 처리할 수 없습니다. @@ -3308,52 +3352,52 @@ Interface '{0}' can be implemented only once by this type. - {0}' 인터페이스는 이 형식으로 한 번만 구현할 수 있습니다. + '{0}' 인터페이스는 이 형식으로 한 번만 구현할 수 있습니다. Interface '{0}' can be implemented only once by this type, but already appears with different tuple element names, as '{1}'. - {0}' 인터페이스는 이 형식으로 한 번만 구현할 수 있지만 이미 다른 튜플 요소 이름을 사용하여 '{1}'(으)로 표시되어 있습니다. + '{0}' 인터페이스는 이 형식으로 한 번만 구현할 수 있지만 이미 다른 튜플 요소 이름을 사용하여 '{1}'(으)로 표시되어 있습니다. Interface '{0}' can be implemented only once by this type, but already appears with different tuple element names, as '{1}' (via '{2}'). - {0}' 인터페이스는 이 형식으로 한 번만 구현할 수 있지만 이미 다른 튜플 요소 이름을 사용하여 '{2}'을(를) 통해 '{1}'(으)로 표시되어 있습니다. + '{0}' 인터페이스는 이 형식으로 한 번만 구현할 수 있지만 이미 다른 튜플 요소 이름을 사용하여 '{2}'을(를) 통해 '{1}'(으)로 표시되어 있습니다. Interface '{0}' (via '{1}') can be implemented only once by this type, but already appears with different tuple element names, as '{2}'. - {0}' 인터페이스는 '{1}'을(를) 통해 이 형식으로 한 번만 구현할 수 있지만 이미 다른 튜플 요소 이름을 사용하여 '{2}'(으)로 표시되어 있습니다. + '{0}' 인터페이스는 '{1}'을(를) 통해 이 형식으로 한 번만 구현할 수 있지만 이미 다른 튜플 요소 이름을 사용하여 '{2}'(으)로 표시되어 있습니다. Interface '{0}' (via '{1}') can be implemented only once by this type, but already appears with different tuple element names, as '{2}' (via '{3}'). - {0}' 인터페이스는 '{1}'을(를) 통해 이 형식으로 한 번만 구현할 수 있지만 이미 다른 튜플 요소 이름을 사용하여 '{3}'을(를) 통해 '{2}'(으)로 표시되어 있습니다. + '{0}' 인터페이스는 '{1}'을(를) 통해 이 형식으로 한 번만 구현할 수 있지만 이미 다른 튜플 요소 이름을 사용하여 '{3}'을(를) 통해 '{2}'(으)로 표시되어 있습니다. Interface '{0}' can be inherited only once by this interface, but already appears with different tuple element names, as '{1}'. - {0}' 인터페이스는 이 인터페이스에서 한 번만 상속될 수 있지만 이미 다른 튜플 요소 이름을 사용하여 '{1}'(으)로 표시되어 있습니다. + '{0}' 인터페이스는 이 인터페이스에서 한 번만 상속될 수 있지만 이미 다른 튜플 요소 이름을 사용하여 '{1}'(으)로 표시되어 있습니다. Interface '{0}' can be inherited only once by this interface, but already appears with different tuple element names, as '{1}' (via '{2}'). - {0}' 인터페이스는 이 인터페이스에서 한 번만 상속될 수 있지만 이미 다른 튜플 요소 이름을 사용하여 '{2}'을(를) 통해 '{1}'(으)로 표시되어 있습니다. + '{0}' 인터페이스는 이 인터페이스에서 한 번만 상속될 수 있지만 이미 다른 튜플 요소 이름을 사용하여 '{2}'을(를) 통해 '{1}'(으)로 표시되어 있습니다. Interface '{0}' (via '{1}') can be inherited only once by this interface, but already appears with different tuple element names, as '{2}'. - {0}' 인터페이스는 '{1}'을(를) 통해 이 인터페이스에서 한 번만 상속될 수 있지만 이미 다른 튜플 요소 이름을 사용하여 '{2}'(으)로 표시되어 있습니다. + '{0}' 인터페이스는 '{1}'을(를) 통해 이 인터페이스에서 한 번만 상속될 수 있지만 이미 다른 튜플 요소 이름을 사용하여 '{2}'(으)로 표시되어 있습니다. Interface '{0}' (via '{1}') can be inherited only once by this interface, but already appears with different tuple element names, as '{2}' (via '{3}'). - {0}' 인터페이스는 '{1}'을(를) 통해 이 인터페이스에서 한 번만 상속될 수 있지만 이미 다른 튜플 요소 이름을 사용하여 '{3}'을(를) 통해 '{2}'(으)로 표시되어 있습니다. + '{0}' 인터페이스는 '{1}'을(를) 통해 이 인터페이스에서 한 번만 상속될 수 있지만 이미 다른 튜플 요소 이름을 사용하여 '{3}'을(를) 통해 '{2}'(으)로 표시되어 있습니다. Interface '{0}' is not implemented by this class. - {0}' 인터페이스가 이 클래스에서 구현되지 않았습니다. + '{0}' 인터페이스가 이 클래스에서 구현되지 않았습니다. @@ -3393,7 +3437,7 @@ Namespace or type '{0}' has already been imported. - {0}' 네임스페이스 또는 형식을 이미 가져왔습니다. + '{0}' 네임스페이스 또는 형식을 이미 가져왔습니다. @@ -3433,7 +3477,7 @@ Security attribute '{0}' has an invalid SecurityAction value '{1}'. - {0}' 보안 특성에 있는 SecurityAction 값('{1}')이 잘못되었습니다. + '{0}' 보안 특성에 있는 SecurityAction 값('{1}')이 잘못되었습니다. @@ -3523,7 +3567,7 @@ Operator '{0}' is not defined for types '{1}' and '{2}'. Use 'Is' operator to compare two reference types. - {1}' 및 '{2}' 형식에 대한 '{0}' 연산자가 정의되지 않았습니다. 두 참조 형식을 비교하려면 'Is' 연산자를 사용하세요. + '{1}' 및 '{2}' 형식에 대한 '{0}' 연산자가 정의되지 않았습니다. 두 참조 형식을 비교하려면 'Is' 연산자를 사용하세요. @@ -3568,7 +3612,7 @@ Import of type '{0}' from assembly or module '{1}' failed. - {1}' 어셈블리 또는 모듈에서 '{0}' 형식을 가져오지 못했습니다. + '{1}' 어셈블리 또는 모듈에서 '{0}' 형식을 가져오지 못했습니다. @@ -3583,12 +3627,12 @@ Implementing class '{0}' for interface '{1}' cannot be found. - {1}' 인터페이스에 대한 '{0}' 구현 클래스를 찾을 수 없습니다. + '{1}' 인터페이스에 대한 '{0}' 구현 클래스를 찾을 수 없습니다. Type '{0}' cannot be used as an implementing class. - {0}' 형식은 클래스를 구현하는 데 사용할 수 없습니다. + '{0}' 형식은 클래스를 구현하는 데 사용할 수 없습니다. @@ -3603,7 +3647,7 @@ Member '{0}' cannot be found in class '{1}'. This condition is usually the result of a mismatched 'Microsoft.VisualBasic.dll'. - {0}' 멤버가 '{1}' 클래스에 없습니다. 일반적으로 'Microsoft.VisualBasic.dll'이 일치하는 않은 결과로 발생하는 조건입니다. + '{0}' 멤버가 '{1}' 클래스에 없습니다. 일반적으로 'Microsoft.VisualBasic.dll'이 일치하는 않은 결과로 발생하는 조건입니다. @@ -3613,7 +3657,7 @@ Access modifier '{0}' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level. - {0}' 액세스 한정자가 잘못되었습니다. 'Get' 및 'Set'의 액세스 한정자는 속성 액세스 수준보다 제한적이어야 합니다. + '{0}' 액세스 한정자가 잘못되었습니다. 'Get' 및 'Set'의 액세스 한정자는 속성 액세스 수준보다 제한적이어야 합니다. @@ -3658,7 +3702,7 @@ Implementing class '{0}' for interface '{1}' is not accessible in this context because it is '{2}'. - {1}' 인터페이스의 '{0}' 구현 클래스는 '{2}'이므로 이 컨텍스트에서 액세스할 수 없습니다. + '{1}' 인터페이스의 '{0}' 구현 클래스는 '{2}'이므로 이 컨텍스트에서 액세스할 수 없습니다. @@ -3808,7 +3852,7 @@ Method '{0}' does not have a signature compatible with delegate '{1}'. - {0}' 메서드에 '{1}' 대리자와 호환되는 시그니처가 없습니다. + '{0}' 메서드에 '{1}' 대리자와 호환되는 시그니처가 없습니다. @@ -3823,7 +3867,7 @@ Duplicate XML attribute '{0}'. - {0}' XML 특성이 중복되었습니다. + '{0}' XML 특성이 중복되었습니다. @@ -3983,7 +4027,7 @@ Prefix '{0}' cannot be bound to namespace name reserved for '{1}'. - {0}' 접두사는 '{1}'에 사용하도록 예약된 네임스페이스 이름에 바인딩할 수 없습니다. + '{0}' 접두사는 '{1}'에 사용하도록 예약된 네임스페이스 이름에 바인딩할 수 없습니다. @@ -4013,12 +4057,12 @@ Unable to open Win32 manifest file '{0}' : {1} - {0}' Win32 매니페스트 파일을 열 수 없습니다({1}). + '{0}' Win32 매니페스트 파일을 열 수 없습니다({1}). Cannot convert '{0}' to '{1}'. You can use the 'Value' property to get the string value of the first element of '{2}'. - {0}'을(를) '{1}'(으)로 변환할 수 없습니다. 'Value' 속성을 사용하여 '{2}'의 첫 번째 요소의 문자열 값을 가져올 수 있습니다. + '{0}'을(를) '{1}'(으)로 변환할 수 없습니다. 'Value' 속성을 사용하여 '{2}'의 첫 번째 요소의 문자열 값을 가져올 수 있습니다. @@ -4028,12 +4072,12 @@ Value of type '{0}' cannot be converted to '{1}'. You can use the 'Value' property to get the string value of the first element of '{2}'. - {0}' 형식의 값을 '{1}'(으)로 변환할 수 없습니다. 'Value' 속성을 사용하여 '{2}'의 첫 번째 요소의 문자열 값을 가져올 수 있습니다. + '{0}' 형식의 값을 '{1}'(으)로 변환할 수 없습니다. 'Value' 속성을 사용하여 '{2}'의 첫 번째 요소의 문자열 값을 가져올 수 있습니다. Operator '{0}' is not defined for types '{1}' and '{2}'. You can use the 'Value' property to get the string value of the first element of '{3}'. - {1}' 및 '{2}' 형식에 대한 '{0}' 연산자가 정의되지 않았습니다. 'Value' 속성을 사용하여 첫 번째 '{3}' 요소의 문자열 값을 가져올 수 있습니다. + '{1}' 및 '{2}' 형식에 대한 '{0}' 연산자가 정의되지 않았습니다. 'Value' 속성을 사용하여 첫 번째 '{3}' 요소의 문자열 값을 가져올 수 있습니다. @@ -4043,7 +4087,7 @@ The value '{0}' is not a valid subsystem version. The version must be 6.02 or greater for ARM or AppContainerExe, and 4.00 or greater otherwise. - {0}' 값이 유효한 하위 시스템 버전이 아닙니다. 버전은 ARM 또는 AppContainerExe의 경우 6.02 이상이어야 하고, 그 외의 경우 4.00 이상이어야 합니다. + '{0}' 값이 유효한 하위 시스템 버전이 아닙니다. 버전은 ARM 또는 AppContainerExe의 경우 6.02 이상이어야 하고, 그 외의 경우 4.00 이상이어야 합니다. @@ -4073,7 +4117,7 @@ Expression of type '{0}' cannot be converted to 'Object' or 'ValueType'. - {0}' 형식의 식은 'Object' 또는 'ValueType'으로 변환할 수 없습니다. + '{0}' 형식의 식은 'Object' 또는 'ValueType'으로 변환할 수 없습니다. @@ -4093,7 +4137,7 @@ Class '{0}' has no accessible 'Sub New' and cannot be inherited. - {0}' 클래스에 액세스 가능한 'Sub New'가 없으므로 상속할 수 없습니다. + '{0}' 클래스에 액세스 가능한 'Sub New'가 없으므로 상속할 수 없습니다. @@ -4103,7 +4147,7 @@ Static local variable '{0}' is already declared. - {0}' static 지역 변수가 이미 선언되었습니다. + '{0}' static 지역 변수가 이미 선언되었습니다. @@ -4183,7 +4227,7 @@ Type '{0}' in assembly '{1}' has been forwarded to assembly '{2}'. Either a reference to '{2}' is missing from your project or the type '{0}' is missing from assembly '{2}'. - {1}' 어셈블리의 '{0}' 형식이 '{2}' 어셈블리로 전달되었습니다. 프로젝트에 '{2}'에 대한 참조가 없거나 '{2}' 어셈블리에 '{0}' 형식이 없습니다. + '{1}' 어셈블리의 '{0}' 형식이 '{2}' 어셈블리로 전달되었습니다. 프로젝트에 '{2}'에 대한 참조가 없거나 '{2}' 어셈블리에 '{0}' 형식이 없습니다. @@ -4213,7 +4257,7 @@ Expression of type '{0}' can never be of type '{1}'. - {0}' 형식의 식은 '{1}' 형식일 수 없습니다. + '{0}' 형식의 식은 '{1}' 형식일 수 없습니다. @@ -4228,12 +4272,12 @@ Method '{0}' cannot be declared 'Partial' because only one method '{1}' can be marked 'Partial'. - {1}' 메서드 하나만 'Partial'로 표시할 수 있으므로 '{0}' 메서드는 'Partial'로 선언할 수 없습니다. + '{1}' 메서드 하나만 'Partial'로 표시할 수 있으므로 '{0}' 메서드는 'Partial'로 선언할 수 없습니다. Method '{0}' cannot implement partial method '{1}' because '{2}' already implements it. Only one method can implement a partial method. - {2}'에서 이미 '{1}' 부분 메서드(Partial Method)를 구현했으므로 '{0}' 메서드에서 부분 메서드를 구현할 수 없습니다. 메서드 하나만 부분 메서드를 구현할 수 있습니다. + '{2}'에서 이미 '{1}' 부분 메서드(Partial Method)를 구현했으므로 '{0}' 메서드에서 부분 메서드를 구현할 수 없습니다. 메서드 하나만 부분 메서드를 구현할 수 있습니다. @@ -4248,12 +4292,12 @@ Method '{0}' does not have the same generic constraints as the partial method '{1}'. - {0}' 메서드에는 '{1}' 부분 메서드(Partial Method)과 같은 제네릭 제약 조건이 없습니다. + '{0}' 메서드에는 '{1}' 부분 메서드(Partial Method)과 같은 제네릭 제약 조건이 없습니다. Partial method '{0}' cannot use the 'Implements' keyword. - {0}' 부분 메서드(Partial Method)에서 'Implements' 키워드를 사용할 수 없습니다. + '{0}' 부분 메서드(Partial Method)에서 'Implements' 키워드를 사용할 수 없습니다. @@ -4263,17 +4307,17 @@ Method '{0}' must be declared 'Private' in order to implement partial method '{1}'. - {1}' 부분 메서드(Partial Method)를 구현하려면 '{0}' 메서드를 'Private'으로 선언해야 합니다. + '{1}' 부분 메서드(Partial Method)를 구현하려면 '{0}' 메서드를 'Private'으로 선언해야 합니다. Parameter name '{0}' does not match the name of the corresponding parameter, '{1}', defined on the partial method declaration '{2}'. - {0}' 매개 변수 이름이 '{2}' 부분 메서드(Partial Method) 선언에 정의된 해당 '{1}' 매개 변수의 이름과 일치하지 않습니다. + '{0}' 매개 변수 이름이 '{2}' 부분 메서드(Partial Method) 선언에 정의된 해당 '{1}' 매개 변수의 이름과 일치하지 않습니다. Name of type parameter '{0}' does not match '{1}', the corresponding type parameter defined on the partial method declaration '{2}'. - {0}' 형식 매개 변수의 이름이 '{2}' 부분 메서드(Partial Method) 선언에 정의된 해당 '{1}' 형식 매개 변수와 일치하지 않습니다. + '{0}' 형식 매개 변수의 이름이 '{2}' 부분 메서드(Partial Method) 선언에 정의된 해당 '{1}' 형식 매개 변수와 일치하지 않습니다. @@ -4313,7 +4357,7 @@ Unable to open resource file '{0}': {1} - {0}' 리소스 파일을 열 수 없습니다({1}). + '{0}' 리소스 파일을 열 수 없습니다({1}). @@ -4328,17 +4372,17 @@ Project '{0}' makes an indirect reference to assembly '{1}', which contains '{2}'. Add a file reference to '{3}' to your project. - {0}' 프로젝트는 '{2}'을(를) 포함하는 '{1}' 어셈블리에 대한 간접 참조를 만듭니다. '{3}'에 대한 파일 참조를 프로젝트에 추가하세요. + '{0}' 프로젝트는 '{2}'을(를) 포함하는 '{1}' 어셈블리에 대한 간접 참조를 만듭니다. '{3}'에 대한 파일 참조를 프로젝트에 추가하세요. Type '{0}' cannot be used in an attribute because it is not declared 'Public'. - {0}' 형식은 'Public'으로 선언되지 않았으므로 특성에 사용할 수 없습니다. + '{0}' 형식은 'Public'으로 선언되지 않았으므로 특성에 사용할 수 없습니다. Type '{0}' cannot be used in an attribute because its container '{1}' is not declared 'Public'. - {0}' 형식의 컨테이너 '{1}'이(가) 'Public'으로 선언되지 않았으므로 이 형식을 특성에 사용할 수 없습니다. + '{0}' 형식의 컨테이너 '{1}'이(가) 'Public'으로 선언되지 않았으므로 이 형식을 특성에 사용할 수 없습니다. @@ -4403,7 +4447,7 @@ Local variable '{0}' cannot be referred to before it is declared. - {0}' 지역 변수를 참조하려면 이 변수를 먼저 선언해야 합니다. + '{0}' 지역 변수를 참조하려면 이 변수를 먼저 선언해야 합니다. @@ -4428,7 +4472,7 @@ Delegate '{0}' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. - {0}' 대리자에서는 'AddressOf' 식 또는 람다 식을 해당 생성자의 유일한 인수로 지정해야 합니다. + '{0}' 대리자에서는 'AddressOf' 식 또는 람다 식을 해당 생성자의 유일한 인수로 지정해야 합니다. @@ -4478,7 +4522,7 @@ Parameter '{0}' in '{1}' already has a matching omitted argument. - {1}'의 '{0}' 매개 변수에 일치하는 생략된 인수가 이미 있습니다. + '{1}'의 '{0}' 매개 변수에 일치하는 생략된 인수가 이미 있습니다. @@ -4523,7 +4567,7 @@ Class '{0}' must declare a 'Sub New' because its base class '{1}' has more than one accessible 'Sub New' that can be called with no arguments. - {0}' 클래스의 기본 클래스 '{1}'에는 인수 없이 호출할 수 있는 액세스 가능한 'Sub New'가 두 개 이상 있으므로 'Sub New'를 선언해야 합니다. + '{0}' 클래스의 기본 클래스 '{1}'에는 인수 없이 호출할 수 있는 액세스 가능한 'Sub New'가 두 개 이상 있으므로 'Sub New'를 선언해야 합니다. @@ -4533,7 +4577,7 @@ First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class '{0}' of '{1}' has more than one accessible 'Sub New' that can be called with no arguments. - {1}'의 기본 클래스 '{0}'에는 인수 없이 호출할 수 있는 액세스 가능한 'Sub New'가 두 개 이상 있으므로 이 'Sub New'의 첫째 문은 'MyBase.New' 또는 'MyClass.New'에 대한 호출이어야 합니다. + '{1}'의 기본 클래스 '{0}'에는 인수 없이 호출할 수 있는 액세스 가능한 'Sub New'가 두 개 이상 있으므로 이 'Sub New'의 첫째 문은 'MyBase.New' 또는 'MyClass.New'에 대한 호출이어야 합니다. @@ -4543,7 +4587,7 @@ The '{0}' keyword is used to overload inherited members; do not use the '{0}' keyword when overloading 'Sub New'. - {0}' 키워드를 사용하여 상속된 멤버를 오버로드했습니다. 'Sub New'를 오버로드할 때에는 '{0}' 키워드를 사용하지 마세요. + '{0}' 키워드를 사용하여 상속된 멤버를 오버로드했습니다. 'Sub New'를 오버로드할 때에는 '{0}' 키워드를 사용하지 마세요. @@ -4553,17 +4597,17 @@ Too few type arguments to '{0}'. - {0}'에 대한 형식 인수가 너무 적습니다. + '{0}'에 대한 형식 인수가 너무 적습니다. Too many type arguments to '{0}'. - {0}'에 대한 형식 인수가 너무 많습니다. + '{0}'에 대한 형식 인수가 너무 많습니다. Type argument '{0}' does not inherit from or implement the constraint type '{1}'. - {0}' 형식 인수는 '{1}' 제약 조건 형식에서 상속되지 않거나 이를 구현하지 않습니다. + '{0}' 형식 인수는 '{1}' 제약 조건 형식에서 상속되지 않거나 이를 구현하지 않습니다. @@ -4578,7 +4622,7 @@ Type parameter '{0}' can only have one constraint that is a class. - {0}' 형식 매개 변수는 제약 조건(클래스)을 하나만 포함할 수 있습니다. + '{0}' 형식 매개 변수는 제약 조건(클래스)을 하나만 포함할 수 있습니다. @@ -4593,7 +4637,7 @@ Type parameter '{0}' for '{1}' cannot be inferred. - {1}'의 형식 매개 변수 '{0}'을(를) 유추할 수 없습니다. + '{1}'의 형식 매개 변수 '{0}'을(를) 유추할 수 없습니다. @@ -4668,7 +4712,7 @@ Cannot implement interface '{0}' because its implementation could conflict with the implementation of another implemented interface '{1}' for some type arguments. - {0}' 인터페이스 구현이 일부 형식 인수에 대해 구현된 다른 인터페이스 '{1}'의 구현과 충돌할 수 있으므로 이 인터페이스를 구현할 수 없습니다. + '{0}' 인터페이스 구현이 일부 형식 인수에 대해 구현된 다른 인터페이스 '{1}'의 구현과 충돌할 수 있으므로 이 인터페이스를 구현할 수 없습니다. @@ -4713,7 +4757,7 @@ Type argument '{0}' is declared 'MustInherit' and does not satisfy the 'New' constraint for type parameter '{1}'. - {0}' 형식 인수는 'MustInherit'으로 선언되었으며 형식 매개 변수 '{1}'에 대한 'New' 제약 조건을 만족하지 않습니다. + '{0}' 형식 인수는 'MustInherit'으로 선언되었으며 형식 매개 변수 '{1}'에 대한 'New' 제약 조건을 만족하지 않습니다. @@ -4818,12 +4862,12 @@ Type argument '{0}' does not satisfy the 'Structure' constraint for type parameter '{1}'. - {0}' 형식 인수는 '{1}' 형식 매개 변수에 대한 'Structure' 제약 조건을 만족하지 않습니다. + '{0}' 형식 인수는 '{1}' 형식 매개 변수에 대한 'Structure' 제약 조건을 만족하지 않습니다. Type argument '{0}' does not satisfy the 'Class' constraint for type parameter '{1}'. - {0}' 형식 인수는 '{1}' 형식 매개 변수에 대한 'Class' 제약 조건을 만족하지 않습니다. + '{0}' 형식 인수는 '{1}' 형식 매개 변수에 대한 'Class' 제약 조건을 만족하지 않습니다. @@ -4860,7 +4904,7 @@ Type parameter '{0}' cannot be constrained to itself: {1} - {0}' 형식 매개 변수는 자신의 제약을 받을 수 없습니다({1}). + '{0}' 형식 매개 변수는 자신의 제약을 받을 수 없습니다({1}). @@ -4880,37 +4924,37 @@ Cannot inherit interface '{0}' because it could be identical to interface '{1}' for some type arguments. - {0}' 인터페이스가 일부 형식 인수에 대해 '{1}' 인터페이스와 동일할 수 있으므로 인터페이스를 상속할 수 없습니다. + '{0}' 인터페이스가 일부 형식 인수에 대해 '{1}' 인터페이스와 동일할 수 있으므로 인터페이스를 상속할 수 없습니다. Cannot inherit interface '{0}' because the interface '{1}' from which it inherits could be identical to interface '{2}' for some type arguments. - {0}' 인터페이스를 상속할 수 없습니다. 이 인터페이스가 상속된 '{1}' 인터페이스가 일부 형식 인수에 대해 '{2}' 인터페이스와 동일할 수 있습니다. + '{0}' 인터페이스를 상속할 수 없습니다. 이 인터페이스가 상속된 '{1}' 인터페이스가 일부 형식 인수에 대해 '{2}' 인터페이스와 동일할 수 있습니다. Cannot inherit interface '{0}' because the interface '{1}' from which it inherits could be identical to interface '{2}' from which the interface '{3}' inherits for some type arguments. - {0}' 인터페이스를 상속할 수 없습니다. 이 인터페이스가 상속된 '{1}' 인터페이스가 일부 형식 인수에 대해 '{3}' 인터페이스가 상속된 '{2}' 인터페이스와 동일할 수 있습니다. + '{0}' 인터페이스를 상속할 수 없습니다. 이 인터페이스가 상속된 '{1}' 인터페이스가 일부 형식 인수에 대해 '{3}' 인터페이스가 상속된 '{2}' 인터페이스와 동일할 수 있습니다. Cannot inherit interface '{0}' because it could be identical to interface '{1}' from which the interface '{2}' inherits for some type arguments. - {0}' 인터페이스를 상속할 수 없습니다. 이 인터페이스가 일부 형식 인수에 대해 '{2}' 인터페이스가 상속된 '{1}' 인터페이스와 동일할 수 있습니다. + '{0}' 인터페이스를 상속할 수 없습니다. 이 인터페이스가 일부 형식 인수에 대해 '{2}' 인터페이스가 상속된 '{1}' 인터페이스와 동일할 수 있습니다. Cannot implement interface '{0}' because the interface '{1}' from which it inherits could be identical to implemented interface '{2}' for some type arguments. - {0}' 인터페이스를 구현할 수 없습니다. 이 인터페이스가 구현된 '{1}' 인터페이스가 일부 형식 인수에 대해 '{2}' 인터페이스와 동일할 수 있습니다. + '{0}' 인터페이스를 구현할 수 없습니다. 이 인터페이스가 구현된 '{1}' 인터페이스가 일부 형식 인수에 대해 '{2}' 인터페이스와 동일할 수 있습니다. Cannot implement interface '{0}' because the interface '{1}' from which it inherits could be identical to interface '{2}' from which the implemented interface '{3}' inherits for some type arguments. - {0}' 인터페이스를 구현할 수 없습니다. 이 인터페이스가 상속된 '{1}' 인터페이스가 일부 형식 인수에 대해 구현된 '{3}' 인터페이스가 상속된 '{2}' 인터페이스와 동일할 수 있습니다. + '{0}' 인터페이스를 구현할 수 없습니다. 이 인터페이스가 상속된 '{1}' 인터페이스가 일부 형식 인수에 대해 구현된 '{3}' 인터페이스가 상속된 '{2}' 인터페이스와 동일할 수 있습니다. Cannot implement interface '{0}' because it could be identical to interface '{1}' from which the implemented interface '{2}' inherits for some type arguments. - {0}' 인터페이스를 구현할 수 없습니다. 이 인터페이스가 일부 형식 인수에 대해 구현된 '{2}' 인터페이스가 상속된 '{1}' 인터페이스와 동일할 수 있습니다. + '{0}' 인터페이스를 구현할 수 없습니다. 이 인터페이스가 일부 형식 인수에 대해 구현된 '{2}' 인터페이스가 상속된 '{1}' 인터페이스와 동일할 수 있습니다. @@ -4965,7 +5009,7 @@ Conflict between the default property and the 'DefaultMemberAttribute' defined on '{0}'. - {0}'에 정의된 'DefaultMemberAttribute'와 기본 속성이 충돌합니다. + '{0}'에 정의된 'DefaultMemberAttribute'와 기본 속성이 충돌합니다. @@ -5055,12 +5099,12 @@ '{0}' parameters cannot be declared 'ParamArray'. - '{0} 매개 변수는 'ParamArray'로 선언할 수 없습니다. + '{0}' 매개 변수는 'ParamArray'로 선언할 수 없습니다. '{0}' parameters cannot be declared 'Optional'. - '{0} 매개 변수는 'Optional'로 선언할 수 없습니다. + '{0}' 매개 변수는 'Optional'로 선언할 수 없습니다. @@ -5080,17 +5124,17 @@ Operator '{0}' must have one parameter. - {0}' 연산자에는 매개 변수를 한 개만 사용할 수 있습니다. + '{0}' 연산자에는 매개 변수를 한 개만 사용할 수 있습니다. Operator '{0}' must have two parameters. - {0}' 연산자에는 두 가지 매개 변수를 사용해야 합니다. + '{0}' 연산자에는 두 가지 매개 변수를 사용해야 합니다. Operator '{0}' must have either one or two parameters. - {0}' 연산자에는 매개 변수를 한 개 또는 두 개만 사용할 수 있습니다. + '{0}' 연산자에는 매개 변수를 한 개 또는 두 개만 사용할 수 있습니다. @@ -5125,7 +5169,7 @@ Operator '{0}' must have a return type of Boolean. - {0}' 연산자의 반환 형식은 Boolean이어야 합니다. + '{0}' 연산자의 반환 형식은 Boolean이어야 합니다. @@ -5180,37 +5224,37 @@ Return and parameter types of '{0}' must be '{1}' to be used in a '{2}' expression. - {0}'의 반환 및 매개 변수 형식은 '{2}' 식에서 사용할 '{1}'이어야 합니다. + '{0}'의 반환 및 매개 변수 형식은 '{2}' 식에서 사용할 '{1}'이어야 합니다. Type '{0}' must define operator '{1}' to be used in a '{2}' expression. - {0}' 형식은 '{2}' 식에서 사용할 '{1}' 연산자를 정의해야 합니다. + '{0}' 형식은 '{2}' 식에서 사용할 '{1}' 연산자를 정의해야 합니다. Cannot copy the value of 'ByRef' parameter '{0}' back to the matching argument because type '{1}' cannot be converted to type '{2}'. - {1}' 형식은 '{2}' 형식으로 변환할 수 없으므로 'ByRef' 매개 변수 '{0}'의 값을 해당 인수에 다시 복사할 수 없습니다. + '{1}' 형식은 '{2}' 형식으로 변환할 수 없으므로 'ByRef' 매개 변수 '{0}'의 값을 해당 인수에 다시 복사할 수 없습니다. Type '{0}' must define operator '{1}' to be used in a 'For' statement. - {0}' 형식은 'For' 문에서 사용할 '{1}' 연산자를 정의해야 합니다. + '{0}' 형식은 'For' 문에서 사용할 '{1}' 연산자를 정의해야 합니다. Return and parameter types of '{0}' must be '{1}' to be used in a 'For' statement. - {0}'의 반환 및 매개 변수 형식은 'For' 문에서 사용할 '{1}'이어야 합니다. + '{0}'의 반환 및 매개 변수 형식은 'For' 문에서 사용할 '{1}'이어야 합니다. Parameter types of '{0}' must be '{1}' to be used in a 'For' statement. - {0}'의 매개 변수 형식은 'For' 문에서 사용할 '{1}'이어야 합니다. + '{0}'의 매개 변수 형식은 'For' 문에서 사용할 '{1}'이어야 합니다. Operator '{0}' must have a second parameter of type 'Integer' or 'Integer?'. - {0}' 연산자의 두 번째 매개 변수 형식은 'Integer' 또는 'Integer?'여야 합니다. + '{0}' 연산자의 두 번째 매개 변수 형식은 'Integer' 또는 'Integer?'여야 합니다. @@ -5220,7 +5264,7 @@ Type '{0}' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'. - {0}' 형식을 'Null 허용' 또는 null 허용 한정자 '?'와 함께 사용하려면 해당 형식이 'Structure'의 제약을 받는 형식 인수이거나 값 형식이어야 합니다. + '{0}' 형식을 'Null 허용' 또는 null 허용 한정자 '?'와 함께 사용하려면 해당 형식이 'Structure'의 제약을 받는 형식 인수이거나 값 형식이어야 합니다. @@ -5275,7 +5319,7 @@ Requested operation is not available because the runtime library function '{0}' is not defined. - {0}' 런타임 라이브러리 함수가 정의되어 있지 않아 요청한 작업을 수행할 수 없습니다. + '{0}' 런타임 라이브러리 함수가 정의되어 있지 않아 요청한 작업을 수행할 수 없습니다. @@ -5345,7 +5389,7 @@ Implicit variable '{0}' is invalid because of '{1}'. - {0}' 암시적 변수가 '{1}' 때문에 잘못되었습니다. + '{0}' 암시적 변수가 '{1}' 때문에 잘못되었습니다. @@ -5450,7 +5494,7 @@ Anonymous type member property '{0}' cannot be used to infer the type of another member property because the type of '{0}' is not yet established. - {0}' 형식이 아직 설정되지 않아 다른 멤버 속성의 형식을 유추하는 데 익명 형식 멤버 속성 '{0}'을(를) 사용할 수 없습니다. + '{0}' 형식이 아직 설정되지 않아 다른 멤버 속성의 형식을 유추하는 데 익명 형식 멤버 속성 '{0}'을(를) 사용할 수 없습니다. @@ -5502,12 +5546,12 @@ Parameter '{0}' already has a matching omitted argument. - {0}' 매개 변수에 일치하는 생략된 인수가 이미 있습니다. + '{0}' 매개 변수에 일치하는 생략된 인수가 이미 있습니다. Parameter '{0}' already has a matching argument. - {0}' 매개 변수에 일치하는 인수가 이미 있습니다. + '{0}' 매개 변수에 일치하는 인수가 이미 있습니다. @@ -5517,7 +5561,7 @@ Argument not specified for parameter '{0}'. - {0}' 매개 변수에는 인수가 지정되어 있지 않습니다. + '{0}' 매개 변수에는 인수가 지정되어 있지 않습니다. @@ -5549,17 +5593,17 @@ Too many arguments to extension method '{0}' defined in '{1}'. - {1}'에 정의된 확장 메서드 '{0}'의 인수가 너무 많습니다. + '{1}'에 정의된 확장 메서드 '{0}'의 인수가 너무 많습니다. Parameter '{0}' in extension method '{1}' defined in '{2}' already has a matching omitted argument. - {2}'에 정의된 확장 메서드 '{1}'의 '{0}' 매개 변수에는 일치하는 생략된 인수가 이미 있습니다. + '{2}'에 정의된 확장 메서드 '{1}'의 '{0}' 매개 변수에는 일치하는 생략된 인수가 이미 있습니다. Parameter '{0}' of extension method '{1}' defined in '{2}' already has a matching argument. - {2}'에 정의된 확장 메서드 '{1}'의 '{0}' 매개 변수에는 일치하는 인수가 이미 있습니다. + '{2}'에 정의된 확장 메서드 '{1}'의 '{0}' 매개 변수에는 일치하는 인수가 이미 있습니다. @@ -5569,22 +5613,22 @@ Argument not specified for parameter '{0}' of extension method '{1}' defined in '{2}'. - {2}'에 정의된 '{1}' 확장 메서드의 '{0}' 매개 변수에는 인수가 지정되어 있지 않습니다. + '{2}'에 정의된 '{1}' 확장 메서드의 '{0}' 매개 변수에는 인수가 지정되어 있지 않습니다. Type parameter '{0}' for extension method '{1}' defined in '{2}' cannot be inferred. - {2}'에 정의된 확장 메서드 '{1}'의 형식 매개 변수 '{0}'을(를) 유추할 수 없습니다. + '{2}'에 정의된 확장 메서드 '{1}'의 형식 매개 변수 '{0}'을(를) 유추할 수 없습니다. Too few type arguments to extension method '{0}' defined in '{1}'. - {1}'에 정의된 확장 메서드 '{0}'의 인수가 너무 적습니다. + '{1}'에 정의된 확장 메서드 '{0}'의 인수가 너무 적습니다. Too many type arguments to extension method '{0}' defined in '{1}'. - {1}'에 정의된 확장 메서드 '{0}'의 형식 인수가 너무 많습니다. + '{1}'에 정의된 확장 메서드 '{0}'의 형식 인수가 너무 많습니다. @@ -5594,7 +5638,7 @@ Expression of type '{0}' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider. - {0}' 형식의 식은 쿼리할 수 없습니다. LINQ 공급자에 대한 네임스페이스 가져오기 및/또는 어셈블리 참조가 있는지 확인하세요. + '{0}' 형식의 식은 쿼리할 수 없습니다. LINQ 공급자에 대한 네임스페이스 가져오기 및/또는 어셈블리 참조가 있는지 확인하세요. @@ -5624,7 +5668,7 @@ Range variable '{0}' is already declared. - {0}' 범위 변수가 이미 선언되었습니다. + '{0}' 범위 변수가 이미 선언되었습니다. @@ -5664,12 +5708,12 @@ Name '{0}' is either not declared or not in the current scope. - {0}' 이름이 선언되지 않았거나 현재 범위에 없습니다. + '{0}' 이름이 선언되지 않았거나 현재 범위에 없습니다. Return type of nested function matching parameter '{0}' narrows from '{1}' to '{2}'. - {0}' 매개 변수와 일치하는 중첩된 함수의 반환 형식이 '{1}'에서 '{2}'(으)로 축소 변환됩니다. + '{0}' 매개 변수와 일치하는 중첩된 함수의 반환 형식이 '{1}'에서 '{2}'(으)로 축소 변환됩니다. @@ -5719,17 +5763,17 @@ Lambda expression cannot be converted to '{0}' because '{0}' is not a delegate type. - {0}'이(가) 대리자 형식이 아니므로 람다 식을 '{0}'(으)로 변환할 수 없습니다. + '{0}'이(가) 대리자 형식이 아니므로 람다 식을 '{0}'(으)로 변환할 수 없습니다. Lambda expression cannot be converted to '{0}' because type '{0}' is declared 'MustInherit' and cannot be created. - {0}' 형식이 'MustInherit'으로 선언되어 있어 만들 수 없으므로 람다 식을 '{0}'(으)로 변환할 수 없습니다. + '{0}' 형식이 'MustInherit'으로 선언되어 있어 만들 수 없으므로 람다 식을 '{0}'(으)로 변환할 수 없습니다. A nullable type cannot be inferred for variable '{0}'. - {0}' 변수에 대해 null 허용 형식을 유추할 수 없습니다. + '{0}' 변수에 대해 null 허용 형식을 유추할 수 없습니다. @@ -5749,7 +5793,7 @@ Range variable '{0}' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression. - {0}' 범위 변수가 바깥쪽 블록의 변수, 이전에 정의한 범위 변수 또는 쿼리 식에 암시적으로 선언한 변수를 숨깁니다. + '{0}' 범위 변수가 바깥쪽 블록의 변수, 이전에 정의한 범위 변수 또는 쿼리 식에 암시적으로 선언한 변수를 숨깁니다. @@ -5919,12 +5963,12 @@ Extension Method '{0}' defined in '{2}' does not have a signature compatible with delegate '{1}'. - {2}'에 정의된 '{0}' 확장 메서드에 '{1}' 대리자와 호환되는 시그니처가 없습니다. + '{2}'에 정의된 '{0}' 확장 메서드에 '{1}' 대리자와 호환되는 시그니처가 없습니다. Argument matching parameter '{0}' narrows to '{1}'. - {0}' 매개 변수와 일치하는 인수는 '{1}'(으)로 한정됩니다. + '{0}' 매개 변수와 일치하는 인수는 '{1}'(으)로 한정됩니다. @@ -5956,7 +6000,7 @@ Extension method '{0}' defined in '{1}' is not generic (or has no free type parameters) and so cannot have type arguments. - {1}'에 정의된 확장 메서드 '{0}'은(는) 제네릭이 아니거나 형식이 자유로운 매개 변수를 포함하지 않으므로 형식 인수를 사용할 수 없습니다. + '{1}'에 정의된 확장 메서드 '{0}'은(는) 제네릭이 아니거나 형식이 자유로운 매개 변수를 포함하지 않으므로 형식 인수를 사용할 수 없습니다. @@ -5976,12 +6020,12 @@ Type '{0}' cannot be embedded because it has generic argument. Consider disabling the embedding of interop types. - {0}' 형식에 제네릭 인수가 있기 때문에 이 형식을 포함할 수 없습니다. interop 형식을 포함하지 않도록 설정하세요. + '{0}' 형식에 제네릭 인수가 있기 때문에 이 형식을 포함할 수 없습니다. interop 형식을 포함하지 않도록 설정하세요. Type '{0}' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. - {0}' 형식에 포함된 interop 형식인 제네릭 형식 인수가 있기 때문에 이 형식을 다른 어셈블리에서 사용할 수 없습니다. + '{0}' 형식에 포함된 interop 형식인 제네릭 형식 인수가 있기 때문에 이 형식을 다른 어셈블리에서 사용할 수 없습니다. @@ -6056,7 +6100,7 @@ Possible problem detected while building assembly '{0}': {1} - {0}' 어셈블리를 빌드하는 동안 발생 가능한 문제가 발견되었습니다({1}). + '{0}' 어셈블리를 빌드하는 동안 발생 가능한 문제가 발견되었습니다({1}). @@ -6126,7 +6170,7 @@ Type of member '{0}' is not CLS-compliant. - {0}' 멤버의 형식이 CLS 규격이 아닙니다. + '{0}' 멤버의 형식이 CLS 규격이 아닙니다. @@ -6146,7 +6190,7 @@ Return type of function '{0}' is not CLS-compliant. - {0}' 함수의 반환 형식이 CLS 규격이 아닙니다. + '{0}' 함수의 반환 형식이 CLS 규격이 아닙니다. @@ -6156,7 +6200,7 @@ Type of parameter '{0}' is not CLS-compliant. - {0}' 매개 변수의 형식이 CLS 규격이 아닙니다. + '{0}' 매개 변수의 형식이 CLS 규격이 아닙니다. @@ -6236,7 +6280,7 @@ Root namespace '{0}' is not CLS-compliant. - {0}' 루트 네임스페이스가 CLS 규격이 아닙니다. + '{0}' 루트 네임스페이스가 CLS 규격이 아닙니다. @@ -6246,7 +6290,7 @@ Name '{0}' in the root namespace '{1}' is not CLS-compliant. - {1}' 루트 네임스페이스의 '{0}' 이름이 CLS 규격이 아닙니다. + '{1}' 루트 네임스페이스의 '{0}' 이름이 CLS 규격이 아닙니다. @@ -6256,7 +6300,7 @@ Generic parameter constraint type '{0}' is not CLS-compliant. - {0}' 제네릭 매개 변수 제약 조건 형식이 CLS 규격이 아닙니다. + '{0}' 제네릭 매개 변수 제약 조건 형식이 CLS 규격이 아닙니다. @@ -6266,7 +6310,7 @@ Type '{0}' is not CLS-compliant. - {0}' 형식이 CLS 규격이 아닙니다. + '{0}' 형식이 CLS 규격이 아닙니다. @@ -6306,7 +6350,7 @@ Type parameter '{0}' has the same name as a type parameter of an enclosing type. Enclosing type's type parameter will be shadowed. - {0}' 형식 매개 변수의 이름이 바깥쪽 형식의 형식 매개 변수 이름과 같습니다. 바깥쪽 형식의 형식 매개 변수가 숨겨집니다. + '{0}' 형식 매개 변수의 이름이 바깥쪽 형식의 형식 매개 변수 이름과 같습니다. 바깥쪽 형식의 형식 매개 변수가 숨겨집니다. @@ -6316,7 +6360,7 @@ Could not find standard library '{0}'. - {0}' 표준 라이브러리를 찾을 수 없습니다. + '{0}' 표준 라이브러리를 찾을 수 없습니다. @@ -6326,7 +6370,7 @@ Delegate type '{0}' of event '{1}' is not CLS-compliant. - {1}' 이벤트의 '{0}' 대리자 형식이 CLS 규격이 아닙니다. + '{1}' 이벤트의 '{0}' 대리자 형식이 CLS 규격이 아닙니다. @@ -6416,7 +6460,7 @@ Class '{0}' should declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete. - {0}' 클래스는 기본 클래스 '{2}'의 '{1}'이(가) obsolete로 표시되어 있으므로 'Sub New'를 선언해야 합니다. + '{0}' 클래스는 기본 클래스 '{2}'의 '{1}'이(가) obsolete로 표시되어 있으므로 'Sub New'를 선언해야 합니다. @@ -6426,7 +6470,7 @@ Class '{0}' should declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete: '{3}'. - {0}' 클래스는 기본 클래스 '{2}'의 '{1}'이(가) obsolete로 표시되어 있으므로 'Sub New'를 선언해야 합니다('{3}'). + '{0}' 클래스는 기본 클래스 '{2}'의 '{1}'이(가) obsolete로 표시되어 있으므로 'Sub New'를 선언해야 합니다('{3}'). @@ -6436,7 +6480,7 @@ First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete. - {2}'의 기본 클래스 '{1}'에 있는 '{0}'이(가) 사용되지 않는 상태로 표시되어 있으므로, 이 'Sub New'의 첫째 문은 'MyBase.New' 또는 'MyClass.New'에 대한 명시적 호출이어야 합니다. + '{2}'의 기본 클래스 '{1}'에 있는 '{0}'이(가) 사용되지 않는 상태로 표시되어 있으므로, 이 'Sub New'의 첫째 문은 'MyBase.New' 또는 'MyClass.New'에 대한 명시적 호출이어야 합니다. @@ -6446,7 +6490,7 @@ First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete: '{3}' - {2}'의 기본 클래스 '{1}'에 있는 '{0}'이(가) obsolete로 표시되어 있으므로 이 'Sub New'의 첫째 문은 'MyBase.New' 또는 'MyClass.New'에 대한 명시적 호출이어야 합니다('{3}'). + '{2}'의 기본 클래스 '{1}'에 있는 '{0}'이(가) obsolete로 표시되어 있으므로 이 'Sub New'의 첫째 문은 'MyBase.New' 또는 'MyClass.New'에 대한 명시적 호출이어야 합니다('{3}'). @@ -6466,7 +6510,7 @@ Type arguments inferred for method '{0}' result in the following warnings :{1} - {0}' 메서드에 대해 유추된 형식 인수가 다음 경고를 표시했습니다({1}) + '{0}' 메서드에 대해 유추된 형식 인수가 다음 경고를 표시했습니다({1}) @@ -6486,7 +6530,7 @@ Use command-line option '{0}' or appropriate project settings instead of '{1}'. - {1}' 대신 명령줄 옵션 '{0}' 또는 적합한 프로젝트 설정을 사용하세요. + '{1}' 대신 명령줄 옵션 '{0}' 또는 적합한 프로젝트 설정을 사용하세요. @@ -6536,7 +6580,7 @@ Implicit conversion from '{0}' to '{1}'. - {0}'에서 '{1}'(으)로의 암시적 변환입니다. + '{0}'에서 '{1}'(으)로의 암시적 변환입니다. @@ -6586,7 +6630,7 @@ Operands of type Object used for operator '{0}'; use the 'Is' operator to test object identity. - {0}' 연산자에 대해 Object 형식의 피연산자를 사용했습니다. 개체 ID를 테스트하려면 'Is' 연산자를 사용하세요. + '{0}' 연산자에 대해 Object 형식의 피연산자를 사용했습니다. 개체 ID를 테스트하려면 'Is' 연산자를 사용하세요. @@ -6596,7 +6640,7 @@ Operands of type Object used for operator '{0}'; runtime errors could occur. - {0}' 연산자에 대해 Object 형식의 피연산자를 사용했습니다. 런타임 오류가 발생할 수 있습니다. + '{0}' 연산자에 대해 Object 형식의 피연산자를 사용했습니다. 런타임 오류가 발생할 수 있습니다. @@ -6726,7 +6770,7 @@ Operands of type Object used for operator '{0}'; use the 'IsNot' operator to test object identity. - {0}' 연산자에 대해 Object 형식의 피연산자를 사용했습니다. 개체 ID를 테스트하려면 'IsNot' 연산자를 사용하세요. + '{0}' 연산자에 대해 Object 형식의 피연산자를 사용했습니다. 개체 ID를 테스트하려면 'IsNot' 연산자를 사용하세요. @@ -6836,7 +6880,7 @@ Function '{0}' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. - {0}' 함수가 일부 코드 경로에서만 값을 반환합니다. 이 결과를 사용하면 런타임에 null 참조 예외가 발생할 수 있습니다. + '{0}' 함수가 일부 코드 경로에서만 값을 반환합니다. 이 결과를 사용하면 런타임에 null 참조 예외가 발생할 수 있습니다. @@ -6846,7 +6890,7 @@ Operator '{0}' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. - {0}' 연산자가 일부 코드 경로에 대해서만 값을 반환합니다. 이 결과를 사용하면 런타임에 null 참조 예외가 발생할 수 있습니다. + '{0}' 연산자가 일부 코드 경로에 대해서만 값을 반환합니다. 이 결과를 사용하면 런타임에 null 참조 예외가 발생할 수 있습니다. @@ -6856,7 +6900,7 @@ Property '{0}' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. - {0}' 속성이 일부 코드 경로에서만 값을 반환합니다. 이 결과를 사용하면 런타임에 null 참조 예외가 발생할 수 있습니다. + '{0}' 속성이 일부 코드 경로에서만 값을 반환합니다. 이 결과를 사용하면 런타임에 null 참조 예외가 발생할 수 있습니다. @@ -6896,7 +6940,7 @@ Assembly reference '{0}' is invalid and cannot be resolved. - {0}' 어셈블리 참조가 잘못되어 확인할 수 없습니다. + '{0}' 어셈블리 참조가 잘못되어 확인할 수 없습니다. @@ -6966,7 +7010,7 @@ XML comment tag '{0}' is not permitted on a '{1}' language element. - {0}' XML 주석 태그는 '{1}' 언어 요소에서 허용되지 않습니다. + '{0}' XML 주석 태그는 '{1}' 언어 요소에서 허용되지 않습니다. @@ -6976,7 +7020,7 @@ XML comment parameter '{0}' does not match a parameter on the corresponding '{1}' statement. - {0}' XML 주석 매개 변수가 해당 '{1}' 문의 매개 변수와 일치하지 않습니다. + '{0}' XML 주석 매개 변수가 해당 '{1}' 문의 매개 변수와 일치하지 않습니다. @@ -7076,7 +7120,7 @@ XML comment type parameter '{0}' does not match a type parameter on the corresponding '{1}' statement. - {0}' XML 주석 형식 매개 변수가 해당 '{1}' 문의 형식 매개 변수와 일치하지 않습니다. + '{0}' XML 주석 형식 매개 변수가 해당 '{1}' 문의 형식 매개 변수와 일치하지 않습니다. @@ -7106,7 +7150,7 @@ Unable to include XML fragment '{0}' of file '{1}'. - {1}' 파일의 '{0}' XML 조각을 포함할 수 없습니다. + '{1}' 파일의 '{0}' XML 조각을 포함할 수 없습니다. @@ -7116,7 +7160,7 @@ Unable to include XML fragment '{1}' of file '{0}'. {2} - {0}' 파일의 '{1}' XML 조각을 포함할 수 없습니다({2}). + '{0}' 파일의 '{1}' XML 조각을 포함할 수 없습니다({2}). @@ -7126,7 +7170,7 @@ Runtime errors might occur when converting '{0}' to '{1}'. - {0}'에서 '{1}'(으)로 변환할 경우 런타임 오류가 발생할 수 있습니다. + '{0}'에서 '{1}'(으)로 변환할 경우 런타임 오류가 발생할 수 있습니다. @@ -7251,12 +7295,12 @@ Cannot initialize the type '{0}' with a collection initializer because it is not a collection type. - {0}' 형식이 컬렉션 형식이 아니므로 컬렉션 이니셜라이저를 사용하여 해당 형식을 초기화할 수 없습니다. + '{0}' 형식이 컬렉션 형식이 아니므로 컬렉션 이니셜라이저를 사용하여 해당 형식을 초기화할 수 없습니다. Cannot initialize the type '{0}' with a collection initializer because it does not have an accessible 'Add' method. - {0}' 형식에 액세스 가능한 'Add' 메서드가 없으므로 컬렉션 이니셜라이저를 사용하여 해당 형식을 초기화할 수 없습니다. + '{0}' 형식에 액세스 가능한 'Add' 메서드가 없으므로 컬렉션 이니셜라이저를 사용하여 해당 형식을 초기화할 수 없습니다. @@ -7326,7 +7370,7 @@ Function '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement? - {0}' 함수가 일부 코드 경로에서만 값을 반환합니다. 'Return' 문이 있는지 확인하세요. + '{0}' 함수가 일부 코드 경로에서만 값을 반환합니다. 'Return' 문이 있는지 확인하세요. @@ -7336,7 +7380,7 @@ Operator '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement? - {0}' 연산자가 일부 코드 경로에서만 값을 반환합니다. 'Return' 문이 있는지 확인하세요. + '{0}' 연산자가 일부 코드 경로에서만 값을 반환합니다. 'Return' 문이 있는지 확인하세요. @@ -7346,7 +7390,7 @@ Property '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement? - {0}' 속성이 일부 코드 경로에서만 값을 반환합니다. 'Return' 문이 있는지 확인하세요. + '{0}' 속성이 일부 코드 경로에서만 값을 반환합니다. 'Return' 문이 있는지 확인하세요. @@ -7418,22 +7462,22 @@ Error extracting public key from file '{0}': {1} - {0}' 파일에서 공용 키를 추출하는 동안 오류가 발생했습니다({1}). + '{0}' 파일에서 공용 키를 추출하는 동안 오류가 발생했습니다({1}). Error extracting public key from container '{0}': {1} - {0}' 컨테이너에서 공용 키를 추출하는 동안 오류가 발생했습니다({1}). + '{0}' 컨테이너에서 공용 키를 추출하는 동안 오류가 발생했습니다({1}). Friend access was granted by '{0}', but the public key of the output assembly does not match that specified by the attribute in the granting assembly. - {0}'에서 friend 액세스 권한을 부여했지만, 출력 어셈블리의 공용 키가 부여한 어셈블리의 특성에서 지정된 키와 일치하지 않습니다. + '{0}'에서 friend 액세스 권한을 부여했지만, 출력 어셈블리의 공용 키가 부여한 어셈블리의 특성에서 지정된 키와 일치하지 않습니다. Friend access was granted by '{0}', but the strong name signing state of the output assembly does not match that of the granting assembly. - {0}'에서 friend 액세스 권한을 부여했지만, 출력 어셈블리의 강력한 이름 서명 상태가 부여한 어셈블리의 상태와 일치하지 않습니다. + '{0}'에서 friend 액세스 권한을 부여했지만, 출력 어셈블리의 강력한 이름 서명 상태가 부여한 어셈블리의 상태와 일치하지 않습니다. @@ -7473,7 +7517,7 @@ Error signing assembly '{0}': {1} - {0}' 어셈블리에 서명하는 동안 오류가 발생했습니다({1}). + '{0}' 어셈블리에 서명하는 동안 오류가 발생했습니다({1}). @@ -7538,7 +7582,7 @@ The assembly name '{0}' is reserved and cannot be used as a reference in an interactive session - {0}' 어셈블리 이름은 예약된 것이므로 대화형 세션에 참조로 사용할 수 없습니다. + '{0}' 어셈블리 이름은 예약된 것이므로 대화형 세션에 참조로 사용할 수 없습니다. @@ -7638,7 +7682,7 @@ Data type of '{0}' in '{1}' could not be inferred. '{2}' assumed. - {1}'에 있는 '{0}'의 데이터 형식을 유추할 수 없습니다. '{2}'(으)로 간주합니다. + '{1}'에 있는 '{0}'의 데이터 형식을 유추할 수 없습니다. '{2}'(으)로 간주합니다. @@ -7653,7 +7697,7 @@ Conversion from '{0}' to '{1}' may be ambiguous. - {0}'에서 '{1}'(으)로의 변환이 모호할 수 있습니다. + '{0}'에서 '{1}'(으)로의 변환이 모호할 수 있습니다. @@ -7688,7 +7732,7 @@ Implicit conversion from '{4}' to '{5}'; this conversion may fail because '{0}' is not derived from '{1}', as required for the 'In' generic parameter '{2}' in '{3}'. - {4}'에서 '{5}'(으)로 암시적 변환을 수행합니다. '{3}'에 있는 'In' 제네릭 매개 변수 '{2}'에 필요한 대로 '{0}'이(가) '{1}'에서 파생되지 않았으므로 이 변환 작업을 수행하지 못할 수 있습니다. + '{4}'에서 '{5}'(으)로 암시적 변환을 수행합니다. '{3}'에 있는 'In' 제네릭 매개 변수 '{2}'에 필요한 대로 '{0}'이(가) '{1}'에서 파생되지 않았으므로 이 변환 작업을 수행하지 못할 수 있습니다. @@ -7698,7 +7742,7 @@ Implicit conversion from '{4}' to '{5}'; this conversion may fail because '{0}' is not derived from '{1}', as required for the 'Out' generic parameter '{2}' in '{3}'. - {4}'에서 '{5}'(으)로 암시적 변환을 수행합니다. '{3}'에 있는 'Out' 제네릭 매개 변수 '{2}'에 필요한 대로 '{0}'이(가) '{1}'에서 파생되지 않았으므로 이 변환 작업을 수행하지 못할 수 있습니다. + '{4}'에서 '{5}'(으)로 암시적 변환을 수행합니다. '{3}'에 있는 'Out' 제네릭 매개 변수 '{2}'에 필요한 대로 '{0}'이(가) '{1}'에서 파생되지 않았으므로 이 변환 작업을 수행하지 못할 수 있습니다. @@ -7738,7 +7782,7 @@ Interface '{0}' is ambiguous with another implemented interface '{1}' due to the 'In' and 'Out' parameters in '{2}'. - {2}'에 있는 'In' 및 'Out' 매개 변수로 인해 '{0}' 인터페이스가 구현된 다른 인터페이스 '{1}'에 대해 모호합니다. + '{2}'에 있는 'In' 및 'Out' 매개 변수로 인해 '{0}' 인터페이스가 구현된 다른 인터페이스 '{1}'에 대해 모호합니다. @@ -7768,37 +7812,37 @@ Type '{0}' cannot be used in this context because '{0}' is an 'In' type parameter. - {0}'이(가) 'In' 형식 매개 변수이므로 '{0}' 형식을 이 컨텍스트에서 사용할 수 없습니다. + '{0}'이(가) 'In' 형식 매개 변수이므로 '{0}' 형식을 이 컨텍스트에서 사용할 수 없습니다. Type '{0}' cannot be used for the '{1}' in '{2}' in this context because '{0}' is an 'In' type parameter. - {0}'이(가) 'In' 형식 매개 변수이므로 '{0}' 형식을 이 컨텍스트에서 '{2}'에 있는 '{1}'에는 사용할 수 없습니다. + '{0}'이(가) 'In' 형식 매개 변수이므로 '{0}' 형식을 이 컨텍스트에서 '{2}'에 있는 '{1}'에는 사용할 수 없습니다. Type '{0}' cannot be used in '{1}' in this context because '{0}' is an 'In' type parameter. - {0}'이(가) 'In' 형식 매개 변수이므로 '{0}' 형식을 이 컨텍스트에서 '{1}'에 사용할 수 없습니다. + '{0}'이(가) 'In' 형식 매개 변수이므로 '{0}' 형식을 이 컨텍스트에서 '{1}'에 사용할 수 없습니다. Type '{0}' cannot be used for the '{2}' of '{3}' in '{1}' in this context because '{0}' is an 'In' type parameter. - {0}'이(가) 'In' 형식 매개 변수이므로 '{0}' 형식을 이 컨텍스트에서 '{1}'에 있는 '{3}'의 '{2}'에는 사용할 수 없습니다. + '{0}'이(가) 'In' 형식 매개 변수이므로 '{0}' 형식을 이 컨텍스트에서 '{1}'에 있는 '{3}'의 '{2}'에는 사용할 수 없습니다. Type '{0}' cannot be used as a property type in this context because '{0}' is an 'In' type parameter and the property is not marked WriteOnly. - {0}'이(가) 'In' 형식 매개 변수이며 속성이 WriteOnly로 표시되어 있지 않으므로 '{0}' 형식을 이 컨텍스트에서 속성 형식으로 사용할 수 없습니다. + '{0}'이(가) 'In' 형식 매개 변수이며 속성이 WriteOnly로 표시되어 있지 않으므로 '{0}' 형식을 이 컨텍스트에서 속성 형식으로 사용할 수 없습니다. Type '{0}' cannot be used as a ReadOnly property type because '{0}' is an 'In' type parameter. - {0}'이(가) 'In' 형식 매개 변수이므로 '{0}' 형식을 ReadOnly 속성 형식으로 사용할 수 없습니다. + '{0}'이(가) 'In' 형식 매개 변수이므로 '{0}' 형식을 ReadOnly 속성 형식으로 사용할 수 없습니다. Type '{0}' cannot be used as a return type because '{0}' is an 'In' type parameter. - {0}'이(가) 'In' 형식 매개 변수이므로 '{0}' 형식을 반환 형식으로 사용할 수 없습니다. + '{0}'이(가) 'In' 형식 매개 변수이므로 '{0}' 형식을 반환 형식으로 사용할 수 없습니다. @@ -7808,12 +7852,12 @@ Type '{0}' cannot be used as a ByVal parameter type because '{0}' is an 'Out' type parameter. - {0}'이(가) 'Out' 형식 매개 변수이므로 '{0}' 형식을 ByVal 매개 변수 형식으로 사용할 수 없습니다. + '{0}'이(가) 'Out' 형식 매개 변수이므로 '{0}' 형식을 ByVal 매개 변수 형식으로 사용할 수 없습니다. Type '{0}' cannot be used as a generic type constraint because '{0}' is an 'Out' type parameter. - {0}'이(가) 'Out' 형식 매개 변수이므로 '{0}' 형식을 제네릭 형식 제약 조건으로 사용할 수 없습니다. + '{0}'이(가) 'Out' 형식 매개 변수이므로 '{0}' 형식을 제네릭 형식 제약 조건으로 사용할 수 없습니다. @@ -7823,52 +7867,52 @@ Type '{0}' cannot be used in this context because '{0}' is an 'Out' type parameter. - {0}'이(가) 'Out' 형식 매개 변수이므로 '{0}' 형식을 이 컨텍스트에서 사용할 수 없습니다. + '{0}'이(가) 'Out' 형식 매개 변수이므로 '{0}' 형식을 이 컨텍스트에서 사용할 수 없습니다. Type '{0}' cannot be used for the '{1}' in '{2}' in this context because '{0}' is an 'Out' type parameter. - {0}'이(가) 'Out' 형식 매개 변수이므로 '{0}' 형식을 이 컨텍스트에서 '{2}'에 있는 '{1}'에는 사용할 수 없습니다. + '{0}'이(가) 'Out' 형식 매개 변수이므로 '{0}' 형식을 이 컨텍스트에서 '{2}'에 있는 '{1}'에는 사용할 수 없습니다. Type '{0}' cannot be used in '{1}' in this context because '{0}' is an 'Out' type parameter. - {0}'이(가) 'Out' 형식 매개 변수이므로 '{0}' 형식을 이 컨텍스트에서 '{1}'에 사용할 수 없습니다. + '{0}'이(가) 'Out' 형식 매개 변수이므로 '{0}' 형식을 이 컨텍스트에서 '{1}'에 사용할 수 없습니다. Type '{0}' cannot be used for the '{2}' of '{3}' in '{1}' in this context because '{0}' is an 'Out' type parameter. - {0}'이(가) 'Out' 형식 매개 변수이므로 '{0}' 형식을 이 컨텍스트에서 '{1}'에 있는 '{3}'의 '{2}'에는 사용할 수 없습니다. + '{0}'이(가) 'Out' 형식 매개 변수이므로 '{0}' 형식을 이 컨텍스트에서 '{1}'에 있는 '{3}'의 '{2}'에는 사용할 수 없습니다. Type '{0}' cannot be used as a property type in this context because '{0}' is an 'Out' type parameter and the property is not marked ReadOnly. - {0}'이(가) 'Out' 형식 매개 변수이고 속성이 ReadOnly로 표시되어 있지 않으므로, '{0}' 형식을 이 컨텍스트에서 속성 형식으로 사용할 수 없습니다. + '{0}'이(가) 'Out' 형식 매개 변수이고 속성이 ReadOnly로 표시되어 있지 않으므로, '{0}' 형식을 이 컨텍스트에서 속성 형식으로 사용할 수 없습니다. Type '{0}' cannot be used as a WriteOnly property type because '{0}' is an 'Out' type parameter. - {0}'이(가) 'Out' 형식 매개 변수이므로 '{0}' 형식을 WriteOnly 속성 형식으로 사용할 수 없습니다. + '{0}'이(가) 'Out' 형식 매개 변수이므로 '{0}' 형식을 WriteOnly 속성 형식으로 사용할 수 없습니다. Type '{0}' cannot be used in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'. - {0}'의 컨텍스트와 정의가 모두 '{1}' 인터페이스 안에 중첩되어 있고 '{1}'에 'In' 또는 'Out' 형식 매개 변수가 있으므로, '{0}' 형식을 이 컨텍스트에서 사용할 수 없습니다. '{0}'의 정의를 '{1}' 외부로 이동하세요. + '{0}'의 컨텍스트와 정의가 모두 '{1}' 인터페이스 안에 중첩되어 있고 '{1}'에 'In' 또는 'Out' 형식 매개 변수가 있으므로, '{0}' 형식을 이 컨텍스트에서 사용할 수 없습니다. '{0}'의 정의를 '{1}' 외부로 이동하세요. Type '{0}' cannot be used for the '{2}' in '{3}' in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'. - {0}'의 컨텍스트와 정의가 모두 '{1}' 인터페이스 안에 중첩되어 있고 '{1}'에 'In' 또는 'Out' 형식 매개 변수가 있으므로, '{0}' 형식을 이 컨텍스트에서 '{3}'에 있는 '{2}'에 대해 사용할 수 없습니다. '{0}'의 정의를 '{1}' 외부로 이동하세요. + '{0}'의 컨텍스트와 정의가 모두 '{1}' 인터페이스 안에 중첩되어 있고 '{1}'에 'In' 또는 'Out' 형식 매개 변수가 있으므로, '{0}' 형식을 이 컨텍스트에서 '{3}'에 있는 '{2}'에 대해 사용할 수 없습니다. '{0}'의 정의를 '{1}' 외부로 이동하세요. Type '{0}' cannot be used in '{2}' in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'. - {0}'의 컨텍스트와 정의가 모두 '{1}' 인터페이스 안에 중첩되어 있고 '{1}'에 'In' 또는 'Out' 형식 매개 변수가 있으므로, '{0}' 형식을 이 컨텍스트에서 '{2}'에 사용할 수 없습니다. '{0}'의 정의를 '{1}' 외부로 이동하세요. + '{0}'의 컨텍스트와 정의가 모두 '{1}' 인터페이스 안에 중첩되어 있고 '{1}'에 'In' 또는 'Out' 형식 매개 변수가 있으므로, '{0}' 형식을 이 컨텍스트에서 '{2}'에 사용할 수 없습니다. '{0}'의 정의를 '{1}' 외부로 이동하세요. Type '{0}' cannot be used for the '{3}' of '{4}' in '{2}' in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'. - {0}'의 컨텍스트와 정의가 모두 '{1}' 인터페이스 안에 중첩되어 있고 '{1}'에 'In' 또는 'Out' 형식 매개 변수가 있으므로, '{0}' 형식을 이 컨텍스트에서 '{2}'에 있는 '{4}'의 '{3}'에 대해 사용할 수 없습니다. '{0}'의 정의를 '{1}' 외부로 이동하세요. + '{0}'의 컨텍스트와 정의가 모두 '{1}' 인터페이스 안에 중첩되어 있고 '{1}'에 'In' 또는 'Out' 형식 매개 변수가 있으므로, '{0}' 형식을 이 컨텍스트에서 '{2}'에 있는 '{4}'의 '{3}'에 대해 사용할 수 없습니다. '{0}'의 정의를 '{1}' 외부로 이동하세요. @@ -7888,12 +7932,12 @@ Attribute parameter '{0}' must be specified. - {0}' 특성 매개 변수를 지정해야 합니다. + '{0}' 특성 매개 변수를 지정해야 합니다. Attribute parameter '{0}' or '{1}' must be specified. - {0}' 또는 '{1}' 특성 매개 변수를 지정해야 합니다. + '{0}' 또는 '{1}' 특성 매개 변수를 지정해야 합니다. @@ -7958,7 +8002,7 @@ Interface '{0}' has an invalid source interface which is required to embed event '{1}'. - {0}' 인터페이스에는 '{1}' 이벤트를 포함하는 데 필요한 소스 인터페이스가 잘못 포함되어 있습니다. + '{0}' 인터페이스에는 '{1}' 이벤트를 포함하는 데 필요한 소스 인터페이스가 잘못 포함되어 있습니다. @@ -7968,12 +8012,12 @@ Nested type '{0}' cannot be embedded. - {0}' 중첩 형식을 포함할 수 없습니다. + '{0}' 중첩 형식을 포함할 수 없습니다. Embedding the interop type '{0}' from assembly '{1}' causes a name clash in the current assembly. Consider disabling the embedding of interop types. - {1}' 어셈블리의 interop 형식 '{0}'을(를) 포함하면 현재 어셈블리에서 이름이 충돌합니다. interop 형식을 포함하지 않도록 설정하세요. + '{1}' 어셈블리의 interop 형식 '{0}'을(를) 포함하면 현재 어셈블리에서 이름이 충돌합니다. interop 형식을 포함하지 않도록 설정하세요. @@ -8153,7 +8197,7 @@ Security attribute '{0}' cannot be applied to an Async or Iterator method. - {0}' 보안 특성은 비동기 또는 반복기 메서드에 적용할 수 없습니다. + '{0}' 보안 특성은 비동기 또는 반복기 메서드에 적용할 수 없습니다. @@ -8198,7 +8242,7 @@ Event '{0}' cannot implement a Windows Runtime event '{1}' and a regular .NET event '{2}' - {0}' 이벤트에서 Windows Runtime 이벤트 '{1}'과(와) 일반 .NET 이벤트 '{2}'을(를) 모두 구현할 수는 없습니다. + '{0}' 이벤트에서 Windows Runtime 이벤트 '{1}'과(와) 일반 .NET 이벤트 '{2}'을(를) 모두 구현할 수는 없습니다. @@ -8268,17 +8312,17 @@ Optional parameter of a method '{0}' does not have the same default value as the corresponding parameter of the partial method '{1}'. - {0}' 메서드의 선택적 매개 변수에는 '{1}' 부분 메서드(Partial Method)에 해당하는 매개 변수와 동일한 기본값이 없습니다. + '{0}' 메서드의 선택적 매개 변수에는 '{1}' 부분 메서드(Partial Method)에 해당하는 매개 변수와 동일한 기본값이 없습니다. Parameter of a method '{0}' differs by ParamArray modifier from the corresponding parameter of the partial method '{1}'. - {0}' 메서드의 매개 변수는 '{1}' 부분 메서드(Partial Method)에 해당하는 매개 변수의 ParamArray 한정자와 다릅니다. + '{0}' 메서드의 매개 변수는 '{1}' 부분 메서드(Partial Method)에 해당하는 매개 변수의 ParamArray 한정자와 다릅니다. Module name '{0}' stored in '{1}' must match its filename. - {1}'에 저장된 '{0}' 모듈 이름은 파일 이름과 일치해야 합니다. + '{1}'에 저장된 '{0}' 모듈 이름은 파일 이름과 일치해야 합니다. @@ -8288,7 +8332,7 @@ Attribute '{0}' from module '{1}' will be ignored in favor of the instance appearing in source. - {1}' 모듈의 '{0}' 특성은 소스에 나타나는 인스턴스를 위해 무시됩니다. + '{1}' 모듈의 '{0}' 특성은 소스에 나타나는 인스턴스를 위해 무시됩니다. @@ -8318,17 +8362,17 @@ Type '{0}' conflicts with public type defined in added module '{1}'. - {0}' 형식이 추가된 모듈 '{1}'에 정의된 public 형식과 충돌합니다. + '{0}' 형식이 추가된 모듈 '{1}'에 정의된 public 형식과 충돌합니다. Type '{0}' exported from module '{1}' conflicts with type declared in primary module of this assembly. - {1}' 모듈에서 내보낸 '{0}' 형식이 이 어셈블리의 주 모듈에서 선언된 형식과 충돌합니다. + '{1}' 모듈에서 내보낸 '{0}' 형식이 이 어셈블리의 주 모듈에서 선언된 형식과 충돌합니다. Type '{0}' exported from module '{1}' conflicts with type '{2}' exported from module '{3}'. - {1}' 모듈에서 내보낸 '{0}' 형식이 '{3}' 모델에서 내보낸 '{2}' 형식과 충돌합니다. + '{1}' 모듈에서 내보낸 '{0}' 형식이 '{3}' 모델에서 내보낸 '{2}' 형식과 충돌합니다. @@ -8378,32 +8422,32 @@ Type '{0}' forwarded to assembly '{1}' conflicts with type '{2}' forwarded to assembly '{3}'. - {1}' 어셈블리로 전달된 '{0}' 형식이 '{3}' 어셈블리로 전달된 '{2}' 형식과 충돌합니다. + '{1}' 어셈블리로 전달된 '{0}' 형식이 '{3}' 어셈블리로 전달된 '{2}' 형식과 충돌합니다. Name '{0}' exceeds the maximum length allowed in metadata. - {0}' 이름이 메타데이터에 허용된 최대 길이를 초과했습니다. + '{0}' 이름이 메타데이터에 허용된 최대 길이를 초과했습니다. Reference to '{0}' netmodule missing. - {0}' netmodule에 대한 참조가 없습니다. + '{0}' netmodule에 대한 참조가 없습니다. Module '{0}' is already defined in this assembly. Each module must have a unique filename. - {0}' 모듈이 이 어셈블리에 이미 정의되었습니다. 각 모듈에 고유한 파일 이름이 있어야 합니다. + '{0}' 모듈이 이 어셈블리에 이미 정의되었습니다. 각 모듈에 고유한 파일 이름이 있어야 합니다. Type '{0}' forwarded to assembly '{1}' conflicts with type '{2}' exported from module '{3}'. - {1}' 어셈블리로 전달된 '{0}' 형식이 '{3}'에서 내보낸 '{2}' 형식과 충돌합니다. + '{1}' 어셈블리로 전달된 '{0}' 형식이 '{3}'에서 내보낸 '{2}' 형식과 충돌합니다. Adding assembly reference '{0}' - {0}' 어셈블리 참조 추가 중 + '{0}' 어셈블리 참조 추가 중 @@ -8413,12 +8457,12 @@ Adding module reference '{0}' - {0}' 모듈 참조 추가 중 + '{0}' 모듈 참조 추가 중 Type '{0}' does not inherit the generic type parameters of its container. - {0}' 형식이 해당 컨테이너의 제네릭 형식 매개 변수를 상속하지 않습니다. + '{0}' 형식이 해당 컨테이너의 제네릭 형식 매개 변수를 상속하지 않습니다. @@ -8723,7 +8767,7 @@ Preprocessor constant '{0}' of type '{1}' is not supported, only primitive types are allowed. - {1}' 형식의 전처리기 상수 '{0}'은(는) 지원되지 않습니다. 기본 형식만 허용됩니다. + '{1}' 형식의 전처리기 상수 '{0}'은(는) 지원되지 않습니다. 기본 형식만 허용됩니다. @@ -8818,7 +8862,7 @@ Error reading debug information for '{0}' - {0}'에 대한 디버그 정보 읽기 오류 + '{0}'에 대한 디버그 정보 읽기 오류 @@ -9058,7 +9102,7 @@ Module '{0}' in assembly '{1}' is forwarding the type '{2}' to multiple assemblies: '{3}' and '{4}'. - {1}' 어셈블리의 '{0}' 모듈이 여러 어셈블리 '{3}' 및 '{4}'에 '{2}' 형식을 전달하고 있습니다. + '{1}' 어셈블리의 '{0}' 모듈이 여러 어셈블리 '{3}' 및 '{4}'에 '{2}' 형식을 전달하고 있습니다. @@ -9113,7 +9157,7 @@ Unable to read debug information of method '{0}' (token 0x{1}) from assembly '{2}' - {2}' 어셈블리에서 '{0}' 메서드(토큰 0x{1})의 디버그 정보를 읽을 수 없습니다. + '{2}' 어셈블리에서 '{0}' 메서드(토큰 0x{1})의 디버그 정보를 읽을 수 없습니다. @@ -9153,7 +9197,7 @@ File name '{0}' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long - {0}' 파일 이름이 비어 있거나, 잘못된 문자가 있거나, 절대 경로가 없는 드라이브 사양이 있거나, 너무 깁니다. + '{0}' 파일 이름이 비어 있거나, 잘못된 문자가 있거나, 절대 경로가 없는 드라이브 사양이 있거나, 너무 깁니다. diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.pl.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.pl.xlf index b4f5f586f7ae9..097427e155e25 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.pl.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.pl.xlf @@ -212,169 +212,169 @@ -vbruntime:<file> Compile with the alternate Visual Basic runtime in <file>. - Visual Basic Compiler Options + Opcje kompilatora Visual Basic - - OUTPUT FILE - --out:<file> Specifies the output file name. --target:exe Create a console application (default). - (Short form: -t) --target:winexe Create a Windows application. --target:library Create a library assembly. --target:module Create a module that can be added to an - assembly. --target:appcontainerexe Create a Windows application that runs in - AppContainer. --target:winmdobj Create a Windows Metadata intermediate file --doc[+|-] Generates XML documentation file. --doc:<file> Generates XML documentation file to <file>. --refout:<file> Reference assembly output to generate + - PLIK WYJŚCIOWY - +-out:<plik> Określa nazwę pliku wyjściowego. +-target:exe Utwórz aplikację konsolową (domyślnie). + (Krótka wersja: -t) +-target:winexe Utwórz aplikację systemu Windows +-target:library Utwórz zestaw biblioteki. +-target:module Utwórz moduł, który można dodać do + zestawu +-target:appcontainerexe Utwórz aplikację systemu Windows uruchamianą w + kontenerze aplikacji. +-target:winmdobj Utwórz plik pośredni metadanych systemu Windows +-doc[+|-] Generuje plik dokumentacji XML. +-doc:<file> Generuje plik dokumentacji XML w pliku <plik>. +-refout:<plik> Dane wyjściowe zestawu odwołania do wygenerowania - - INPUT FILES - --addmodule:<file_list> Reference metadata from the specified modules --link:<file_list> Embed metadata from the specified interop - assembly. (Short form: -l) --recurse:<wildcard> Include all files in the current directory - and subdirectories according to the - wildcard specifications. --reference:<file_list> Reference metadata from the specified - assembly. (Short form: -r) --analyzer:<file_list> Run the analyzers from this assembly - (Short form: -a) --additionalfile:<file list> Additional files that don't directly affect code - generation but may be used by analyzers for producing - errors or warnings. + - PLIKI WEJŚCIOWE - +-addmodule:<lista_plików> Odwołuj się do metadanych z określonych modułów +-link:<lista_plików> Osadź metadane z określonego + zestawu międzyoperacyjnego. (Krótka wersja: -l) +-recurse:<symbol wieloznaczny> Dołącz wszystkie pliki zawarte w bieżącym katalogu + i jego podkatalogach zgodnie ze + specyfikacją określoną przy użyciu symboli wieloznacznych. +-reference:<lista_plików> Odwołuj się do metadanych z określonego + zestawu. (Krótka wersja: -r) +-analyzer:<lista_plików> Uruchom analizatory z tego zestawu + (Krótka wersja: -a) +-additionalfile:<lista_plików> Dodatkowe pliki, które nie mają bezpośredniego wpływu + na generowanie kodu, ale mogą być używane przez analizatory w celu tworzenia + komunikatów o błędach lub ostrzeżeń. - - RESOURCES - --linkresource:<resinfo> Links the specified file as an external - assembly resource. - resinfo:<file>[,<name>[,public|private]] - (Short form: -linkres) --nowin32manifest The default manifest should not be embedded - in the manifest section of the output PE. --resource:<resinfo> Adds the specified file as an embedded - assembly resource. - resinfo:<file>[,<name>[,public|private]] - (Short form: -res) --win32icon:<file> Specifies a Win32 icon file (.ico) for the - default Win32 resources. --win32manifest:<file> The provided file is embedded in the manifest - section of the output PE. --win32resource:<file> Specifies a Win32 resource file (.res). + - ZASOBY - +-linkresource:<informacje_o_zasobie> Łączy określony plik jako + zasób zewnętrzny zestawu. + informacje_o_zasobie:<plik>[,<nazwa>[,public|private]] + (Krótka wersja: -linkres) +-nowin32manifest Manifest domyślny nie powinien być osadzony + w sekcji manifestu w wyjściowym środowisku PE. +-resource:<informacje_o_zasobie> Dodaje określony plik jako osadzony + zasób zestawu. + informacje_o_zasobie:<plik>[,<nazwa>[,public|private]] + (Krótka wersja: -res) +-win32icon:<p> Określa plik ikony środowiska Win32 (ico) dla + domyślnych zasobów środowiska Win32. +-win32manifest:<plik> Podany plik zostanie osadzony w + sekcji manifestu wyjściowego środowiska PE. +-win32resource:<plik> Określa plik zasobów środowiska Win32 (res). - - CODE GENERATION - --optimize[+|-] Enable optimizations. --removeintchecks[+|-] Remove integer checks. Default off. --debug[+|-] Emit debugging information. --debug:full Emit full debugging information (default). --debug:pdbonly Emit full debugging information. --debug:portable Emit cross-platform debugging information. --debug:embedded Emit cross-platform debugging information into - the target .dll or .exe. --deterministic Produce a deterministic assembly - (including module version GUID and timestamp) --refonly Produce a reference assembly in place of the main output --instrument:TestCoverage Produce an assembly instrumented to collect - coverage information --sourcelink:<file> Source link info to embed into PDB. + - GENEROWANIE KODU - +-optimize[+|-] Włącz optymalizacje. +-removeintchecks[+|-] Usuń kontrole liczb całkowitych. Domyślnie wyłączone. +-debug[+|-] Emituj informacje o debugowaniu. +-debug:full Emituj pełne informacje o debugowaniu (domyślnie). +-debug:pdbonly Emituj pełne informacje o debugowaniu. +-debug:portable Emituj informacje o debugowaniu międzyplatformowym. +-debug:embedded Emituj informacje o debugowaniu międzyplatformowym do + docelowego pliku DLL lub EXE. +-deterministic Utwórz zestaw deterministyczny + (w tym sygnaturę czasową i identyfikator GUID wersji modułu) +-refonly Utwórz zestaw odwołania zamiast głównych danych wyjściowych +-instrument:TestCoverage Utwórz zestaw instrumentowany w celu gromadzenia + informacji o pokryciu +-sourcelink:<plik> Informacje o linku źródłowym do wbudowania w pliku PDB. - - ERRORS AND WARNINGS - --nowarn Disable all warnings. --nowarn:<number_list> Disable a list of individual warnings. --warnaserror[+|-] Treat all warnings as errors. --warnaserror[+|-]:<number_list> Treat a list of warnings as errors. --ruleset:<file> Specify a ruleset file that disables specific - diagnostics. --errorlog:<file>[,version=<sarif_version>] - Specify a file to log all compiler and analyzer - diagnostics in SARIF format. - sarif_version:{1|2|2.1} Default is 1. 2 and 2.1 - both mean SARIF version 2.1.0. --reportanalyzer Report additional analyzer information, such as - execution time. --skipanalyzers[+|-] Skip execution of diagnostic analyzers. + - BŁĘDY I OSTRZEŻENIA - +-nowarn Wyłącz wszystkie ostrzeżenia. +-nowarn:<lista_numerów> Wyłącz listę poszczególnych ostrzeżeń. +-warnaserror[+|-] Traktuj wszystkie ostrzeżenia jako błędy. +-warnaserror[+|-]:<lista_numerów> Traktuj ostrzeżenia z listy jako błędy. +-ruleset:<plik> Określ plik zestawu reguł, który wyłącza określone + opcje diagnostyczne. +-errorlog:<plik>[,version=<wersja_sarif>] + Określ plik, w którym mają zostać zarejestrowane dane diagnostyczne + w formacie SARIF. + wersja_sarif:{1|2|2.1} Domyślne wartości 1. 2 i 2.1 + oznaczają format SARIF w wersji 2.1.0. +-reportanalyzer Zgłoś dodatkowe informacje analizatora, takie jak + czas wykonywania. +-skipanalyzers[+|-] Pomiń wykonywanie analizatorów diagnostycznych. - - LANGUAGE - --define:<symbol_list> Declare global conditional compilation - symbol(s). symbol_list:name=value,... - (Short form: -d) --imports:<import_list> Declare global Imports for namespaces in - referenced metadata files. - import_list:namespace,... --langversion:? Display the allowed values for language version --langversion:<string> Specify language version such as - `default` (latest major version), or - `latest` (latest version, including minor versions), - or specific versions like `14` or `15.3` --optionexplicit[+|-] Require explicit declaration of variables. --optioninfer[+|-] Allow type inference of variables. --rootnamespace:<string> Specifies the root Namespace for all type - declarations. --optionstrict[+|-] Enforce strict language semantics. --optionstrict:custom Warn when strict language semantics are not - respected. --optioncompare:binary Specifies binary-style string comparisons. - This is the default. --optioncompare:text Specifies text-style string comparisons. + - JĘZYK - +-define:<lista_symboli> Zadeklaruj globalne symbole + kompilacji warunkowej. symbol_list:nazwa=wartość,... + (Krótka wersja: -d) +-imports:<lista_importów> Zadeklaruj globalne importy dla przestrzeni nazw w + przywoływanych plikach metadanych. + import_list:przestrzeń_nazw, ,... +-langversion:? Wyświetl dozwolone wartości dla wersji języka +-langversion:<ciąg> Określ wersję języka, taką jak + „default” (najnowsza wersja główna) lub + „latest” (najnowsza wersja, z uwzględnieniem wersji pomocniczych) + albo konkretna wersja, na przykład „14” lub „15.3” +-optionexplicit[+|-] Wymagaj jawnej deklaracji zmiennych. +-optioninfer[+|-] Zezwalaj na wnioskowanie o typie zmiennych. +-rootnamespace:<ciąg> Określa główną przestrzeń nazw dla wszystkich + deklaracji typów. +-optionstrict[+|-] Wymuszaj ścisłą semantykę języka. +-optionstrict:custom Ostrzegaj, gdy ścisła semantyka języka nie jest + przestrzegana. +-optioncompare:binary Określa binarne porównywanie ciągów. + Jest to opcja domyślna. +-optioncompare:text Określa tekstowe porównywanie ciągów. - - MISCELLANEOUS - --help Display this usage message. (Short form: -?) --noconfig Do not auto-include VBC.RSP file. --nologo Do not display compiler copyright banner. --quiet Quiet output mode. --verbose Display verbose messages. --parallel[+|-] Concurrent build. --version Display the compiler version number and exit. + - RÓŻNE - +-help Wyświetl ten komunikat dotyczący użycia. (krótka wersja: -?) +-noconfig Nie dołączaj automatycznie pliku VBC.RSP. +-nologo Nie wyświetlaj baneru kompilatora z informacjami o prawach autorskich. +-quiet Cichy tryb wyjściowy. +-verbose Wyświetl pełne komunikaty +-parallel[+|-] Współbieżna kompilacja. +-version Wyświetl numer wersji kompilatora i wyjdź. - - ADVANCED - --baseaddress:<number> The base address for a library or module - (hex). --checksumalgorithm:<alg> Specify algorithm for calculating source file - checksum stored in PDB. Supported values are: - SHA1 or SHA256 (default). --codepage:<number> Specifies the codepage to use when opening - source files. --delaysign[+|-] Delay-sign the assembly using only the public - portion of the strong name key. --publicsign[+|-] Public-sign the assembly using only the public - portion of the strong name key. --errorreport:<string> Specifies how to handle internal compiler - errors; must be prompt, send, none, or queue - (default). --filealign:<number> Specify the alignment used for output file - sections. --highentropyva[+|-] Enable high-entropy ASLR. --keycontainer:<string> Specifies a strong name key container. --keyfile:<file> Specifies a strong name key file. --libpath:<path_list> List of directories to search for metadata - references. (Semi-colon delimited.) --main:<class> Specifies the Class or Module that contains - Sub Main. It can also be a Class that - inherits from System.Windows.Forms.Form. - (Short form: -m) --moduleassemblyname:<string> Name of the assembly which this module will - be a part of. --netcf Target the .NET Compact Framework. --nostdlib Do not reference standard libraries - (system.dll and VBC.RSP file). --pathmap:<K1>=<V1>,<K2>=<V2>,... - Specify a mapping for source path names output by - the compiler. --platform:<string> Limit which platforms this code can run on; - must be x86, x64, Itanium, arm, arm64 - AnyCPU32BitPreferred or anycpu (default). --preferreduilang Specify the preferred output language name. --nosdkpath Disable searching the default SDK path for standard library assemblies. --sdkpath:<path> Location of the .NET Framework SDK directory + - ZAAWANSOWANE - +-baseaddress:<numer> Podstawowy adres biblioteki lub modułu + (szesnastkowy). +-checksumalgorithm:<algorytm> Określ algorytm obliczania sumy kontrolnej + pliku źródłowego przechowywanej w pliku PDB. Obsługiwane wartości: + SHA1 lub SHA256 (domyślnie). +-codepage:<numer> Określa stronę kodową do użycia podczas otwierania + plików źródłowych. +-delaysign[+|-] Podpisz z opóźnieniem zestaw, używając tylko części publicznej + klucza o silnej nazwie. +-publicsign[+|-] Podpisz publicznie zestaw, używając tylko części publicznej + klucza o silnej nazwie. +-errorreport:<ciąg> Określa, w jaki sposób obsługiwać wewnętrzne + błędy kompilatora: musi mieć wartość prompt, send, none lub queue + (wartość domyślna). +-filealign:<numer> Określ wyrównanie stosowane dla sekcji + plików wyjściowych. +-highentropyva[+|-] Włącz losowe generowanie układu przestrzeni adresowej o wysokiej entropii. +-keycontainer:<ciąg> Określa kontener klucza o silnej nazwie. +-keyfile:<plik> Określa plik klucza o silnej nazwie. +-libpath:<lista_ścieżek> Lista katalogów, w których mają zostać wyszukane + odwołania do metadanych (lista wartości oddzielonych średnikami). +-main:<klasa> Określa klasę lub moduł zawierające + element Sub Main. Może to również być klasa + dziedzicząca po elemencie System.Windows.Forms.Form. + (krótka wersja: -m) +-moduleassemblyname:<ciąg> Nazwa zestawu, do którego będzie należeć + ten moduł. +-netcf Ustaw program .NET Compact Framework jako element docelowy. +-nostdlib Nie odwołuj się do bibliotek standardowych + (plików system.dll i VBC.RSP). +-pathmap:<K1>=<W1>,<K2>=<W2>,... + Określ mapowanie nazw ścieżek źródłowych wyprowadzanych + przez kompilator. +-platform:<ciąg> Ogranicz platformy, na jakich można uruchomić ten kod; + dozwolone wartości: x86, x64, Itanium, arm, arm64, + AnyCPU32BitPreferred lub anycpu (wartość domyślna). +-preferreduilang Określ nazwę preferowanego języka wyjściowego. +-nosdkpath Wyłącz wyszukiwanie ścieżki domyślnego zestawu SDK dla standardowych zestawów bibliotecznych. +-sdkpath:<ścieżka> Lokalizacja katalogu zestawu .NET Framework SDK (mscorlib.dll). --subsystemversion:<version> Specify subsystem version of the output PE. - version:<number>[.<number>] --utf8output[+|-] Emit compiler output in UTF8 character - encoding. -@<file> Insert command-line settings from a text file --vbruntime[+|-|*] Compile with/without the default Visual Basic - runtime. --vbruntime:<file> Compile with the alternate Visual Basic - runtime in <file>. +-subsystemversion:<wersja> Określ wersję podsystemu wyjściowego środowiska PE. + version:<numer>[.<numer>] +-utf8output[+|-] Emituj dane wyjściowe kompilatora przy użyciu + kodowania znaków UTF8. +@<plik> Wstaw ustawienia wiersza polecenia z pliku tekstowego +-vbruntime[+|-|*] Wykonaj kompilację przy użyciu-bez użycia domyślnego + środowiska uruchomieniowego języka Visual Basic. +-vbruntime:<plik> Wykonaj kompilację przy użyciu alternatywnego + środowiska uruchomieniowego języka Visual Basic w pliku <plik>. @@ -463,6 +463,50 @@ Argument typu nie może mieć wartości Nothing + + The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + Zestaw „{0}” zawierający typ „{1}” odwołuje się do platformy .NET Framework, co nie jest obsługiwane. + {1} is the type that was loaded, {0} is the containing assembly. + + + The loaded assembly references .NET Framework, which is not supported. + Załadowany zestaw odwołuje się do platformy .NET Framework, co nie jest obsługiwane. + + + + Generator '{0}' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + Generator „{0}” nie mógł wygenerować źródła. W rezultacie nie będzie on współtworzyć danych wyjściowych i mogą wystąpić błędy kompilacji. Typ wyjątku: „{1}”, komunikat: „{2}” + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + Generator zgłosił następujący wyjątek: +„{0}”. + {0} is the string representation of the exception that was thrown. + + + Generator failed to generate source. + Generator nie mógł wygenerować źródła. + + + + Generator '{0}' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + Generator „{0}” nie mógł przeprowadzić inicjalizacji. W rezultacie nie będzie on współtworzyć danych wyjściowych i mogą wystąpić błędy kompilacji. Typ wyjątku: „{1}”, komunikat: „{2}” + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + Generator zgłosił następujący wyjątek: +„{0}”. + {0} is the string representation of the exception that was thrown. + + + Generator failed to initialize. + Generator nie mógł przeprowadzić inicjalizacji. + + Wrong number of type arguments Nieprawidłowa liczba argumentów typu @@ -2390,7 +2434,7 @@ '{0}' is a MustOverride event in the base class '{1}'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class '{2}' MustInherit. - '„{0}” jest zdarzeniem MustOverride w klasie bazowej „{1}”. Język Visual Basic nie obsługuje przesłaniania zdarzeń. Musisz określić implementację zdarzenia w klasie bazowej lub ustawić klasę „{2}” jako zdarzenie MustInherit. + „{0}” jest zdarzeniem MustOverride w klasie bazowej „{1}”. Język Visual Basic nie obsługuje przesłaniania zdarzeń. Musisz określić implementację zdarzenia w klasie bazowej lub ustawić klasę „{2}” jako zdarzenie MustInherit. @@ -8718,7 +8762,7 @@ '{0}' is not a valid format specifier - '„{0}” nie jest prawidłowym specyfikatorem formatu + „{0}” nie jest prawidłowym specyfikatorem formatu diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.pt-BR.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.pt-BR.xlf index 1bae75be97849..ef4b3ce5f8cd0 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.pt-BR.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.pt-BR.xlf @@ -212,169 +212,169 @@ -vbruntime:<file> Compile with the alternate Visual Basic runtime in <file>. - Visual Basic Compiler Options + Opções do Compilador do Visual Basic - - OUTPUT FILE - --out:<file> Specifies the output file name. --target:exe Create a console application (default). - (Short form: -t) --target:winexe Create a Windows application. --target:library Create a library assembly. --target:module Create a module that can be added to an + – ARQUIVO DE SAÍDA – +-out:<file> Especifica o nome do arquivo de saída. +-target:exe Cria um aplicativo de console (padrão). + (Forma abreviada: -t) +-target:winexe Cria um aplicativo do Windows. +-target:library Cria um assembly de biblioteca. +-target:module Cria um módulo que pode ser adicionado a um assembly. --target:appcontainerexe Create a Windows application that runs in +-target:appcontainerexe Cria um aplicativo do Windows que é executado no AppContainer. --target:winmdobj Create a Windows Metadata intermediate file --doc[+|-] Generates XML documentation file. --doc:<file> Generates XML documentation file to <file>. --refout:<file> Reference assembly output to generate +-target:winmdobj Cria um arquivo intermediário de Metadados do Windows +-doc[+|-] Gera um arquivo de documentação XML. +-doc:<file> Gera um arquivo de documentação XML para <file>. +-refout:<file> Saída do assembly de referência a ser gerado - - INPUT FILES - --addmodule:<file_list> Reference metadata from the specified modules --link:<file_list> Embed metadata from the specified interop - assembly. (Short form: -l) --recurse:<wildcard> Include all files in the current directory - and subdirectories according to the - wildcard specifications. --reference:<file_list> Reference metadata from the specified - assembly. (Short form: -r) --analyzer:<file_list> Run the analyzers from this assembly - (Short form: -a) --additionalfile:<file list> Additional files that don't directly affect code - generation but may be used by analyzers for producing - errors or warnings. + – ARQUIVOS DE ENTRADA – +-addmodule:<file_list> Metadados de referência dos módulos especificados +-link:<file_list> Insere metadados do assembly de interoperabilidade + especificado. (Forma abreviada: -l) +-recurse:<wildcard> Inclui todos os arquivos no diretório e nos subdiretórios + atuais de acordo com as + especificações de curinga. +-reference:<file_list> Metadados de referência do assembly + especificado. (Forma abreviada: -r) +-analyzer:<file_list> Executa os analisadores deste assembly + (Forma abreviada: -a) +-additionalfile:<file list> Arquivos adicionais que não afetam diretamente a geração de + código, mas que podem ser usados por analisadores para produzir + erros ou avisos. - - RESOURCES - --linkresource:<resinfo> Links the specified file as an external - assembly resource. + – RECURSOS – +-linkresource:<resinfo> Vincula o arquivo especificado como um recurso de + assembly externo. resinfo:<file>[,<name>[,public|private]] - (Short form: -linkres) --nowin32manifest The default manifest should not be embedded - in the manifest section of the output PE. --resource:<resinfo> Adds the specified file as an embedded - assembly resource. + (Forma abreviada: -linkres) +-nowin32manifest O manifesto padrão não deve ser inserido + na seção do manifesto do PE de saída. +-resource:<resinfo> Adiciona o arquivo especificado como um recurso do + assembly inserido. resinfo:<file>[,<name>[,public|private]] - (Short form: -res) --win32icon:<file> Specifies a Win32 icon file (.ico) for the - default Win32 resources. --win32manifest:<file> The provided file is embedded in the manifest - section of the output PE. --win32resource:<file> Specifies a Win32 resource file (.res). + (Forma abreviada: -res) +-win32icon:<file> Especifica um arquivo de ícone Win32 (.ico) para os + recursos Win32 padrão. +-win32manifest:<file> O arquivo fornecido é inserido na seção do manifesto + do PE de saída. +-win32resource:<file> Especifica um arquivo de recurso Win32 (.res). - - CODE GENERATION - --optimize[+|-] Enable optimizations. --removeintchecks[+|-] Remove integer checks. Default off. --debug[+|-] Emit debugging information. --debug:full Emit full debugging information (default). --debug:pdbonly Emit full debugging information. --debug:portable Emit cross-platform debugging information. --debug:embedded Emit cross-platform debugging information into - the target .dll or .exe. --deterministic Produce a deterministic assembly - (including module version GUID and timestamp) --refonly Produce a reference assembly in place of the main output --instrument:TestCoverage Produce an assembly instrumented to collect - coverage information --sourcelink:<file> Source link info to embed into PDB. + – GERAÇÃO DE CÓDIGO – +-optimize[+|-] Habilita otimizações. +-removeintchecks[+|-] Remove verificações de inteiros. O padrão é desligado. +-debug[+|-] Emite informações de depuração. +-debug:full Emite informações de depuração completas (padrão). +-debug:pdbonly Emite informações de depuração completas. +-debug:portable Emite informações de depuração de multiplataforma. +-debug:embedded Emite informações de depuração de multiplataforma + no .dll ou no .exe de destino. +-deterministic Produz um assembly determinístico + (incluindo o carimbo de data/hora e o GUID da versão do módulo) +-refonly Produz um assembly de referência no lugar da saída principal +-instrument:TestCoverage Produz um assembly instrumentado para coletar + informações de cobertura +-sourcelink:<file> Informações do link de origem para inserir no PDB. - - ERRORS AND WARNINGS - --nowarn Disable all warnings. --nowarn:<number_list> Disable a list of individual warnings. --warnaserror[+|-] Treat all warnings as errors. --warnaserror[+|-]:<number_list> Treat a list of warnings as errors. --ruleset:<file> Specify a ruleset file that disables specific - diagnostics. + – ERROS E AVISOS – +-nowarn Desabilita todos os avisos. +-nowarn:<number_list> Desabilita uma lista de avisos individuais. +-warnaserror[+|-] Trata todos os avisos como erros. +-warnaserror[+|-]:<number_list> Trata uma lista de avisos como erros. +-ruleset:<file> Especifica um arquivo de conjunto de regras que desabilita um diagnóstico + específico. -errorlog:<file>[,version=<sarif_version>] - Specify a file to log all compiler and analyzer - diagnostics in SARIF format. - sarif_version:{1|2|2.1} Default is 1. 2 and 2.1 - both mean SARIF version 2.1.0. --reportanalyzer Report additional analyzer information, such as - execution time. --skipanalyzers[+|-] Skip execution of diagnostic analyzers. + Especifica um arquivo para registrar todos os diagnósticos do compilador e do + analisador em formato SARIF. + sarif_version:{1|2|2.1} O padrão é 1.2 e 2.1, + ambos significam a versão SARIF 2.1.0. +-reportanalyzer Relata informações adicionais do analisador, como o + tempo de execução. +-skipanalyzers[+|-] Ignora a execução de analisadores de diagnóstico. - - LANGUAGE - --define:<symbol_list> Declare global conditional compilation - symbol(s). symbol_list:name=value,... - (Short form: -d) --imports:<import_list> Declare global Imports for namespaces in - referenced metadata files. + – LINGUAGEM – +-define:<symbol_list> Declara os símbolos globais de + compilação condicional. symbol_list:name=value,... + (Forma abreviada: -d) +-imports:<import_list> Declara as Importações globais dos namespaces nos + arquivos de metadados referenciados. import_list:namespace,... --langversion:? Display the allowed values for language version --langversion:<string> Specify language version such as - `default` (latest major version), or - `latest` (latest version, including minor versions), - or specific versions like `14` or `15.3` --optionexplicit[+|-] Require explicit declaration of variables. --optioninfer[+|-] Allow type inference of variables. --rootnamespace:<string> Specifies the root Namespace for all type - declarations. --optionstrict[+|-] Enforce strict language semantics. --optionstrict:custom Warn when strict language semantics are not - respected. --optioncompare:binary Specifies binary-style string comparisons. - This is the default. --optioncompare:text Specifies text-style string comparisons. +-langversion:? Exibe os valores permitidos para a versão da linguagem +-langversion:<string> Especifica a versão da linguagem como + `padrão` (versão principal mais recente) ou + `mais recente` (versão mais recente, incluindo versões secundárias), + ou versões específicas, como `14` ou `15.3` +-optionexplicit[+|-] Exige a declaração explícita de variáveis. +-optioninfer[+|-] Permite a inferência de tipos de variáveis. +-rootnamespace:<string> Especifica o Namespace raiz para todos os tipos de + declarações. +-optionstrict[+|-] Impõe a semântica de linguagem estrita. +-optionstrict:custom Avisa quando a semântica de linguagem estrita não é + respeitada. +-optioncompare:binary Especifica comparações de cadeia de caracteres de estilo binário. + Esse é o padrão. +-optioncompare:text Especifica comparações de cadeia de caracteres de estilo de texto. - - MISCELLANEOUS - --help Display this usage message. (Short form: -?) --noconfig Do not auto-include VBC.RSP file. --nologo Do not display compiler copyright banner. --quiet Quiet output mode. --verbose Display verbose messages. --parallel[+|-] Concurrent build. --version Display the compiler version number and exit. + – DIVERSOS – +-help Exibe esta mensagem de uso. (Forma abreviada: -?) +-noconfig Não inclui o arquivo VBC.RSP automaticamente. +-nologo Não exibe o banner de direitos autorais do compilador. +-quiet Modo de saída silencioso. +-verbose Exibe mensagens detalhadas. +-parallel[+|-] Build simultâneo. +-version Exibe o número de versão do compilador e a saída. - - ADVANCED - --baseaddress:<number> The base address for a library or module - (hex). --checksumalgorithm:<alg> Specify algorithm for calculating source file - checksum stored in PDB. Supported values are: - SHA1 or SHA256 (default). --codepage:<number> Specifies the codepage to use when opening - source files. --delaysign[+|-] Delay-sign the assembly using only the public - portion of the strong name key. --publicsign[+|-] Public-sign the assembly using only the public - portion of the strong name key. --errorreport:<string> Specifies how to handle internal compiler - errors; must be prompt, send, none, or queue - (default). --filealign:<number> Specify the alignment used for output file - sections. --highentropyva[+|-] Enable high-entropy ASLR. --keycontainer:<string> Specifies a strong name key container. --keyfile:<file> Specifies a strong name key file. --libpath:<path_list> List of directories to search for metadata - references. (Semi-colon delimited.) --main:<class> Specifies the Class or Module that contains - Sub Main. It can also be a Class that - inherits from System.Windows.Forms.Form. - (Short form: -m) --moduleassemblyname:<string> Name of the assembly which this module will - be a part of. --netcf Target the .NET Compact Framework. --nostdlib Do not reference standard libraries - (system.dll and VBC.RSP file). + – AVANÇADO – +-baseaddress:<number> O endereço básico de uma biblioteca ou um módulo + (hexadecimal). +-checksumalgorithm:<alg> Especifica o algoritmo para calcular a soma de verificação do + arquivo de origem armazenado no PDB. Os valores com suporte são: + SHA1 ou SHA256 (padrão). +-codepage:<number> Especifica a página de código a ser usada ao abrir os + arquivos de origem. +-delaysign[+|-] Sinaliza o assembly com atraso usando somente a parte pública + da chave de nome forte. +-publicsign[+|-] Sinaliza o assembly como público usando somente a parte pública + da chave de nome forte. +-errorreport:<string> Especifica como lidar com os erros internos do + compilador; precisa ser prompt, send, none ou queue + (padrão). +-filealign:<number> Especifica o alinhamento usado nas seções do arquivo de + saída. +-highentropyva[+|-] Habilita a ASLR de alta entropia. +-keycontainer:<string> Especifica um contêiner de chave de nome forte. +-keyfile:<file> Especifica um arquivo de chave de nome forte. +-libpath:<path_list> Lista de diretórios nos quais pesquisar as referências de + metadados. (Delimitados por ponto e vírgula.) +-main:<class> Especifica a Classe ou o Módulo que contém + Sub Main. Também pode ser uma Classe + herdada de System.Windows.Forms.Form. + (Forma abreviada: -m) +-moduleassemblyname:<string> Nome do assembly do qual o módulo + fará parte. +-netcf Direciona ao .NET Compact Framework. +-nostdlib Não referencia bibliotecas padrão + (arquivo system.dll e VBC.RSP). -pathmap:<K1>=<V1>,<K2>=<V2>,... - Specify a mapping for source path names output by - the compiler. --platform:<string> Limit which platforms this code can run on; - must be x86, x64, Itanium, arm, arm64 - AnyCPU32BitPreferred or anycpu (default). --preferreduilang Specify the preferred output language name. --nosdkpath Disable searching the default SDK path for standard library assemblies. --sdkpath:<path> Location of the .NET Framework SDK directory + Especifica um mapeamento para nomes de caminhos de origem produzidos pelo + compilador. +-platform:<string> Limita em quais plataformas o código pode ser executado; + precisa ser x86, x64, Itanium, arm, arm64, + AnyCPU32BitPreferred ou anycpu (padrão). +-preferreduilang Especifica o nome da linguagem de saída preferencial. +-nosdkpath Desabilita a pesquisa no caminho de SDK padrão para assemblies de biblioteca padrão. +-sdkpath:<path> Localização do diretório do SDK do .NET Framework (mscorlib.dll). --subsystemversion:<version> Specify subsystem version of the output PE. +-subsystemversion:<version> Especifica a versão do subsistema do PE de saída. version:<number>[.<number>] --utf8output[+|-] Emit compiler output in UTF8 character - encoding. -@<file> Insert command-line settings from a text file --vbruntime[+|-|*] Compile with/without the default Visual Basic - runtime. --vbruntime:<file> Compile with the alternate Visual Basic - runtime in <file>. +-utf8output[+|-] Emite a saída do compilador em codificação de caracteres + UTF8. +@<file> Insere configurações de linha de comando de um arquivo de texto +-vbruntime[+|-|*] Compila com/sem o runtime padrão do + Visual Basic. +-vbruntime:<file> Compila com o runtime alternativo do + Visual Basic em <file>. @@ -463,6 +463,50 @@ Argumento de tipo não pode ser Nothing + + The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + O assembly '{0}' contendo o tipo '{1}' referencia o .NET Framework, mas não há suporte para isso. + {1} is the type that was loaded, {0} is the containing assembly. + + + The loaded assembly references .NET Framework, which is not supported. + O assembly carregado referencia o .NET Framework, mas não há suporte para isso. + + + + Generator '{0}' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + O gerador '{0}' não pôde gerar a origem. Ele não contribuirá com a saída e poderão ocorrer erros de compilação como resultado. A exceção foi do tipo '{1}', com a mensagem '{2}' + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + O gerador gerou a seguinte exceção: +'{0}'. + {0} is the string representation of the exception that was thrown. + + + Generator failed to generate source. + O gerador não pôde gerar a origem. + + + + Generator '{0}' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + Falha na inicialização do gerador '{0}'. Ele não contribuirá com a saída e poderão ocorrer erros de compilação como resultado. A exceção foi do tipo '{1}', com a mensagem '{2}' + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + O gerador gerou a seguinte exceção: +'{0}'. + {0} is the string representation of the exception that was thrown. + + + Generator failed to initialize. + Falha na inicialização do gerador. + + Wrong number of type arguments Número errado de argumentos de tipo @@ -615,7 +659,7 @@ '{0}' is not a valid value for /moduleassemblyname - '"{0}" não é um valor válido para /moduleassemblyname + "{0}" não é um valor válido para /moduleassemblyname @@ -705,7 +749,7 @@ 'TypeOf ... Is' requires its left operand to have a reference type, but this operand has the value type '{0}'. - '"TypeOf ... Is" requer que seu operando esquerdo tenha um tipo de referência, mas este operando tem o tipo de valor "{0}". + "TypeOf ... Is" requer que seu operando esquerdo tenha um tipo de referência, mas este operando tem o tipo de valor "{0}". @@ -815,12 +859,12 @@ '{0}' is valid only within an instance method. - '"{0}" é válido somente em um método de instância. + "{0}" é válido somente em um método de instância. '{0}' is not valid within a structure. - '"{0}" não é válido dentro de uma estrutura. + "{0}" não é válido dentro de uma estrutura. @@ -835,7 +879,7 @@ '{0}' statement requires an array. - '"{0}" instrução requer uma matriz. + "{0}" instrução requer uma matriz. @@ -1040,7 +1084,7 @@ '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type '{0}'. - '"!" requer que seu operando esquerdo tenha um parâmetro de tipo, classe ou tipo de interface, mas este operando tem o tipo "{0}". + "!" requer que seu operando esquerdo tenha um parâmetro de tipo, classe ou tipo de interface, mas este operando tem o tipo "{0}". @@ -1055,42 +1099,42 @@ '{0}' is an Enum type and cannot be used as an expression. - '"{0}" é um tipo Enum e não pode ser usado como uma expressão. + "{0}" é um tipo Enum e não pode ser usado como uma expressão. '{0}' is a type and cannot be used as an expression. - '"{0}" é um tipo e não pode ser usado como uma expressão. + "{0}" é um tipo e não pode ser usado como uma expressão. '{0}' is a class type and cannot be used as an expression. - '"{0}" é um tipo de classe e não pode ser usado como uma expressão. + "{0}" é um tipo de classe e não pode ser usado como uma expressão. '{0}' is a structure type and cannot be used as an expression. - '"{0}" é um tipo de estrutura e não pode ser usado como uma expressão. + "{0}" é um tipo de estrutura e não pode ser usado como uma expressão. '{0}' is an interface type and cannot be used as an expression. - '"{0}" é um tipo de interface e não pode ser usado como uma expressão. + "{0}" é um tipo de interface e não pode ser usado como uma expressão. '{0}' is a namespace and cannot be used as an expression. - '"{0}" é um namespace e não pode ser usado como uma expressão. + "{0}" é um namespace e não pode ser usado como uma expressão. '{0}' is not a valid name and cannot be used as the root namespace name. - '"{0}" não é um nome válido e não pode ser usado como o nome do namespace raiz. + "{0}" não é um nome válido e não pode ser usado como o nome do namespace raiz. '{0}' is an XML prefix and cannot be used as an expression. Use the GetXmlNamespace operator to create a namespace object. - '"{0}" é um prefixo XML e não pode ser usado como uma expressão. Use o operador GetXmlNamespace para criar um objeto namespace. + "{0}" é um prefixo XML e não pode ser usado como uma expressão. Use o operador GetXmlNamespace para criar um objeto namespace. @@ -1350,17 +1394,17 @@ '{0}' is not valid on a constant declaration. - '"{0}" não é válido em uma declaração de constante. + "{0}" não é válido em uma declaração de constante. '{0}' is not valid on a WithEvents declaration. - '"{0}" não é válido em uma declaração WithEvents. + "{0}" não é válido em uma declaração WithEvents. '{0}' is not valid on a member variable declaration. - '"{0}" não é válido em uma declaração de variável de membro. + "{0}" não é válido em uma declaração de variável de membro. @@ -1400,27 +1444,27 @@ '{0}' is not valid on a method declaration. - '"{0}" não é válido em uma declaração de método. + "{0}" não é válido em uma declaração de método. '{0}' is not valid on an event declaration. - '"{0}" não é válido em uma declaração de evento. + "{0}" não é válido em uma declaração de evento. '{0}' is not valid on a Declare. - '"{0}" não é válido em Declare. + "{0}" não é válido em Declare. '{0}' is not valid on a local constant declaration. - '"{0}" não é válido em uma declaração de constante local. + "{0}" não é válido em uma declaração de constante local. '{0}' is not valid on a local variable declaration. - '"{0}" não é válido em uma declaração de variável local. + "{0}" não é válido em uma declaração de variável local. @@ -1474,22 +1518,22 @@ '{0}' is already declared as '{1}' in this {2}. - '"{0}" já está declarado neste como "{1}" neste {2}. + "{0}" já está declarado neste como "{1}" neste {2}. '{0}' cannot override '{1}' because they have different access levels. - '"{0}" não pode substituir "{1}" porque têm níveis de acesso diferentes. + "{0}" não pode substituir "{1}" porque têm níveis de acesso diferentes. '{0}' cannot override '{1}' because it is declared 'NotOverridable'. - '"{0}" não pode substituir "{1}" porque está declarado como "NotOverridable". + "{0}" não pode substituir "{1}" porque está declarado como "NotOverridable". '{0}' has multiple definitions with identical signatures. - '"{0}" tem várias definições com assinaturas idênticas. + "{0}" tem várias definições com assinaturas idênticas. @@ -1499,17 +1543,17 @@ '{0}' is not valid on an interface method declaration. - '"{0}" não é válido em uma declaração de método de interface. + "{0}" não é válido em uma declaração de método de interface. '{0}' is not a parameter of '{1}'. - '"{0}" não é um parâmetro de "{1}". + "{0}" não é um parâmetro de "{1}". '{0}' is not valid on an interface property declaration. - '"{0}" não é válido em uma declaração de propriedade de interface. + "{0}" não é válido em uma declaração de propriedade de interface. @@ -1519,7 +1563,7 @@ '{0}' is not valid on an interface event declaration. - '"{0}" não é válido em uma declaração de evento de interface. + "{0}" não é válido em uma declaração de evento de interface. @@ -1549,7 +1593,7 @@ 'Sub New' cannot be declared 'Partial'. - '"Sub New" não pode ser declarado como "Partial". + "Sub New" não pode ser declarado como "Partial". @@ -1618,17 +1662,17 @@ '{0}' cannot inherit from {2} '{1}' because '{1}' is declared 'NotInheritable'. - '"{0}" não pode herdar de {2} "{1}" porque "{1}" é declarado "NotInheritable". + "{0}" não pode herdar de {2} "{1}" porque "{1}" é declarado "NotInheritable". '{0}' and '{1}' cannot overload each other because they differ only by optional parameters. - '"{0}" e "{1}" não podem sobrecarregar um ao outro porque diferem somente por parâmetros opcionais. + "{0}" e "{1}" não podem sobrecarregar um ao outro porque diferem somente por parâmetros opcionais. '{0}' and '{1}' cannot overload each other because they differ only by return types. - '"{0}" e "{1}" não podem sobrecarregar um ao outro porque diferem somente por tipos de retorno. + "{0}" e "{1}" não podem sobrecarregar um ao outro porque diferem somente por tipos de retorno. @@ -1643,7 +1687,7 @@ '{0}' and '{1}' cannot overload each other because they differ only by the default values of optional parameters. - '"{0}" e "{1}" não podem sobrecarregar um ao outro porque diferem somente pelos valores padrões de parâmetros opcionais. + "{0}" e "{1}" não podem sobrecarregar um ao outro porque diferem somente pelos valores padrões de parâmetros opcionais. @@ -1653,12 +1697,12 @@ '{0}' cannot override '{1}' because they differ by the default values of optional parameters. - '"{0}" não pode substituir "{1}" porque diferem pelos valores padrões de parâmetros opcionais. + "{0}" não pode substituir "{1}" porque diferem pelos valores padrões de parâmetros opcionais. '{0}' cannot override '{1}' because they differ by optional parameters. - '"{0}" não pode substituir "{1}" porque diferem por parâmetros opcionais. + "{0}" não pode substituir "{1}" porque diferem por parâmetros opcionais. @@ -1693,7 +1737,7 @@ '{0}' and '{1}' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'. - '"{0}" e "{1}" não podem sobrecarregar um ao outro porque diferem somente por parâmetros declarados "ByRef" ou "ByVal". + "{0}" e "{1}" não podem sobrecarregar um ao outro porque diferem somente por parâmetros declarados "ByRef" ou "ByVal". @@ -1708,17 +1752,17 @@ 'Default' can be applied to only one property name in a {0}. - '"Default" pode ser aplicado a somente um nome de propriedade em um {0}. + "Default" pode ser aplicado a somente um nome de propriedade em um {0}. '{0}' and '{1}' cannot overload each other because only one is declared 'Default'. - '"{0}" e "{1}" não podem sobrecarregar um ao outro porque somente um está declarado como "Default". + "{0}" e "{1}" não podem sobrecarregar um ao outro porque somente um está declarado como "Default". '{0}' cannot override '{1}' because they differ by 'ReadOnly' or 'WriteOnly'. - '"{0}" não pode substituir "{1}" porque diferem por "ReadOnly" ou "WriteOnly". + "{0}" não pode substituir "{1}" porque diferem por "ReadOnly" ou "WriteOnly". @@ -1728,12 +1772,12 @@ 'Sub New' cannot be declared '{0}'. - '"Sub New" não pode ser declarados "{0}". + "Sub New" não pode ser declarados "{0}". '{0}' and '{1}' cannot overload each other because they differ only by 'ReadOnly' or 'WriteOnly'. - '"{0}" e "{1}" não pode sobrecarregar um ao outro porque diferem apenas por "ReadOnly" ou "WriteOnly". + "{0}" e "{1}" não pode sobrecarregar um ao outro porque diferem apenas por "ReadOnly" ou "WriteOnly". @@ -1743,7 +1787,7 @@ '{0}' and '{1}' cannot overload each other because they differ only by parameters declared 'ParamArray'. - '"{0}" e "{1}" não podem sobrecarregar um ao outro porque diferem somente por parâmetros declarados "ParamArray". + "{0}" e "{1}" não podem sobrecarregar um ao outro porque diferem somente por parâmetros declarados "ParamArray". @@ -1798,7 +1842,7 @@ '{0}' is not valid on a Delegate declaration. - '"{0}" não é válido em uma declaração Delegate. + "{0}" não é válido em uma declaração Delegate. @@ -1808,17 +1852,17 @@ '{0}' is not accessible in this context because it is '{1}'. - '"{0}" não está acessível neste contexto porque é "{1}". + "{0}" não está acessível neste contexto porque é "{1}". '{0}.{1}' is not accessible in this context because it is '{2}'. - '"{0}.{1}" não é acessível neste contexto porque é "{2}". + "{0}.{1}" não é acessível neste contexto porque é "{2}". 'Catch' cannot catch type '{0}' because it is not 'System.Exception' or a class that inherits from 'System.Exception'. - '"Catch" não pode capturar o tipo "{0}" porque não é "System.Exception" ou uma classe que herda de "System.Exception". + "Catch" não pode capturar o tipo "{0}" porque não é "System.Exception" ou uma classe que herda de "System.Exception". @@ -1828,32 +1872,32 @@ '{0}' is not valid on a Structure declaration. - '"{0}" não é válido em uma declaração Structure. + "{0}" não é válido em uma declaração Structure. '{0}' is not valid on an Enum declaration. - '"{0}" não é válido em uma declaração Enum. + "{0}" não é válido em uma declaração Enum. '{0}' is not valid on an Interface declaration. - '"{0}" não é válido em uma declaração Interface. + "{0}" não é válido em uma declaração Interface. '{0}' cannot override '{1}' because they differ by a parameter that is marked as 'ByRef' versus 'ByVal'. - '"{0}" não pode substituir "{1}" porque diferem por um parâmetros que é marcado como "ByRef" versus "ByVal". + "{0}" não pode substituir "{1}" porque diferem por um parâmetros que é marcado como "ByRef" versus "ByVal". 'MyBase' cannot be used with method '{0}' because it is declared 'MustOverride'. - '"MyBase" não pode ser usado com o método "{0}" porque está declarado como "MustOverride". + "MyBase" não pode ser usado com o método "{0}" porque está declarado como "MustOverride". '{0}' cannot implement '{1}' because there is no matching {2} on interface '{3}'. - '"{0}" não pode implementar "{1}" porque não há correspondência {2} na interface "{3}". + "{0}" não pode implementar "{1}" porque não há correspondência {2} na interface "{3}". @@ -1883,7 +1927,7 @@ 'Sub Main' was not found in '{0}'. - '"Sub Main" não foi encontrado em "{0}". + "Sub Main" não foi encontrado em "{0}". @@ -1923,7 +1967,7 @@ '{0}' cannot override '{1}' because they differ by their return types. - '"{0}" não pode substituir "{1}" porque diferem por seus tipos de retorno. + "{0}" não pode substituir "{1}" porque diferem por seus tipos de retorno. @@ -1958,7 +2002,7 @@ '{0}' is not declared. It may be inaccessible due to its protection level. - '"{0}" não está declarado. Ele pode estar inacessível devido ao seu nível de proteção. + "{0}" não está declarado. Ele pode estar inacessível devido ao seu nível de proteção. @@ -1978,7 +2022,7 @@ '{0}' is not a member of '{1}'. - '"{0}" não é um membro de "{1}". + "{0}" não é um membro de "{1}". @@ -1998,7 +2042,7 @@ '{1}' for the Imports '{0}' does not refer to a Namespace, Class, Structure, Enum or Module. - '"{1}" para Imports "{0}" não se refere a um Namespace, Classe, Estrutura, Enum ou Módulo. + "{1}" para Imports "{0}" não se refere a um Namespace, Classe, Estrutura, Enum ou Módulo. @@ -2048,7 +2092,7 @@ 'Default' cannot be combined with '{0}'. - '"Default" não pode ser combinado com "{0}". + "Default" não pode ser combinado com "{0}". @@ -2078,12 +2122,12 @@ 'Shared' cannot be combined with '{0}' on a method declaration. - '"Shared" não pode ser combinado com "{0}" em uma declaração de método. + "Shared" não pode ser combinado com "{0}" em uma declaração de método. 'Shared' cannot be combined with '{0}' on a property declaration. - '"Shared" não pode ser combinado com "{0}" em uma declaração de propriedade. + "Shared" não pode ser combinado com "{0}" em uma declaração de propriedade. @@ -2103,7 +2147,7 @@ '{0}' cannot inherit from {1} '{2}' because it expands the access of the base {1} to {3} '{4}'. - '"{0}" não pode herdar de {1} "{2}" porque ele expande o acesso da base {1} para {3} "{4}". + "{0}" não pode herdar de {1} "{2}" porque ele expande o acesso da base {1} para {3} "{4}". @@ -2205,7 +2249,7 @@ '{0}' cannot be indexed because it has no default property. - '"{0}" não pode ser indexado porque não tem nenhuma propriedade padrão. + "{0}" não pode ser indexado porque não tem nenhuma propriedade padrão. @@ -2220,7 +2264,7 @@ '{0}' is ambiguous. - '"{0}" é ambíguo. + "{0}" é ambíguo. @@ -2230,22 +2274,22 @@ '{0}' is ambiguous in the namespace '{1}'. - '"{0}" é ambíguo no namespace "{1}". + "{0}" é ambíguo no namespace "{1}". '{0}' is ambiguous, imported from the namespaces or types '{1}'. - '"{0}" é ambíguo, importado dos namespaces ou tipos "{1}". + "{0}" é ambíguo, importado dos namespaces ou tipos "{1}". '{0}' is ambiguous between declarations in Modules '{1}'. - '"{0}" é ambíguo entre declarações em Módulos "{1}". + "{0}" é ambíguo entre declarações em Módulos "{1}". '{0}' is ambiguous between declarations in namespaces '{1}'. - '"{0}" é ambíguo entre declarações e namespace "{1}". + "{0}" é ambíguo entre declarações e namespace "{1}". @@ -2320,12 +2364,12 @@ '{0}.{1}' cannot be implemented more than once. - '"{0}.{1}" não pode ser implementado mais de uma vez. + "{0}.{1}" não pode ser implementado mais de uma vez. '{0}' cannot be inherited more than once. - '"{0}" não pode ser herdado mais de uma vez. + "{0}" não pode ser herdado mais de uma vez. @@ -2570,7 +2614,7 @@ '{0}' is an unsupported type. - '"{0}" é um tipo sem suporte. + "{0}" é um tipo sem suporte. @@ -2605,7 +2649,7 @@ '{0}' has a return type that is not supported or parameter types that are not supported. - '"{0}" tem um tipo de retorno que não é suportado ou tipos de parâmetro que não são suportados. + "{0}" tem um tipo de retorno que não é suportado ou tipos de parâmetro que não são suportados. @@ -2687,7 +2731,7 @@ '{0}' is obsolete: '{1}'. - '"{0}" está obsoleto: "{1}". + "{0}" está obsoleto: "{1}". @@ -2717,7 +2761,7 @@ '{0}' is not an event of '{1}'. - '"{0}" não é um evento de "{1}". + "{0}" não é um evento de "{1}". @@ -2752,7 +2796,7 @@ '{0}' is ambiguous across the inherited interfaces '{1}' and '{2}'. - '"{0}" é ambíguo nas interfaces herdadas "{1}" e "{2}". + "{0}" é ambíguo nas interfaces herdadas "{1}" e "{2}". @@ -2782,7 +2826,7 @@ '{0}' cannot override '{1}' because they differ by the types of optional parameters. - '"{0}" não pode substituir "{1}" porque diferem pelos tipos de parâmetros opcionais. + "{0}" não pode substituir "{1}" porque diferem pelos tipos de parâmetros opcionais. @@ -2802,7 +2846,7 @@ '{0}' is already declared as a parameter of this method. - '"{0}" já está declarado como um parâmetro deste método. + "{0}" já está declarado como um parâmetro deste método. @@ -2822,7 +2866,7 @@ 'Sub Main' is declared more than once in '{0}': {1} - '"Sub Main" está declarado mais de uma vez em "{0}": {1} + "Sub Main" está declarado mais de uma vez em "{0}": {1} @@ -2842,22 +2886,22 @@ 'GoTo {0}' is not valid because '{0}' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement. - '"GoTo {0}" não é válido porque "{0}" está dentro de uma instrução "Try", "Catch" ou "Finally" que não contém essa instrução. + "GoTo {0}" não é válido porque "{0}" está dentro de uma instrução "Try", "Catch" ou "Finally" que não contém essa instrução. 'GoTo {0}' is not valid because '{0}' is inside a 'SyncLock' statement that does not contain this statement. - '"GoTo {0}" não é válido porque "{0}" está dentro de uma instrução "SyncLock" que não contém essa instrução. + "GoTo {0}" não é válido porque "{0}" está dentro de uma instrução "SyncLock" que não contém essa instrução. 'GoTo {0}' is not valid because '{0}' is inside a 'With' statement that does not contain this statement. - '"GoTo {0}" não é válido porque "{0}" está dentro de uma instrução "With" que não contém essa instrução. + "GoTo {0}" não é válido porque "{0}" está dentro de uma instrução "With" que não contém essa instrução. 'GoTo {0}' is not valid because '{0}' is inside a 'For' or 'For Each' statement that does not contain this statement. - '"GoTo {0}" não é válido porque "{0}" está dentro de uma instrução "For" ou "For Each" que não contém essa instrução. + "GoTo {0}" não é válido porque "{0}" está dentro de uma instrução "For" ou "For Each" que não contém essa instrução. @@ -2942,7 +2986,7 @@ '{1}' for the Imports alias to '{0}' does not refer to a Namespace, Class, Structure, Interface, Enum or Module. - '"{1}" para o alias Imports para "{0}" não se refere a um Namespace, Classe, Estrutura, Interface, Enum ou Módulo. + "{1}" para o alias Imports para "{0}" não se refere a um Namespace, Classe, Estrutura, Interface, Enum ou Módulo. @@ -3027,7 +3071,7 @@ '{0}' cannot override '{1}' because they differ by parameters declared 'ParamArray'. - '"{0}" não pode substituir "{1}" porque diferem por parâmetros declarados "ParamArray". + "{0}" não pode substituir "{1}" porque diferem por parâmetros declarados "ParamArray". @@ -3042,32 +3086,32 @@ '{0}' cannot expose type '{1}' outside the project through {2} '{3}'. - '"{0}" não pode expor o tipo "{1}" fora do projeto através de {2} "{3}". + "{0}" não pode expor o tipo "{1}" fora do projeto através de {2} "{3}". '{0}' cannot inherit from {1} '{2}' because it expands the access of the base {1} outside the assembly. - '"{0}" não pode herdar de {1} "{2}" porque ele expande o acesso da base {1} fora do assembly. + "{0}" não pode herdar de {1} "{2}" porque ele expande o acesso da base {1} fora do assembly. '{0}' accessor of '{1}' is obsolete: '{2}'. - '"{0}" acessador de "{1}" está obsoleto: "{2}". + "{0}" acessador de "{1}" está obsoleto: "{2}". '{0}' accessor of '{1}' is obsolete. - '"{0}" acessador de "{1}" está obsoleto. + "{0}" acessador de "{1}" está obsoleto. '{0}' cannot expose the underlying delegate type '{1}' of the event it is implementing to {2} '{3}' through {4} '{5}'. - '"{0}" não pode expor o tipo delegado subjacente "{1}" do evento que está implementando para {2} "{3}" através de {4} "{5}". + "{0}" não pode expor o tipo delegado subjacente "{1}" do evento que está implementando para {2} "{3}" através de {4} "{5}". '{0}' cannot expose the underlying delegate type '{1}' of the event it is implementing outside the project through {2} '{3}'. - '"{0}" não pode expor o tipo delegado subjacente "{1}" do evento que está implementando fora do projeto por meio de {2} "{3}". + "{0}" não pode expor o tipo delegado subjacente "{1}" do evento que está implementando fora do projeto por meio de {2} "{3}". @@ -3097,12 +3141,12 @@ '{0}' cannot inherit from {1} '{2}' because it expands the access of type '{3}' to {4} '{5}'. - '"{0}" não pode herdar de {1} "{2}" porque ele expande o acesso de tipo "{3}" para {4} "{5}". + "{0}" não pode herdar de {1} "{2}" porque ele expande o acesso de tipo "{3}" para {4} "{5}". '{0}' cannot inherit from {1} '{2}' because it expands the access of type '{3}' outside the assembly. - '"{0}" não pode herdar de {1} "{2}" porque ele expande o acesso de tipo "{3}" fora do assembly. + "{0}" não pode herdar de {1} "{2}" porque ele expande o acesso de tipo "{3}" fora do assembly. @@ -3112,12 +3156,12 @@ 'MustInherit' cannot be specified for partial type '{0}' because it cannot be combined with 'NotInheritable' specified for one of its other partial types. - '"MustInherit" não pode ser especificado para o tipo parcial "{0}" porque não pode ser combinado com "NotInheritable" especificado para um dos seus outros tipos parciais. + "MustInherit" não pode ser especificado para o tipo parcial "{0}" porque não pode ser combinado com "NotInheritable" especificado para um dos seus outros tipos parciais. 'MustOverride' cannot be specified on this member because it is in a partial type that is declared 'NotInheritable' in another partial definition. - '"MustOverride" não pode ser especificado neste membro porque está em um tipo parcial declarado "NotInheritable" em outra definição parcial. + "MustOverride" não pode ser especificado neste membro porque está em um tipo parcial declarado "NotInheritable" em outra definição parcial. @@ -3213,7 +3257,7 @@ '{0}' in class '{1}' cannot override '{2}' in class '{3}' because an intermediate class '{4}' overrides '{2}' in class '{3}' but is not accessible. - '"{0}" na classe "{1}" não pode substituir "{2}" na classe "{3}" porque uma classe intermediária "{4}" substitui "{2}" na classe "{3}", mas não está acessível. + "{0}" na classe "{1}" não pode substituir "{2}" na classe "{3}" porque uma classe intermediária "{4}" substitui "{2}" na classe "{3}", mas não está acessível. @@ -3508,17 +3552,17 @@ '{0}' is obsolete. - '"{0}" está obsoleto. + "{0}" está obsoleto. '{0}' is a module and cannot be referenced as an assembly. - '"{0}" é um módulo e não pode ser referenciado como um assembly. + "{0}" é um módulo e não pode ser referenciado como um assembly. '{0}' is an assembly and cannot be referenced as a module. - '"{0}" é um assembly e não pode ser referenciado como um módulo. + "{0}" é um assembly e não pode ser referenciado como um módulo. @@ -3528,7 +3572,7 @@ '{0}' is not a local variable or parameter, and so cannot be used as a 'Catch' variable. - '"{0}" não é uma variável local ou parâmetro e, portanto, não pode ser usado como uma variável "Catch". + "{0}" não é uma variável local ou parâmetro e, portanto, não pode ser usado como uma variável "Catch". @@ -3548,7 +3592,7 @@ '{0}' cannot override '{1}' because it is not declared 'Overridable'. - '"{0}" não pode substituir "{1}" porque não está declarado como "Overridable". + "{0}" não pode substituir "{1}" porque não está declarado como "Overridable". @@ -3788,7 +3832,7 @@ '{0}' cannot refer to itself through its default instance; use 'Me' instead. - '"{0}" não pode referir-se a si mesmo por meio de sua instância padrão; ao invés disso, use "Me". + "{0}" não pode referir-se a si mesmo por meio de sua instância padrão; ao invés disso, use "Me". @@ -3803,7 +3847,7 @@ '{0}' cannot be applied to the 'AddHandler', 'RemoveHandler', or 'RaiseEvent' definitions. If required, apply the attribute directly to the event. - '"{0}" não pode ser aplicado às definições "AddHandler", "RemoveHandler" ou "RaiseEvent". Se necessário, aplique o atributo diretamente ao evento. + "{0}" não pode ser aplicado às definições "AddHandler", "RemoveHandler" ou "RaiseEvent". Se necessário, aplique o atributo diretamente ao evento. @@ -4083,7 +4127,7 @@ '{0}' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. - '"{0}" não pode ser anulável e não pode ser usado como o tipo de dados de um elemento de matriz, campo, membro de tipo anônimo, argumento de tipo, parâmetro "ByRef" ou instrução return. + "{0}" não pode ser anulável e não pode ser usado como o tipo de dados de um elemento de matriz, campo, membro de tipo anônimo, argumento de tipo, parâmetro "ByRef" ou instrução return. @@ -4113,7 +4157,7 @@ '{0}' cannot shadow a method declared 'MustOverride'. - '"{0}" não pode sombrear um método declarado como "MustOverride". + "{0}" não pode sombrear um método declarado como "MustOverride". @@ -4123,7 +4167,7 @@ '{0}' and '{1}' cannot be combined. - '"{0}" e "{1}" não podem ser combinados. + "{0}" e "{1}" não podem ser combinados. @@ -4133,7 +4177,7 @@ '{0}' must be declared 'MustInherit' because it contains methods declared 'MustOverride'. - '"{0}" deve ser declarado "MustInherit" porque contém métodos declarados "MustOverride". + "{0}" deve ser declarado "MustInherit" porque contém métodos declarados "MustOverride". @@ -4143,12 +4187,12 @@ '{0}', implicitly declared for {1} '{2}', cannot shadow a 'MustOverride' method in the base {3} '{4}'. - '"{0}", implicitamente declarado para {1} "{2}", não pode sombrear um método "MustOverride" na base {3} "{4}". + "{0}", implicitamente declarado para {1} "{2}", não pode sombrear um método "MustOverride" na base {3} "{4}". '{0}' cannot override '{1}' because it is not accessible in this context. - '"{0}" não pode substituir "{1}" porque não está acessível neste contexto. + "{0}" não pode substituir "{1}" porque não está acessível neste contexto. @@ -4158,17 +4202,17 @@ 'IsNot' requires operands that have reference types, but this operand has the value type '{0}'. - '"IsNot" requer operandos que tenham tipos de referência, mas este operando tem o tipo de valor "{0}". + "IsNot" requer operandos que tenham tipos de referência, mas este operando tem o tipo de valor "{0}". '{0}' conflicts with the reserved member by this name that is implicitly declared in all enums. - '"{0}" está em conflito com o membro reservado por este nome que é declarado implicitamente em todos os enums. + "{0}" está em conflito com o membro reservado por este nome que é declarado implicitamente em todos os enums. '{0}' is already declared in this {1}. - '"{0}" já está declarado neste {1}. + "{0}" já está declarado neste {1}. @@ -4188,7 +4232,7 @@ '{0}' in assembly '{1}' has been forwarded to itself and so is an unsupported type. - '"{0}" no assembly "{1}" foi encaminhado para si mesmo e, portanto, é um tipo sem suporte. + "{0}" no assembly "{1}" foi encaminhado para si mesmo e, portanto, é um tipo sem suporte. @@ -4208,7 +4252,7 @@ '{0}' is ambiguous because multiple kinds of members with this name exist in {1} '{2}'. - '"{0}" é ambíguo porque vários tipos de membros com este nome existem em {1} "{2}". + "{0}" é ambíguo porque vários tipos de membros com este nome existem em {1} "{2}". @@ -4243,7 +4287,7 @@ '{0}' cannot be declared 'Partial' because partial methods must be Subs. - '"{0}" não pode ser declarado como "Partial" porque métodos parciais devem ser Subs. + "{0}" não pode ser declarado como "Partial" porque métodos parciais devem ser Subs. @@ -4258,7 +4302,7 @@ 'AddressOf' cannot be applied to '{0}' because '{0}' is a partial method without an implementation. - '"AddressOf" não pode ser aplicado a "{0}" porque "{0}" é um método parcial sem uma implementação. + "AddressOf" não pode ser aplicado a "{0}" porque "{0}" é um método parcial sem uma implementação. @@ -4298,17 +4342,17 @@ '{0}' cannot be used as an attribute because it is not a class. - '"{0}" não pode ser usado como um atributo porque não é uma classe. + "{0}" não pode ser usado como um atributo porque não é uma classe. '{0}' cannot be used as an attribute because it does not inherit from 'System.Attribute'. - '"{0}" não pode ser usado como um atributo porque não herda de "System.Attribute". + "{0}" não pode ser usado como um atributo porque não herda de "System.Attribute". '{0}' cannot be used as an attribute because it is declared 'MustInherit'. - '"{0}" não pode ser usado como um atributo porque é declarado como "MustInherit". + "{0}" não pode ser usado como um atributo porque é declarado como "MustInherit". @@ -4408,7 +4452,7 @@ '{0}' is not valid within a Module. - '"{0}" não é válido dentro de um Módulo. + "{0}" não é válido dentro de um Módulo. @@ -4423,7 +4467,7 @@ '{0}' values cannot be converted to 'Char'. Use 'Microsoft.VisualBasic.ChrW' to interpret a numeric value as a Unicode character or first convert it to 'String' to produce a digit. - '"{0}" valores não podem ser convertidos em "Char". Use "Microsoft.VisualBasic.ChrW" para interpretar um valor numérico como um caractere Unicode ou converta-o primeiro em "String" para produzir um dígito. + "{0}" valores não podem ser convertidos em "Char". Use "Microsoft.VisualBasic.ChrW" para interpretar um valor numérico como um caractere Unicode ou converta-o primeiro em "String" para produzir um dígito. @@ -4438,7 +4482,7 @@ '{0}' cannot be named as a parameter in an attribute specifier because it is not a field or property. - '"{0}" não pode ser nomeado como um parâmetro em um especificador de atributo porque não é um campo ou propriedade. + "{0}" não pode ser nomeado como um parâmetro em um especificador de atributo porque não é um campo ou propriedade. @@ -4458,7 +4502,7 @@ '{0}' has no parameters and its return type cannot be indexed. - '"{0}" não tem parâmetros e seu tipo de retorno não pode ser indexado. + "{0}" não tem parâmetros e seu tipo de retorno não pode ser indexado. @@ -4483,7 +4527,7 @@ '{0}' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event. - '"{0}" é um evento e não pode ser chamado diretamente. Use uma instrução "RaiseEvent" para acionar um evento. + "{0}" é um evento e não pode ser chamado diretamente. Use uma instrução "RaiseEvent" para acionar um evento. @@ -4568,7 +4612,7 @@ '{0}' has no type parameters and so cannot have type arguments. - '"{0}" não tem parâmetros de tipo e, portanto, não pode ter argumentos de tipo. + "{0}" não tem parâmetros de tipo e, portanto, não pode ter argumentos de tipo. @@ -4608,7 +4652,7 @@ '{0}' has the same name as a type parameter. - '"{0}" tem o mesmo nome de um parâmetro de tipo. + "{0}" tem o mesmo nome de um parâmetro de tipo. @@ -4633,7 +4677,7 @@ '{0}' cannot be used as a type constraint. - '"{0}" não pode ser usado como uma restrição de tipo. + "{0}" não pode ser usado como uma restrição de tipo. @@ -4688,12 +4732,12 @@ '{0}' cannot override '{1}' because they differ by type parameter constraints. - '"{0}" não pode substituir "{1}" porque diferem por restrições de parâmetros de tipo. + "{0}" não pode substituir "{1}" porque diferem por restrições de parâmetros de tipo. '{0}' cannot implement '{1}.{2}' because they differ by type parameter constraints. - '"{0}" não pode implementar "{1}.{2}" porque diferem por restrições de parâmetro de tipo. + "{0}" não pode implementar "{1}.{2}" porque diferem por restrições de parâmetro de tipo. @@ -4748,7 +4792,7 @@ '{0}' is already declared as a type parameter of this method. - '"{0}" já está declarado como um parâmetro de tipo deste método. + "{0}" já está declarado como um parâmetro de tipo deste método. @@ -4773,7 +4817,7 @@ 'For Each' on type '{0}' is ambiguous because the type implements multiple instantiations of 'System.Collections.Generic.IEnumerable(Of T)'. - '"For Each" no tipo "{0}" é ambíguo porque o tipo implementa várias instanciações de "System.Collections.Generic.IEnumerable (Of T)". + "For Each" no tipo "{0}" é ambíguo porque o tipo implementa várias instanciações de "System.Collections.Generic.IEnumerable (Of T)". @@ -4870,7 +4914,7 @@ 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter '{0}'. Only non-nullable 'Structure' types are allowed. - '"System. Nullable" não satisfaz a restrição "Structure" para parâmetro de tipo "{0}". Somente tipos "Structure" não anuláveis são permitidos. + "System. Nullable" não satisfaz a restrição "Structure" para parâmetro de tipo "{0}". Somente tipos "Structure" não anuláveis são permitidos. @@ -4935,7 +4979,7 @@ '{0}' cannot be declared 'Shadows' outside of a class, structure, or interface. - '"{0}" não pode ser declarado como "Shadows" fora de uma classe, estrutura ou interface. + "{0}" não pode ser declarado como "Shadows" fora de uma classe, estrutura ou interface. @@ -4970,27 +5014,27 @@ '{0}' cannot be applied because the format of the GUID '{1}' is not correct. - '"{0}" não pode ser aplicado porque o formato do GUID "{1}" não está correto. + "{0}" não pode ser aplicado porque o formato do GUID "{1}" não está correto. 'Microsoft.VisualBasic.ComClassAttribute' and '{0}' cannot both be applied to the same class. - '"Microsoft.VisualBasic.ComClassAttribute" e "{0}" não podem ser aplicados à mesma classe. + "Microsoft.VisualBasic.ComClassAttribute" e "{0}" não podem ser aplicados à mesma classe. 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to '{0}' because its container '{1}' is not declared 'Public'. - '"Microsoft.VisualBasic.ComClassAttribute" não pode ser aplicado a "{0}" porque seu contêiner "{1}" não está declarado como "Public". + "Microsoft.VisualBasic.ComClassAttribute" não pode ser aplicado a "{0}" porque seu contêiner "{1}" não está declarado como "Public". 'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to '{0}' because 'Microsoft.VisualBasic.ComClassAttribute' reserves zero for the default property. - '"System.Runtime.InteropServices.DispIdAttribute" não pode ser aplicado a "{0}" porque "Microsoft.VisualBasic.ComClassAttribute" reserva para a propriedade padrão. + "System.Runtime.InteropServices.DispIdAttribute" não pode ser aplicado a "{0}" porque "Microsoft.VisualBasic.ComClassAttribute" reserva para a propriedade padrão. 'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to '{0}' because 'Microsoft.VisualBasic.ComClassAttribute' reserves values less than zero. - '"System.Runtime.InteropServices.DispIdAttribute" não pode ser aplicado a "{0}" porque "Microsoft.VisualBasic.ComClassAttribute" reserva valores menores que zero. + "System.Runtime.InteropServices.DispIdAttribute" não pode ser aplicado a "{0}" porque "Microsoft.VisualBasic.ComClassAttribute" reserva valores menores que zero. @@ -5005,7 +5049,7 @@ 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to '{0}' because it is not declared 'Public'. - '"Microsoft.VisualBasic.ComClassAttribute" não pode ser aplicado a "{0}" porque não está declarado como "Public". + "Microsoft.VisualBasic.ComClassAttribute" não pode ser aplicado a "{0}" porque não está declarado como "Public". @@ -5055,12 +5099,12 @@ '{0}' parameters cannot be declared 'ParamArray'. - '"{0}" parâmetros não podem ser declarados "ParamArray". + "{0}" parâmetros não podem ser declarados "ParamArray". '{0}' parameters cannot be declared 'Optional'. - '"{0}" parâmetros não podem ser declarados "Optional". + "{0}" parâmetros não podem ser declarados "Optional". @@ -5315,7 +5359,7 @@ 'GoTo {0}' is not valid because '{0}' is inside a 'Using' statement that does not contain this statement. - '"GoTo {0}" não é válido porque "{0}" está dentro de uma instrução "Using" que não contém essa instrução. + "GoTo {0}" não é válido porque "{0}" está dentro de uma instrução "Using" que não contém essa instrução. @@ -5340,7 +5384,7 @@ '{0}' has the same name as a member used for type '{1}' exposed in a 'My' group. Rename the type or its enclosing namespace. - '"{0}" tem o mesmo nome de um membro usado para o tipo "{1}" exposto em um grupo "My". Renomeie o tipo ou seu namespace delimitador. + "{0}" tem o mesmo nome de um membro usado para o tipo "{1}" exposto em um grupo "My". Renomeie o tipo ou seu namespace delimitador. @@ -5355,7 +5399,7 @@ 'From' expected. - '"From" esperado. + "From" esperado. @@ -5440,7 +5484,7 @@ '{0}' is not a member of '{1}'; it does not exist in the current context. - '"{0}" não é um membro de "{1}"; ele não existe no contexto atual. + "{0}" não é um membro de "{1}"; ele não existe no contexto atual. @@ -5512,7 +5556,7 @@ '{0}' is not a method parameter. - '"{0}" não é um parâmetro de método. + "{0}" não é um parâmetro de método. @@ -5564,7 +5608,7 @@ '{0}' is not a parameter of extension method '{1}' defined in '{2}'. - '"{0}" não é um parâmetro do método de extensão "{1}" definido em "{2}". + "{0}" não é um parâmetro do método de extensão "{1}" definido em "{2}". @@ -5589,7 +5633,7 @@ 'In' or '=' expected. - '"In" ou "=" esperado. + "In" ou "=" esperado. @@ -5609,7 +5653,7 @@ '{0}{1}' is not valid because '{2}' is inside a scope that defines a variable that is used in a lambda or query expression. - '"{0}{1}" não é válido porque "{2}" está dentro de um escopo que define uma variável que é usada em uma expressão lambda ou de consulta. + "{0}{1}" não é válido porque "{2}" está dentro de um escopo que define uma variável que é usada em uma expressão lambda ou de consulta. @@ -5709,7 +5753,7 @@ 'Equals' cannot compare a value of type '{0}' with a value of type '{1}'. - '"Equals" não pode comparar um valor do tipo "{0}" com um valor do tipo "{1}". + "Equals" não pode comparar um valor do tipo "{0}" com um valor do tipo "{1}". @@ -5899,7 +5943,7 @@ '{0}' is not accessible in this context because the return type is not accessible. - '"{0}" não está acessível neste contexto porque o tipo de retorno não está acessível. + "{0}" não está acessível neste contexto porque o tipo de retorno não está acessível. @@ -5986,7 +6030,7 @@ '{0}' is obsolete: '{1}'. - '"{0}" está obsoleto: "{1}". + "{0}" está obsoleto: "{1}". @@ -6036,7 +6080,7 @@ '{0}' is obsolete. - '"{0}" está obsoleto. + "{0}" está obsoleto. @@ -6066,7 +6110,7 @@ 'Microsoft.VisualBasic.ComClassAttribute' is specified for class '{0}' but '{0}' has no public members that can be exposed to COM; therefore, no COM interfaces are generated. - '"Microsoft.VisualBasic.ComClassAttribute" está especificado para a classe "{0}", mas "{0}" não tem membros públicos que podem ser expostos ao COM; portanto, nenhuma interfaces COM é gerada. + "Microsoft.VisualBasic.ComClassAttribute" está especificado para a classe "{0}", mas "{0}" não tem membros públicos que podem ser expostos ao COM; portanto, nenhuma interfaces COM é gerada. @@ -6106,7 +6150,7 @@ '{0}' accessor of '{1}' is obsolete: '{2}'. - '"{0}" acessador de "{1}" está obsoleto: "{2}". + "{0}" acessador de "{1}" está obsoleto: "{2}". @@ -6116,7 +6160,7 @@ '{0}' accessor of '{1}' is obsolete. - '"{0}" acessador de "{1}" está obsoleto. + "{0}" acessador de "{1}" está obsoleto. @@ -6136,7 +6180,7 @@ '{0}' is not CLS-compliant because it derives from '{1}', which is not CLS-compliant. - '"{0}" não tem conformidade com CLS porque deriva de "{1}", o qual não tem conformidade com CLS. + "{0}" não tem conformidade com CLS porque deriva de "{1}", o qual não tem conformidade com CLS. @@ -6166,7 +6210,7 @@ '{0}' is not CLS-compliant because the interface '{1}' it inherits from is not CLS-compliant. - '"{0}" não tem conformidade com CLS porque a interface "{1}" da qual ele herda não tem conformidade com CLS. + "{0}" não tem conformidade com CLS porque a interface "{1}" da qual ele herda não tem conformidade com CLS. @@ -6226,7 +6270,7 @@ '{0}' is not CLS-compliant because it overloads '{1}' which differs from it only by array of array parameter types or by the rank of the array parameter types. - '"{0}" não tem conformidade com CLS porque sobrecarrega "{1}" que difere dele apenas pela matriz de tipos de parâmetro de matriz ou pela classificação dos tipos de parâmetro de matriz. + "{0}" não tem conformidade com CLS porque sobrecarrega "{1}" que difere dele apenas pela matriz de tipos de parâmetro de matriz ou pela classificação dos tipos de parâmetro de matriz. @@ -6356,7 +6400,7 @@ '{0}' method for event '{1}' cannot be marked CLS compliant because its containing type '{2}' is not CLS compliant. - '"{0}" método para o evento "{1}" não pode ser marcado como em conformidade com CLS porque seu tipo recipiente "{2}" não tem conformidade com CLS. + "{0}" método para o evento "{1}" não pode ser marcado como em conformidade com CLS porque seu tipo recipiente "{2}" não tem conformidade com CLS. @@ -6366,7 +6410,7 @@ '{0}' in designer-generated type '{1}' should call InitializeComponent method. - '"{0}" no tipo gerado por designer "{1}" deve chamar o método InitializeComponent. + "{0}" no tipo gerado por designer "{1}" deve chamar o método InitializeComponent. @@ -6701,7 +6745,7 @@ 'Catch' block never reached; exception type's base type handled above in the same Try statement - 'O bloco 'Catch' nunca é alcançado. O tipo base do tipo de exceção foi identificado acima na mesma instrução Try + 'O bloco 'Catch' nunca foi alcançado. O tipo base do tipo de exceção foi identificado acima na mesma instrução Try @@ -6806,7 +6850,7 @@ 'Microsoft.VisualBasic.ComClassAttribute' on class '{0}' implicitly declares {1} '{2}', which conflicts with a member of the same name in {3} '{4}'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base {4}. - '"Microsoft.VisualBasic.ComClassAttribute" na classe "{0}" declara implicitamente {1} "{2}", que está em conflito com um membro do mesmo nome em {3} "{4}". Use "Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)" se você deseja ocultar o nome da base {4}. + "Microsoft.VisualBasic.ComClassAttribute" na classe "{0}" declara implicitamente {1} "{2}", que está em conflito com um membro do mesmo nome em {3} "{4}". Use "Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)" se você deseja ocultar o nome da base {4}. @@ -6816,7 +6860,7 @@ '{0}' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement. - '"{0}" não pode ser exposto a COM como uma propriedade "Let". Você não poderá atribuir valores não-objeto (como números ou cadeias de caracteres) para essa propriedade do Visual Basic 6.0 usando uma instrução "Let". + "{0}" não pode ser exposto a COM como uma propriedade "Let". Você não poderá atribuir valores não-objeto (como números ou cadeias de caracteres) para essa propriedade do Visual Basic 6.0 usando uma instrução "Let". @@ -7361,17 +7405,17 @@ '{0}' cannot expose type '{1}' in {2} '{3}' through {4} '{5}'. - '"{0}" não pode expor o tipo "{1}" em {2} "{3}" através de {4} "{5}". + "{0}" não pode expor o tipo "{1}" em {2} "{3}" através de {4} "{5}". '{0}' cannot be referenced because it is not a valid assembly. - '"{0}" não pode ser referenciado porque não é um assembly válido. + "{0}" não pode ser referenciado porque não é um assembly válido. '{0}' cannot be implemented by a {1} property. - '"{0}" não pode ser implementado por uma {1} propriedade. + "{0}" não pode ser implementado por uma {1} propriedade. @@ -7663,12 +7707,12 @@ '{0}' cannot be converted to '{1}'. Consider using '{2}' instead. - '"{0}" não pode ser convertido em "{1}". Ao invés disso, considere o uso de "{2}". + "{0}" não pode ser convertido em "{1}". Ao invés disso, considere o uso de "{2}". '{0}' cannot be converted to '{1}'. Consider using '{2}' instead. - '"{0}" não pode ser convertido em "{1}". Ao invés disso, considere o uso de "{2}". + "{0}" não pode ser convertido em "{1}". Ao invés disso, considere o uso de "{2}". @@ -7678,12 +7722,12 @@ '{4}' cannot be converted to '{5}' because '{0}' is not derived from '{1}', as required for the 'In' generic parameter '{2}' in '{3}'. - '"{4}" não pode ser convertido em "{5}" porque "{0}" não é derivado de "{1}", conforme necessário para o parâmetro genérico "In" "{2}" em "{3}". + "{4}" não pode ser convertido em "{5}" porque "{0}" não é derivado de "{1}", conforme necessário para o parâmetro genérico "In" "{2}" em "{3}". '{4}' cannot be converted to '{5}' because '{0}' is not derived from '{1}', as required for the 'Out' generic parameter '{2}' in '{3}'. - '"{4}" não pode ser convertido em "{5}" porque "{0}" não é derivado de "{1}", conforme necessário para o parâmetro genérico "Out" "{2}" em "{3}". + "{4}" não pode ser convertido em "{5}" porque "{0}" não é derivado de "{1}", conforme necessário para o parâmetro genérico "Out" "{2}" em "{3}". @@ -7708,17 +7752,17 @@ '{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an In type parameter, 'In {2}'. - '"{0}" não pode ser convertido em "{1}". Considere alterar o "{2}" na definição de "{3}" para um parâmetro de tipo In, "In {2}". + "{0}" não pode ser convertido em "{1}". Considere alterar o "{2}" na definição de "{3}" para um parâmetro de tipo In, "In {2}". '{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an Out type parameter, 'Out {2}'. - '"{0}" não pode ser convertido em "{1}". Considere alterar o "{2}" na definição de "{3}" para um parâmetro de tipo Out, "Out {2}". + "{0}" não pode ser convertido em "{1}". Considere alterar o "{2}" na definição de "{3}" para um parâmetro de tipo Out, "Out {2}". '{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an In type parameter, 'In {2}'. - '"{0}" não pode ser convertido em "{1}". Considere alterar o "{2}" na definição de "{3}" para um parâmetro de tipo In, "In {2}". + "{0}" não pode ser convertido em "{1}". Considere alterar o "{2}" na definição de "{3}" para um parâmetro de tipo In, "In {2}". @@ -7728,7 +7772,7 @@ '{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an Out type parameter, 'Out {2}'. - '"{0}" não pode ser convertido em "{1}". Considere alterar o "{2}" na definição de "{3}" para um parâmetro de tipo Out, "Out {2}". + "{0}" não pode ser convertido em "{1}". Considere alterar o "{2}" na definição de "{3}" para um parâmetro de tipo Out, "Out {2}". @@ -7988,17 +8032,17 @@ 'Await' requires that the type '{0}' have a suitable GetAwaiter method. - '"Await" requer que o tipo "{0}" tenha um método GetAwaiter adequado. + "Await" requer que o tipo "{0}" tenha um método GetAwaiter adequado. 'Await' requires that the return type '{0}' of '{1}.GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion. - '"Await" requer que o tipo de retorno "{0}" de "{1}.GetAwaiter()" tenha membros IsCompleted, OnCompleted e GetResult adequados e implemente INotifyCompletion ou ICriticalNotifyCompletion. + "Await" requer que o tipo de retorno "{0}" de "{1}.GetAwaiter()" tenha membros IsCompleted, OnCompleted e GetResult adequados e implemente INotifyCompletion ou ICriticalNotifyCompletion. '{0}' does not implement '{1}'. - '"{0}" não implementa "{1}". + "{0}" não implementa "{1}". @@ -8038,7 +8082,7 @@ '{0}' does not return a Task and cannot be awaited. Consider changing it to an Async Function. - '"{0}" não retornar uma Tarefa e não podem ser colocada em espera. Considere alterá-la para uma Função Assíncrona. + "{0}" não retornar uma Tarefa e não podem ser colocada em espera. Considere alterá-la para uma Função Assíncrona. @@ -8048,7 +8092,7 @@ 'Await' can only be used within an Async method. Consider marking this method with the 'Async' modifier and changing its return type to 'Task(Of {0})'. - '"Await" pode somente ser usado dentro de um método Assíncrono. Considere marcar este método com o modificador "Async" e alterar seu tipo de retorno para "Task(Of {0})". + "Await" pode somente ser usado dentro de um método Assíncrono. Considere marcar este método com o modificador "Async" e alterar seu tipo de retorno para "Task(Of {0})". @@ -8093,7 +8137,7 @@ '{0}' cannot be used as a parameter type for an Iterator or Async method. - '"{0}" não pode ser usado como um tipo de parâmetro para um método Iterador ou Assíncrono. + "{0}" não pode ser usado como um tipo de parâmetro para um método Iterador ou Assíncrono. @@ -8103,7 +8147,7 @@ '{0}' cannot be declared 'Partial' because it has the 'Async' modifier. - '"{0}" não pode ser declarado como "Parcial" porque ele tem o modificador "Async". + "{0}" não pode ser declarado como "Parcial" porque ele tem o modificador "Async". @@ -8448,12 +8492,12 @@ '{0}' is an unsupported .NET module. - '"{0}" é um módulo .NET sem suporte. + "{0}" é um módulo .NET sem suporte. '{0}' is an unsupported event. - '"{0}" é um evento sem suporte. + "{0}" é um evento sem suporte. @@ -8718,7 +8762,7 @@ '{0}' is not a valid format specifier - '"{0}" não é um especificador de formato válido + "{0}" não é um especificador de formato válido @@ -8728,7 +8772,7 @@ 'Warning' expected. - '"Aviso" esperado. + "Aviso" esperado. diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.ru.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.ru.xlf index b2cb46ddaa46b..d8868f290a36e 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.ru.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.ru.xlf @@ -212,169 +212,169 @@ -vbruntime:<file> Compile with the alternate Visual Basic runtime in <file>. - Visual Basic Compiler Options + Параметры компилятора Visual Basic - - OUTPUT FILE - --out:<file> Specifies the output file name. --target:exe Create a console application (default). - (Short form: -t) --target:winexe Create a Windows application. --target:library Create a library assembly. --target:module Create a module that can be added to an - assembly. --target:appcontainerexe Create a Windows application that runs in + - Выходной файл - +-out:<file> Задает имя выходного файла. +-target:exe Создать консольное приложение (по умолчанию). + (Краткая форма: -t) +-target:winexe Создать Windows-приложение. +-target:library Создать библиотечную сборку. +-target:module Создать модуль, который может быть добавлен в + сборку. +-target:appcontainerexe Создать Windows-приложение, выполняемое в контейнере AppContainer. --target:winmdobj Create a Windows Metadata intermediate file --doc[+|-] Generates XML documentation file. --doc:<file> Generates XML documentation file to <file>. --refout:<file> Reference assembly output to generate +-target:winmdobj Создать промежуточный файл метаданных Windows +-doc[+|-] Создает XML-файл документации. +-doc:<file> Создает XML-файл документации <file>. +-refout:<file> Выходные данные создаваемой базовой сборки - - INPUT FILES - --addmodule:<file_list> Reference metadata from the specified modules --link:<file_list> Embed metadata from the specified interop - assembly. (Short form: -l) --recurse:<wildcard> Include all files in the current directory - and subdirectories according to the - wildcard specifications. --reference:<file_list> Reference metadata from the specified - assembly. (Short form: -r) --analyzer:<file_list> Run the analyzers from this assembly - (Short form: -a) --additionalfile:<file list> Additional files that don't directly affect code - generation but may be used by analyzers for producing - errors or warnings. + - Входные файлы - +-addmodule:<file_list> Ссылка на метаданные из заданных модулей +-link:<file_list> Внедрить метаданные из указанной сборки + взаимодействия. (Краткая форма: -l) +-recurse:<wildcard> Включить все файлы в текущем каталоге + и подкаталогах в соответствии с + заданным шаблоном. +-reference:<file_list> Ссылка на метаданные из заданной + сборки. (Краткая форма: -r) +-analyzer:<file_list> Запускать анализаторы из этой сборки + (Краткая форма: -a) +-additionalfile:<file list> Дополнительные файлы, которые не оказывают прямого влияния на создание + кода, но могут использоваться анализаторами для вывода + ошибок или предупреждений. - - RESOURCES - --linkresource:<resinfo> Links the specified file as an external - assembly resource. - resinfo:<file>[,<name>[,public|private]] - (Short form: -linkres) --nowin32manifest The default manifest should not be embedded - in the manifest section of the output PE. --resource:<resinfo> Adds the specified file as an embedded - assembly resource. - resinfo:<file>[,<name>[,public|private]] - (Short form: -res) --win32icon:<file> Specifies a Win32 icon file (.ico) for the - default Win32 resources. --win32manifest:<file> The provided file is embedded in the manifest - section of the output PE. --win32resource:<file> Specifies a Win32 resource file (.res). + - Ресурсы - +-linkresource:<resinfo> Привязывает указанный файл в качестве внешнего + ресурса сборки. + Данные о ресурсе:<file>[,<name>[,public|private]] + (Краткая форма: -linkres) +-nowin32manifest Манифест по умолчанию не должен внедряться + в раздел манифеста выходного PE-файла. +-resource:<resinfo> Добавляет указанный файл в качестве внедренного + ресурса сборки. + Данные о ресурсе:<file>[,<name>[,public|private]] + (Краткая форма: -res) +-win32icon:<file> Задает файл значка Win32 (ICO-файл) для + ресурсов Win32 по умолчанию. +-win32manifest:<file> Предоставленный файл внедряется в раздел + манифеста выходного PE-файла. +-win32resource:<file> Задает файл ресурсов Win32 (RES-файл). - - CODE GENERATION - --optimize[+|-] Enable optimizations. --removeintchecks[+|-] Remove integer checks. Default off. --debug[+|-] Emit debugging information. --debug:full Emit full debugging information (default). --debug:pdbonly Emit full debugging information. --debug:portable Emit cross-platform debugging information. --debug:embedded Emit cross-platform debugging information into - the target .dll or .exe. --deterministic Produce a deterministic assembly - (including module version GUID and timestamp) --refonly Produce a reference assembly in place of the main output --instrument:TestCoverage Produce an assembly instrumented to collect - coverage information --sourcelink:<file> Source link info to embed into PDB. + - Создание кода - +-optimize[+|-] Включить оптимизацию. +-removeintchecks[+|-] Удалить целочисленные проверки. По умолчанию отключены. +-debug[+|-] Выдать отладочные данные. +-debug:full Выдать полные отладочные данные (по умолчанию). +-debug:pdbonly Выдать полные отладочные данные. +-debug:portable Выдать кроссплатформенные отладочные данные. +-debug:embedded Выдать кроссплатформенные отладочные данные в + целевой DLL-файл или EXE-файл. +-deterministic Создать детерминированную сборку + (включая GUID версии модуля и метку времени) +-refonly Создавать базовую сборку вместо основных выходных данных +-instrument:TestCoverage Создавать сборку, инструментированную для сбора + данных об объеме протестированного кода +-sourcelink:<file> Данные о ссылке на исходные файлы для внедрения в PDB. - - ERRORS AND WARNINGS - --nowarn Disable all warnings. --nowarn:<number_list> Disable a list of individual warnings. --warnaserror[+|-] Treat all warnings as errors. --warnaserror[+|-]:<number_list> Treat a list of warnings as errors. --ruleset:<file> Specify a ruleset file that disables specific - diagnostics. + - Ошибки и предупреждения - +-nowarn Отключить все предупреждения. +-nowarn:<number_list> Отключить отдельные предупреждения по списку. +-warnaserror[+|-] Обрабатывать все предупреждения как ошибки. +-warnaserror[+|-]:<number_list> Обрабатывать список предупреждений как ошибки. +-ruleset:<file> Указать файл набора правил, отключающий определенные + диагностические операции. -errorlog:<file>[,version=<sarif_version>] - Specify a file to log all compiler and analyzer - diagnostics in SARIF format. - sarif_version:{1|2|2.1} Default is 1. 2 and 2.1 - both mean SARIF version 2.1.0. --reportanalyzer Report additional analyzer information, such as - execution time. --skipanalyzers[+|-] Skip execution of diagnostic analyzers. + Указать файл для записи всех диагностических данных + компилятора и анализатора в формате SARIF. + sarif_version:{1|2|2.1} По умолчанию используются значения 1. 2 и 2.1, + обозначающие версию SARIF 2.1.0. +-reportanalyzer Сообщить дополнительные сведения об анализаторе, например + время выполнения. +-skipanalyzers[+|-] Пропустить выполнение анализаторов диагностики. - - LANGUAGE - --define:<symbol_list> Declare global conditional compilation - symbol(s). symbol_list:name=value,... - (Short form: -d) --imports:<import_list> Declare global Imports for namespaces in - referenced metadata files. - import_list:namespace,... --langversion:? Display the allowed values for language version --langversion:<string> Specify language version such as - `default` (latest major version), or - `latest` (latest version, including minor versions), - or specific versions like `14` or `15.3` --optionexplicit[+|-] Require explicit declaration of variables. --optioninfer[+|-] Allow type inference of variables. --rootnamespace:<string> Specifies the root Namespace for all type - declarations. --optionstrict[+|-] Enforce strict language semantics. --optionstrict:custom Warn when strict language semantics are not - respected. --optioncompare:binary Specifies binary-style string comparisons. - This is the default. --optioncompare:text Specifies text-style string comparisons. + - Язык - +-define:<symbol_list> Объявить глобальные символы условной + компиляции. symbol_list:имя=значение,... + (Краткая форма: -d) +-imports:<import_list> Объявить глобальные импорты для пространств имен в + указанных файлах метаданных. + import_list:пространство_имен,... +-langversion:? Отображать допустимые значения версии языка +-langversion:<string> Указать версию языка, например + "default" (последний основной номер версии) или + "latest" (последняя версия, включая дополнительные номера), + или конкретные версии, например 14 или 15.3 +-optionexplicit[+|-] Требовать явное объявление переменных. +-optioninfer[+|-] Разрешить вывод для типов переменных. +-rootnamespace:<string> Задает корневое пространство имен для всех объявлений + типов. +-optionstrict[+|-] Требовать строгую семантику языка. +-optionstrict:custom Предупреждать, когда не соблюдается строгая семантика + языка. +-optioncompare:binary Задает сравнение строк как двоичных данных. + Задано по умолчанию. +-optioncompare:text Задает сравнение строк как текста. - - MISCELLANEOUS - --help Display this usage message. (Short form: -?) --noconfig Do not auto-include VBC.RSP file. --nologo Do not display compiler copyright banner. --quiet Quiet output mode. --verbose Display verbose messages. --parallel[+|-] Concurrent build. --version Display the compiler version number and exit. + - Прочее - +-help Отображать это сообщение об использовании. (Краткая форма: -?) +-noconfig Не включать файл VBC.RSP в состав автоматически. +-nologo Не отображать заставку компилятора с информацией об авторских правах. +-quiet Режим вывода без сообщений. +-verbose Отображать подробные сообщения. +-parallel[+|-] Параллельная сборка. +-version Отобразить номер версии компилятора и выйти. - - ADVANCED - --baseaddress:<number> The base address for a library or module - (hex). --checksumalgorithm:<alg> Specify algorithm for calculating source file - checksum stored in PDB. Supported values are: - SHA1 or SHA256 (default). --codepage:<number> Specifies the codepage to use when opening - source files. --delaysign[+|-] Delay-sign the assembly using only the public - portion of the strong name key. --publicsign[+|-] Public-sign the assembly using only the public - portion of the strong name key. --errorreport:<string> Specifies how to handle internal compiler - errors; must be prompt, send, none, or queue - (default). --filealign:<number> Specify the alignment used for output file - sections. --highentropyva[+|-] Enable high-entropy ASLR. --keycontainer:<string> Specifies a strong name key container. --keyfile:<file> Specifies a strong name key file. --libpath:<path_list> List of directories to search for metadata - references. (Semi-colon delimited.) --main:<class> Specifies the Class or Module that contains - Sub Main. It can also be a Class that - inherits from System.Windows.Forms.Form. - (Short form: -m) --moduleassemblyname:<string> Name of the assembly which this module will - be a part of. --netcf Target the .NET Compact Framework. --nostdlib Do not reference standard libraries - (system.dll and VBC.RSP file). + - Дополнительно - +-baseaddress:<number> Базовый адрес библиотеки или модуля + (шестнадцатеричный). +-checksumalgorithm:<alg> Задать алгоритм расчета контрольной суммы + исходного файла, хранимой в PDB. Поддерживаемые значения: + SHA1 или SHA256 (по умолчанию). +-codepage:<number> Указывает кодовую страницу, используемую при открытии + исходных файлов. +-delaysign[+|-] Использовать отложенную подпись для сборки, применяя только + открытую часть ключа строгого имени. +-publicsign[+|-] Выполнить общедоступную подпись сборки, используя только открытую + часть ключа строгого имени. +-errorreport:<string> Указывает способ обработки внутренних ошибок + компилятора; принимает prompt, send, none или queue + (по умолчанию). +-filealign:<number> Задать выравнивание для разделов выходных + файлов. +-highentropyva[+|-] Включить ASLR с высокой энтропией. +-keycontainer:<string> Задает контейнер ключа строгого имени. +-keyfile:<file> Задает файл ключа строгого имени. +-libpath:<path_list> Список каталогов для поиска ссылок на + метаданные. (Разделитель — точка с запятой.) +-main:<class> Задает класс или модуль, содержащий + Sub Main. Он может являться производным + классом от System.Windows.Forms.Form. + (Краткая форма: -m) +-moduleassemblyname:<string> Имя сборки, частью которой будет + данный модуль. +-netcf Целевая версия .NET Compact Framework. +-nostdlib Не обращаться к стандартным библиотекам + (файл system.dll и VBC.RSP). -pathmap:<K1>=<V1>,<K2>=<V2>,... - Specify a mapping for source path names output by - the compiler. --platform:<string> Limit which platforms this code can run on; - must be x86, x64, Itanium, arm, arm64 - AnyCPU32BitPreferred or anycpu (default). --preferreduilang Specify the preferred output language name. --nosdkpath Disable searching the default SDK path for standard library assemblies. --sdkpath:<path> Location of the .NET Framework SDK directory + Указать сопоставление для выходных данных имен исходного пути по + компилятору. +-platform:<string> Ограничить платформы, на которых может выполняться этот код: + x86, x64, Itanium, arm, arm64 + AnyCPU32BitPreferred или anycpu (по умолчанию). +-preferreduilang Указать имя предпочтительного языка вывода. +-nosdkpath Отключить поиск пути пакета SDK по умолчанию для сборок стандартных библиотек. +-sdkpath:<path> Расположение каталога пакета SDK .NET Framework (mscorlib.dll). --subsystemversion:<version> Specify subsystem version of the output PE. +-subsystemversion:<version> Указать версию подсистемы выходного PE-файла. version:<number>[.<number>] --utf8output[+|-] Emit compiler output in UTF8 character - encoding. -@<file> Insert command-line settings from a text file --vbruntime[+|-|*] Compile with/without the default Visual Basic - runtime. --vbruntime:<file> Compile with the alternate Visual Basic - runtime in <file>. +-utf8output[+|-] Выдавать выходные данные компилятора в кодировке + UTF8. +@<file> Вставить параметры командной строки из текстового файла +-vbruntime[+|-|*] Скомпилировать с помощью или без использования стандартной среды выполнения + Visual Basic. +-vbruntime:<file> Скомпилировать с помощью альтернативной среды выполнения + Visual Basic в <file>. @@ -463,6 +463,50 @@ Аргумент типа не может иметь значение Nothing + + The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + Сборка "{0}", содержащая тип "{1}", ссылается на платформу .NET Framework, которая не поддерживается. + {1} is the type that was loaded, {0} is the containing assembly. + + + The loaded assembly references .NET Framework, which is not supported. + Загруженная сборка ссылается на платформу .NET Framework, которая не поддерживается. + + + + Generator '{0}' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + Генератору "{0}" не удалось создать источник. Это не повлияет на выходные данные и ошибки компиляции, которые могут возникнуть в результате. Тип возникшего исключения: "{1}", сообщение: "{2}" + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + Генератор создал следующее исключение: +"{0}". + {0} is the string representation of the exception that was thrown. + + + Generator failed to generate source. + Генератору не удалось создать источник. + + + + Generator '{0}' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + Не удалось инициализировать генератор "{0}". Это не повлияет на выходные данные и ошибки компиляции, которые могут возникнуть в результате. Тип возникшего исключения: "{1}", сообщение: "{2}" + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + Генератор создал следующее исключение: +"{0}". + {0} is the string representation of the exception that was thrown. + + + Generator failed to initialize. + Не удалось инициализировать генератор. + + Wrong number of type arguments Неверное число аргументов типа @@ -615,7 +659,7 @@ '{0}' is not a valid value for /moduleassemblyname - '"{0}" не является допустимым значением для /moduleassemblyname + "{0}" не является допустимым значением для /moduleassemblyname @@ -815,12 +859,12 @@ '{0}' is valid only within an instance method. - '"{0}" допускается только в методе экземпляра. + "{0}" допускается только в методе экземпляра. '{0}' is not valid within a structure. - '"{0}" не является допустимым в структуре. + "{0}" не является допустимым в структуре. @@ -1055,42 +1099,42 @@ '{0}' is an Enum type and cannot be used as an expression. - '"{0}" является типом Enum и не может использоваться как выражение. + "{0}" является типом Enum и не может использоваться как выражение. '{0}' is a type and cannot be used as an expression. - '"{0}" является типом и не может использоваться в качестве выражения. + "{0}" является типом и не может использоваться в качестве выражения. '{0}' is a class type and cannot be used as an expression. - '"{0}" является типом класса и не может использоваться как выражение. + "{0}" является типом класса и не может использоваться как выражение. '{0}' is a structure type and cannot be used as an expression. - '"{0}" является типом структуры и не может использоваться в качестве выражения. + "{0}" является типом структуры и не может использоваться в качестве выражения. '{0}' is an interface type and cannot be used as an expression. - '"{0}" является типом интерфейса и не может использоваться как выражение. + "{0}" является типом интерфейса и не может использоваться как выражение. '{0}' is a namespace and cannot be used as an expression. - '"{0}" является пространством имени и не может использоваться в качестве выражения. + "{0}" является пространством имени и не может использоваться в качестве выражения. '{0}' is not a valid name and cannot be used as the root namespace name. - '"{0}" является недопустимым именем и не может использоваться как имя корневого пространства имен. + "{0}" является недопустимым именем и не может использоваться как имя корневого пространства имен. '{0}' is an XML prefix and cannot be used as an expression. Use the GetXmlNamespace operator to create a namespace object. - '"{0}" является префиксом XML и не может использоваться в качестве выражения. Используйте оператор GetXmlNamespace для создания объекта пространства имен. + "{0}" является префиксом XML и не может использоваться в качестве выражения. Используйте оператор GetXmlNamespace для создания объекта пространства имен. @@ -1350,17 +1394,17 @@ '{0}' is not valid on a constant declaration. - '"{0}" недопустимо использовать при объявлении константы. + "{0}" недопустимо использовать при объявлении константы. '{0}' is not valid on a WithEvents declaration. - '"{0}" недопустимо использовать в объявлении WithEvents. + "{0}" недопустимо использовать в объявлении WithEvents. '{0}' is not valid on a member variable declaration. - '"{0}" недопустимо использовать при объявлении переменной-члена. + "{0}" недопустимо использовать при объявлении переменной-члена. @@ -1400,27 +1444,27 @@ '{0}' is not valid on a method declaration. - '"{0}" недопустимо использовать в объявлении метода. + "{0}" недопустимо использовать в объявлении метода. '{0}' is not valid on an event declaration. - '"{0}" недопустимо использовать при объявлении события. + "{0}" недопустимо использовать при объявлении события. '{0}' is not valid on a Declare. - '"{0}" является недопустимым для Declare. + "{0}" является недопустимым для Declare. '{0}' is not valid on a local constant declaration. - '"{0}" недопустимо использовать в объявлении локальной константы. + "{0}" недопустимо использовать в объявлении локальной константы. '{0}' is not valid on a local variable declaration. - '"{0}" недопустимо использовать в объявлении локальной переменной. + "{0}" недопустимо использовать в объявлении локальной переменной. @@ -1474,42 +1518,42 @@ '{0}' is already declared as '{1}' in this {2}. - '"{0}" уже объявлено как "{1}" в {2}. + "{0}" уже объявлено как "{1}" в {2}. '{0}' cannot override '{1}' because they have different access levels. - '"{0}" не может переопределить "{1}", поскольку у них разные уровни доступа. + "{0}" не может переопределить "{1}", поскольку у них разные уровни доступа. '{0}' cannot override '{1}' because it is declared 'NotOverridable'. - '"{0}" не может переопределить "{1}", поскольку он объявлен как "NotOverridable". + "{0}" не может переопределить "{1}", поскольку он объявлен как "NotOverridable". '{0}' has multiple definitions with identical signatures. - '"{0}" имеет несколько определений с одинаковыми сигнатурами. + "{0}" имеет несколько определений с одинаковыми сигнатурами. '{0}' has multiple definitions with identical signatures with different tuple element names, including '{1}'. - '"{0}" имеет несколько определений с одинаковыми подписями, но разными именами элементов кортежа, в том числе "{1}". + "{0}" имеет несколько определений с одинаковыми подписями, но разными именами элементов кортежа, в том числе "{1}". '{0}' is not valid on an interface method declaration. - '"{0}" является недопустимым объявлением метода интерфейса. + "{0}" является недопустимым объявлением метода интерфейса. '{0}' is not a parameter of '{1}'. - '"{0}" не является параметром "{1}". + "{0}" не является параметром "{1}". '{0}' is not valid on an interface property declaration. - '"{0}" является недопустимым объявлением свойства интерфейса. + "{0}" является недопустимым объявлением свойства интерфейса. @@ -1519,7 +1563,7 @@ '{0}' is not valid on an interface event declaration. - '"{0}" является недопустимым объявлением события интерфейса. + "{0}" является недопустимым объявлением события интерфейса. @@ -1618,17 +1662,17 @@ '{0}' cannot inherit from {2} '{1}' because '{1}' is declared 'NotInheritable'. - '"{0}" не может наследовать от {2} "{1}", поскольку "{1}" объявлен как "NotInheritable". + "{0}" не может наследовать от {2} "{1}", поскольку "{1}" объявлен как "NotInheritable". '{0}' and '{1}' cannot overload each other because they differ only by optional parameters. - '"{0}" и "{1}" не могут переопределить друг друга, так как они отличаются только по необязательным параметрам. + "{0}" и "{1}" не могут переопределить друг друга, так как они отличаются только по необязательным параметрам. '{0}' and '{1}' cannot overload each other because they differ only by return types. - '"{0}" и "{1}" не могут переопределить друг друга, так как они отличаются только по возвращаемым типам. + "{0}" и "{1}" не могут переопределить друг друга, так как они отличаются только по возвращаемым типам. @@ -1643,7 +1687,7 @@ '{0}' and '{1}' cannot overload each other because they differ only by the default values of optional parameters. - '"{0}" и "{1}" не могут переопределить друг друга, так как они отличаются только по значениям по умолчанию необязательных параметров. + "{0}" и "{1}" не могут переопределить друг друга, так как они отличаются только по значениям по умолчанию необязательных параметров. @@ -1653,12 +1697,12 @@ '{0}' cannot override '{1}' because they differ by the default values of optional parameters. - '"{0}" не может переопределить "{1}", так как они отличаются по значениям по умолчанию необязательных параметров. + "{0}" не может переопределить "{1}", так как они отличаются по значениям по умолчанию необязательных параметров. '{0}' cannot override '{1}' because they differ by optional parameters. - '"{0}" не может переопределить "{1}", так как они отличаются по необязательным параметрам. + "{0}" не может переопределить "{1}", так как они отличаются по необязательным параметрам. @@ -1693,7 +1737,7 @@ '{0}' and '{1}' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'. - '"{0}" и "{1}" не могут переопределить друг друга, так как они отличаются только по параметрам, объявленным "ByRef" или "ByVal". + "{0}" и "{1}" не могут переопределить друг друга, так как они отличаются только по параметрам, объявленным "ByRef" или "ByVal". @@ -1713,12 +1757,12 @@ '{0}' and '{1}' cannot overload each other because only one is declared 'Default'. - '"{0}" и "{1}" не могут перегружать друг друга, т. к. только один из них объявлен как "Default". + "{0}" и "{1}" не могут перегружать друг друга, т. к. только один из них объявлен как "Default". '{0}' cannot override '{1}' because they differ by 'ReadOnly' or 'WriteOnly'. - '"{0}" не может переопределить "{1}", так как они отличаются по типу "ReadOnly" или "WriteOnly". + "{0}" не может переопределить "{1}", так как они отличаются по типу "ReadOnly" или "WriteOnly". @@ -1733,7 +1777,7 @@ '{0}' and '{1}' cannot overload each other because they differ only by 'ReadOnly' or 'WriteOnly'. - '"{0}" и "{1}" не могут переопределить друг друга, так как они отличаются только по "ReadOnly" или "WriteOnly". + "{0}" и "{1}" не могут переопределить друг друга, так как они отличаются только по "ReadOnly" или "WriteOnly". @@ -1743,7 +1787,7 @@ '{0}' and '{1}' cannot overload each other because they differ only by parameters declared 'ParamArray'. - '"{0}" и "{1}" не могут переопределить друг друга, так как они отличаются только по параметрам, объявленным "ParamArray". + "{0}" и "{1}" не могут переопределить друг друга, так как они отличаются только по параметрам, объявленным "ParamArray". @@ -1798,7 +1842,7 @@ '{0}' is not valid on a Delegate declaration. - '"{0}" недопустимо использовать при объявлении делегата. + "{0}" недопустимо использовать при объявлении делегата. @@ -1808,12 +1852,12 @@ '{0}' is not accessible in this context because it is '{1}'. - '"{0}" в этом контексте недоступен, так как он является "{1}". + "{0}" в этом контексте недоступен, так как он является "{1}". '{0}.{1}' is not accessible in this context because it is '{2}'. - '"{0}.{1}" в этом контексте недоступен, так как он является "{2}". + "{0}.{1}" в этом контексте недоступен, так как он является "{2}". @@ -1828,22 +1872,22 @@ '{0}' is not valid on a Structure declaration. - '"{0}" недопустимо использовать в объявлении Structure. + "{0}" недопустимо использовать в объявлении Structure. '{0}' is not valid on an Enum declaration. - '"{0}" недопустимо использовать при объявлении перечисления. + "{0}" недопустимо использовать при объявлении перечисления. '{0}' is not valid on an Interface declaration. - '"{0}" является недопустимым объявлением интерфейса. + "{0}" является недопустимым объявлением интерфейса. '{0}' cannot override '{1}' because they differ by a parameter that is marked as 'ByRef' versus 'ByVal'. - '"{0}" не может переопределить "{1}", так как они отличаются по параметру, который помечен как ByRef" относительно "ByVal". + "{0}" не может переопределить "{1}", так как они отличаются по параметру, который помечен как ByRef" относительно "ByVal". @@ -1853,12 +1897,12 @@ '{0}' cannot implement '{1}' because there is no matching {2} on interface '{3}'. - '"{0}" не может реализовать "{1}", поскольку нет соответствующего {2} в интерфейсе "{3}". + "{0}" не может реализовать "{1}", поскольку нет соответствующего {2} в интерфейсе "{3}". '{0}' cannot implement {1} '{2}' on interface '{3}' because the tuple element names in '{4}' do not match those in '{5}'. - '"{0}" не может реализовать {1} "{2}" в интерфейсе "{3}", так как имена элементов кортежа в "{4}" не соответствуют именам в "{5}". + "{0}" не может реализовать {1} "{2}" в интерфейсе "{3}", так как имена элементов кортежа в "{4}" не соответствуют именам в "{5}". @@ -1923,12 +1967,12 @@ '{0}' cannot override '{1}' because they differ by their return types. - '"{0}" не может переопределить "{1}", так как их возвращаемые типы различны. + "{0}" не может переопределить "{1}", так как их возвращаемые типы различны. '{0}' cannot override '{1}' because they differ by their tuple element names. - '"{0}" не может переопределять "{1}", так как они отличаются именами элементов кортежа. + "{0}" не может переопределять "{1}", так как они отличаются именами элементов кортежа. @@ -1958,7 +2002,7 @@ '{0}' is not declared. It may be inaccessible due to its protection level. - '"{0}" не объявлена. Возможно, она недоступна из-за своего уровня защиты. + "{0}" не объявлена. Возможно, она недоступна из-за своего уровня защиты. @@ -1978,7 +2022,7 @@ '{0}' is not a member of '{1}'. - '"{0}" не является членом "{1}". + "{0}" не является членом "{1}". @@ -1998,7 +2042,7 @@ '{1}' for the Imports '{0}' does not refer to a Namespace, Class, Structure, Enum or Module. - '"{1}" для Imports "{0}" не ссылается на Namespace, Class, Structure, Enum или Module. + "{1}" для Imports "{0}" не ссылается на Namespace, Class, Structure, Enum или Module. @@ -2103,7 +2147,7 @@ '{0}' cannot inherit from {1} '{2}' because it expands the access of the base {1} to {3} '{4}'. - '"{0}" не может наследовать от {1} "{2}", поскольку он расширяет доступ базы {1} до {3} "{4}". + "{0}" не может наследовать от {1} "{2}", поскольку он расширяет доступ базы {1} до {3} "{4}". @@ -2205,7 +2249,7 @@ '{0}' cannot be indexed because it has no default property. - '"{0}" невозможно индексировать, поскольку он не содержит свойства по умолчанию. + "{0}" невозможно индексировать, поскольку он не содержит свойства по умолчанию. @@ -2220,7 +2264,7 @@ '{0}' is ambiguous. - '"{0}" неоднозначен. + "{0}" неоднозначен. @@ -2230,22 +2274,22 @@ '{0}' is ambiguous in the namespace '{1}'. - '"{0}" неоднозначен в пространстве имен "{1}". + "{0}" неоднозначен в пространстве имен "{1}". '{0}' is ambiguous, imported from the namespaces or types '{1}'. - '"{0}", импортированный из пространств имен или типов "{1}", является неоднозначным. + "{0}", импортированный из пространств имен или типов "{1}", является неоднозначным. '{0}' is ambiguous between declarations in Modules '{1}'. - '"{0}" неоднозначен для объявлений в модулях "{1}". + "{0}" неоднозначен для объявлений в модулях "{1}". '{0}' is ambiguous between declarations in namespaces '{1}'. - '"{0}" неоднозначен для объявлений в пространствах имен "{1}". + "{0}" неоднозначен для объявлений в пространствах имен "{1}". @@ -2320,12 +2364,12 @@ '{0}.{1}' cannot be implemented more than once. - '"{0}.{1}" невозможно реализовать более одного раза. + "{0}.{1}" невозможно реализовать более одного раза. '{0}' cannot be inherited more than once. - '"{0}" не может наследоваться несколько раз. + "{0}" не может наследоваться несколько раз. @@ -2390,7 +2434,7 @@ '{0}' is a MustOverride event in the base class '{1}'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class '{2}' MustInherit. - '"{0}" является событием MustOverride в базовом классе "{1}". Visual Basic не поддерживает переопределение событий. Необходимо предоставить реализацию события в базовом классе или задать для класса "{2}" значение MustInherit. + "{0}" является событием MustOverride в базовом классе "{1}". Visual Basic не поддерживает переопределение событий. Необходимо предоставить реализацию события в базовом классе или задать для класса "{2}" значение MustInherit. @@ -2570,7 +2614,7 @@ '{0}' is an unsupported type. - '"{0}" является неподдерживаемым типом. + "{0}" является неподдерживаемым типом. @@ -2605,7 +2649,7 @@ '{0}' has a return type that is not supported or parameter types that are not supported. - '"{0}" имеет возвращаемый тип или типы параметров, которые не поддерживаются. + "{0}" имеет возвращаемый тип или типы параметров, которые не поддерживаются. @@ -2687,7 +2731,7 @@ '{0}' is obsolete: '{1}'. - '"{0}" является устаревшим: "{1}". + "{0}" является устаревшим: "{1}". @@ -2717,7 +2761,7 @@ '{0}' is not an event of '{1}'. - '"{0}" не является событием "{1}". + "{0}" не является событием "{1}". @@ -2782,7 +2826,7 @@ '{0}' cannot override '{1}' because they differ by the types of optional parameters. - '"{0}" не может переопределить "{1}", так как они отличаются по типам необязательных параметров. + "{0}" не может переопределить "{1}", так как они отличаются по типам необязательных параметров. @@ -2802,7 +2846,7 @@ '{0}' is already declared as a parameter of this method. - '"{0}" уже объявлена как параметр этого метода. + "{0}" уже объявлена как параметр этого метода. @@ -2942,7 +2986,7 @@ '{1}' for the Imports alias to '{0}' does not refer to a Namespace, Class, Structure, Interface, Enum or Module. - '"{1}" псевдонима Imports для "{0}" не ссылается на Namespace, Class, Structure, Interface, Enum или Module. + "{1}" псевдонима Imports для "{0}" не ссылается на Namespace, Class, Structure, Interface, Enum или Module. @@ -3027,7 +3071,7 @@ '{0}' cannot override '{1}' because they differ by parameters declared 'ParamArray'. - '"{0}" не может переопределить "{1}", так как они отличаются по параметрам, объявленным как "ParamArray". + "{0}" не может переопределить "{1}", так как они отличаются по параметрам, объявленным как "ParamArray". @@ -3042,32 +3086,32 @@ '{0}' cannot expose type '{1}' outside the project through {2} '{3}'. - '"{0}" не может представлять тип "{1}" вне проекта посредством {2} "{3}". + "{0}" не может представлять тип "{1}" вне проекта посредством {2} "{3}". '{0}' cannot inherit from {1} '{2}' because it expands the access of the base {1} outside the assembly. - '"{0}" не может наследовать от {1} "{2}", поскольку он расширяет доступ базы {1} за пределы сборки. + "{0}" не может наследовать от {1} "{2}", поскольку он расширяет доступ базы {1} за пределы сборки. '{0}' accessor of '{1}' is obsolete: '{2}'. - '"{0}" средство доступа для "{1}" устарело: '{2}'. + "{0}" средство доступа для "{1}" устарело: '{2}'. '{0}' accessor of '{1}' is obsolete. - '"{0}" средство доступа для "{1}" устарело. + "{0}" средство доступа для "{1}" устарело. '{0}' cannot expose the underlying delegate type '{1}' of the event it is implementing to {2} '{3}' through {4} '{5}'. - '"{0}" не может представлять базовый тип делегата "{1}" события, которое он реализует в {2} "{3}" посредством {4} "{5}". + "{0}" не может представлять базовый тип делегата "{1}" события, которое он реализует в {2} "{3}" посредством {4} "{5}". '{0}' cannot expose the underlying delegate type '{1}' of the event it is implementing outside the project through {2} '{3}'. - '"{0}" не может представлять базовый тип делегата "{1}" события, которое он реализует вне проекта посредством {2} "{3}". + "{0}" не может представлять базовый тип делегата "{1}" события, которое он реализует вне проекта посредством {2} "{3}". @@ -3097,12 +3141,12 @@ '{0}' cannot inherit from {1} '{2}' because it expands the access of type '{3}' to {4} '{5}'. - '"{0}" не может наследовать от {1} "{2}", поскольку он расширяет доступ типа "{3}" до {4} "{5}". + "{0}" не может наследовать от {1} "{2}", поскольку он расширяет доступ типа "{3}" до {4} "{5}". '{0}' cannot inherit from {1} '{2}' because it expands the access of type '{3}' outside the assembly. - '"{0}" не может наследовать от {1} "{2}", поскольку он расширяет доступ типа "{3}" за пределы данной сборки. + "{0}" не может наследовать от {1} "{2}", поскольку он расширяет доступ типа "{3}" за пределы данной сборки. @@ -3213,7 +3257,7 @@ '{0}' in class '{1}' cannot override '{2}' in class '{3}' because an intermediate class '{4}' overrides '{2}' in class '{3}' but is not accessible. - '"{0}" в классе "{1}" не может переопределять "{2}" в классе "{3}", поскольку недоступен промежуточный класс "{4}", переопределяющий "{2}" в классе "{3}". + "{0}" в классе "{1}" не может переопределять "{2}" в классе "{3}", поскольку недоступен промежуточный класс "{4}", переопределяющий "{2}" в классе "{3}". @@ -3358,7 +3402,7 @@ '{0}' exists in multiple base interfaces. Use the name of the interface that declares '{0}' in the 'Implements' clause instead of the name of the derived interface. - '"{0}" существует в нескольких базовых интерфейсах. Используйте имя данного интерфейса, которое объявляет "{0}" в предложении "Implements", а не имя производного интерфейса. + "{0}" существует в нескольких базовых интерфейсах. Используйте имя данного интерфейса, которое объявляет "{0}" в предложении "Implements", а не имя производного интерфейса. @@ -3508,17 +3552,17 @@ '{0}' is obsolete. - '"{0}" является устаревшим. + "{0}" является устаревшим. '{0}' is a module and cannot be referenced as an assembly. - '"{0}" является модулем и не может указываться в ссылках как сборка. + "{0}" является модулем и не может указываться в ссылках как сборка. '{0}' is an assembly and cannot be referenced as a module. - '"{0}' является сборкой и не может указываться в ссылках как модуль. + "{0}" является сборкой и не может указываться в ссылках как модуль. @@ -3528,7 +3572,7 @@ '{0}' is not a local variable or parameter, and so cannot be used as a 'Catch' variable. - '"{0}" не является локальной переменной или параметром и поэтому не может использоваться как переменная оператора "Catch". + "{0}" не является локальной переменной или параметром и поэтому не может использоваться как переменная оператора "Catch". @@ -3548,7 +3592,7 @@ '{0}' cannot override '{1}' because it is not declared 'Overridable'. - '"{0}" не может переопределить "{1}", поскольку он не объявлен как "Overridable". + "{0}" не может переопределить "{1}", поскольку он не объявлен как "Overridable". @@ -3788,7 +3832,7 @@ '{0}' cannot refer to itself through its default instance; use 'Me' instead. - '"{0}" не может ссылаться на себя с помощью экземпляра по умолчанию; вместо этого используйте "Me". + "{0}" не может ссылаться на себя с помощью экземпляра по умолчанию; вместо этого используйте "Me". @@ -3803,7 +3847,7 @@ '{0}' cannot be applied to the 'AddHandler', 'RemoveHandler', or 'RaiseEvent' definitions. If required, apply the attribute directly to the event. - '"{0}" не может быть применен к определениям "AddHandler", "RemoveHandler" или "RaiseEvent". При необходимости примените атрибут непосредственно к событию. + "{0}" не может быть применен к определениям "AddHandler", "RemoveHandler" или "RaiseEvent". При необходимости примените атрибут непосредственно к событию. @@ -4083,7 +4127,7 @@ '{0}' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. - '"{0}" не может принимать значение Null и не может быть использовано в качестве типа данных элемента массива, поля, анонимного типа члена, аргумента типа, параметра "ByRef" или оператора return. + "{0}" не может принимать значение Null и не может быть использовано в качестве типа данных элемента массива, поля, анонимного типа члена, аргумента типа, параметра "ByRef" или оператора return. @@ -4113,7 +4157,7 @@ '{0}' cannot shadow a method declared 'MustOverride'. - '"{0}" не может сделать теневым метод, объявленный как "MustOverride". + "{0}" не может сделать теневым метод, объявленный как "MustOverride". @@ -4123,7 +4167,7 @@ '{0}' and '{1}' cannot be combined. - '"{0}" и "{1}" объединять нельзя. + "{0}" и "{1}" объединять нельзя. @@ -4133,7 +4177,7 @@ '{0}' must be declared 'MustInherit' because it contains methods declared 'MustOverride'. - '"{0}" должна быть объявлена как "MustInherit", потому что она содержит методы, объявленные как "MustOverride". + "{0}" должна быть объявлена как "MustInherit", потому что она содержит методы, объявленные как "MustOverride". @@ -4143,12 +4187,12 @@ '{0}', implicitly declared for {1} '{2}', cannot shadow a 'MustOverride' method in the base {3} '{4}'. - '"{0}", неявно объявленный для {1} "{2}", не может затенять метод "MustOverride" в базе {3} "{4}". + "{0}", неявно объявленный для {1} "{2}", не может затенять метод "MustOverride" в базе {3} "{4}". '{0}' cannot override '{1}' because it is not accessible in this context. - '"{0}" не может переопределить "{1}", поскольку он недоступен в данном контексте. + "{0}" не может переопределить "{1}", поскольку он недоступен в данном контексте. @@ -4163,12 +4207,12 @@ '{0}' conflicts with the reserved member by this name that is implicitly declared in all enums. - '"{0}" конфликтует с зарезервированным членом по данному имени, которое явно объявлено во всех перечислениях. + "{0}" конфликтует с зарезервированным членом по данному имени, которое явно объявлено во всех перечислениях. '{0}' is already declared in this {1}. - '"{0}" уже объявлено в {1}. + "{0}" уже объявлено в {1}. @@ -4188,7 +4232,7 @@ '{0}' in assembly '{1}' has been forwarded to itself and so is an unsupported type. - '"{0}" в сборке "{1}" был перемещен к себе и поэтому является недопустимым типом. + "{0}" в сборке "{1}" был перемещен к себе и поэтому является недопустимым типом. @@ -4208,7 +4252,7 @@ '{0}' is ambiguous because multiple kinds of members with this name exist in {1} '{2}'. - '"{0}" неоднозначно, поскольку несколько видов членов с данным именем существует в {1} "{2}". + "{0}" неоднозначно, поскольку несколько видов членов с данным именем существует в {1} "{2}". @@ -4243,7 +4287,7 @@ '{0}' cannot be declared 'Partial' because partial methods must be Subs. - '"{0}" не может быть объявлен "Partial", так как разделяемые методы должны быть Subs. + "{0}" не может быть объявлен "Partial", так как разделяемые методы должны быть Subs. @@ -4298,17 +4342,17 @@ '{0}' cannot be used as an attribute because it is not a class. - '"{0}" нельзя использовать как атрибут, поскольку он не является классом. + "{0}" нельзя использовать как атрибут, поскольку он не является классом. '{0}' cannot be used as an attribute because it does not inherit from 'System.Attribute'. - '"{0}" нельзя использовать как атрибут, так как он не является производным от "System.Attribute". + "{0}" нельзя использовать как атрибут, так как он не является производным от "System.Attribute". '{0}' cannot be used as an attribute because it is declared 'MustInherit'. - '"{0}" не может использоваться как атрибут, поскольку он объявлен как "MustInherit". + "{0}" не может использоваться как атрибут, поскольку он объявлен как "MustInherit". @@ -4408,7 +4452,7 @@ '{0}' is not valid within a Module. - '"{0}" не является допустимым в модуле. + "{0}" не является допустимым в модуле. @@ -4438,7 +4482,7 @@ '{0}' cannot be named as a parameter in an attribute specifier because it is not a field or property. - '"{0}" нельзя указать как параметр в описателе атрибута, поскольку он не является полем или свойством. + "{0}" нельзя указать как параметр в описателе атрибута, поскольку он не является полем или свойством. @@ -4458,7 +4502,7 @@ '{0}' has no parameters and its return type cannot be indexed. - '"{0}" не имеет параметров, поэтому невозможно проиндексировать его возвращаемый тип. + "{0}" не имеет параметров, поэтому невозможно проиндексировать его возвращаемый тип. @@ -4483,7 +4527,7 @@ '{0}' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event. - '"{0}" является событием и не может вызываться напрямую. Для порождения события используйте оператор "RaiseEvent". + "{0}" является событием и не может вызываться напрямую. Для порождения события используйте оператор "RaiseEvent". @@ -4568,7 +4612,7 @@ '{0}' has no type parameters and so cannot have type arguments. - '"{0}" не имеет параметров типа и поэтому не может иметь аргументов типа. + "{0}" не имеет параметров типа и поэтому не может иметь аргументов типа. @@ -4608,7 +4652,7 @@ '{0}' has the same name as a type parameter. - '"{0}" имеет такое же имя, как и параметр типа. + "{0}" имеет такое же имя, как и параметр типа. @@ -4633,7 +4677,7 @@ '{0}' cannot be used as a type constraint. - '"{0}" нельзя использовать как ограничение типа. + "{0}" нельзя использовать как ограничение типа. @@ -4688,12 +4732,12 @@ '{0}' cannot override '{1}' because they differ by type parameter constraints. - '"{0}" не может переопределить "{1}", так как они отличаются по ограничениям параметра типа. + "{0}" не может переопределить "{1}", так как они отличаются по ограничениям параметра типа. '{0}' cannot implement '{1}.{2}' because they differ by type parameter constraints. - '"{0}" не может реализовать "{1}.{2}", поскольку они отличаются ограничениями параметра типа. + "{0}" не может реализовать "{1}.{2}", поскольку они отличаются ограничениями параметра типа. @@ -4748,7 +4792,7 @@ '{0}' is already declared as a type parameter of this method. - '"{0}" уже объявлен в качестве параметра типа этого метода. + "{0}" уже объявлен в качестве параметра типа этого метода. @@ -4935,7 +4979,7 @@ '{0}' cannot be declared 'Shadows' outside of a class, structure, or interface. - '"{0}" невозможно объявить "Shadows" вне области класса, структуры или интерфейса. + "{0}" невозможно объявить "Shadows" вне области класса, структуры или интерфейса. @@ -4950,7 +4994,7 @@ Multiple assemblies with equivalent identity have been imported: '{0}' and '{1}'. Remove one of the duplicate references. - Импортировано несколько сборок с одинаковыми удостоверениями: '{0}" и "{1}". Удалите одну из повторяющихся ссылок. + Импортировано несколько сборок с одинаковыми удостоверениями: "{0}" и "{1}". Удалите одну из повторяющихся ссылок. @@ -4970,7 +5014,7 @@ '{0}' cannot be applied because the format of the GUID '{1}' is not correct. - '"{0}" не может использоваться из-за неверного формата GUID "{1}". + "{0}" не может использоваться из-за неверного формата GUID "{1}". @@ -5060,7 +5104,7 @@ '{0}' parameters cannot be declared 'Optional'. - '"{0}" не могут быть объявлены "Optional". + "{0}" не могут быть объявлены "Optional". @@ -5340,7 +5384,7 @@ '{0}' has the same name as a member used for type '{1}' exposed in a 'My' group. Rename the type or its enclosing namespace. - '"{0}" имеет то же имя, что и член, используемый для типа "{1}" в группе "My". Переименуйте тип или его вложенное пространство имен. + "{0}" имеет то же имя, что и член, используемый для типа "{1}" в группе "My". Переименуйте тип или его вложенное пространство имен. @@ -5440,7 +5484,7 @@ '{0}' is not a member of '{1}'; it does not exist in the current context. - '"{0}" не является членом "{1}"; он не существует в текущем контексте. + "{0}" не является членом "{1}"; он не существует в текущем контексте. @@ -5512,7 +5556,7 @@ '{0}' is not a method parameter. - '"{0}" не является параметром метода. + "{0}" не является параметром метода. @@ -5564,7 +5608,7 @@ '{0}' is not a parameter of extension method '{1}' defined in '{2}'. - '"{0}" не является параметром метода расширения "{1}", определенного в "{2}". + "{0}" не является параметром метода расширения "{1}", определенного в "{2}". @@ -5609,7 +5653,7 @@ '{0}{1}' is not valid because '{2}' is inside a scope that defines a variable that is used in a lambda or query expression. - '"{0}{1}" является недопустимым, поскольку "{2}" находится внутри области, которая определяет переменную, используемую в лямбда-выражении или выражении запроса. + "{0}{1}" является недопустимым, поскольку "{2}" находится внутри области, которая определяет переменную, используемую в лямбда-выражении или выражении запроса. @@ -5749,7 +5793,7 @@ Range variable '{0}' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression. - Переменная диапазона ''{0}" скрывает переменную во внешнем блоке, ранее определенную переменную диапазона или неявно объявленную переменную в выражении запроса. + Переменная диапазона "{0}" скрывает переменную во внешнем блоке, ранее определенную переменную диапазона или неявно объявленную переменную в выражении запроса. @@ -5899,7 +5943,7 @@ '{0}' is not accessible in this context because the return type is not accessible. - '"{0}" в этом контексте недоступен, так как недоступен возвращаемый тип. + "{0}" в этом контексте недоступен, так как недоступен возвращаемый тип. @@ -5986,7 +6030,7 @@ '{0}' is obsolete: '{1}'. - '"{0}" является устаревшим: "{1}". + "{0}" является устаревшим: "{1}". @@ -6036,7 +6080,7 @@ '{0}' is obsolete. - '"{0}" является устаревшим. + "{0}" является устаревшим. @@ -6106,7 +6150,7 @@ '{0}' accessor of '{1}' is obsolete: '{2}'. - '"{0}" средство доступа для "{1}" устарело: '{2}'. + "{0}" средство доступа для "{1}" устарело: '{2}'. @@ -6116,7 +6160,7 @@ '{0}' accessor of '{1}' is obsolete. - '"{0}" средство доступа для "{1}" устарело. + "{0}" средство доступа для "{1}" устарело. @@ -6136,7 +6180,7 @@ '{0}' is not CLS-compliant because it derives from '{1}', which is not CLS-compliant. - '"{0}" несовместим с CLS, так как унаследован от "{1}", который несовместим с CLS. + "{0}" несовместим с CLS, так как унаследован от "{1}", который несовместим с CLS. @@ -6166,7 +6210,7 @@ '{0}' is not CLS-compliant because the interface '{1}' it inherits from is not CLS-compliant. - '"{0}" несовместим с CLS, так как унаследованный интерфейс "{1}" несовместим с CLS. + "{0}" несовместим с CLS, так как унаследованный интерфейс "{1}" несовместим с CLS. @@ -6226,7 +6270,7 @@ '{0}' is not CLS-compliant because it overloads '{1}' which differs from it only by array of array parameter types or by the rank of the array parameter types. - '"{0}" несовместим с CLS, так как перегружает "{1}", который отличается от него только массивом типов параметра массива или рангом типов параметра массива. + "{0}" несовместим с CLS, так как перегружает "{1}", который отличается от него только массивом типов параметра массива или рангом типов параметра массива. @@ -6356,7 +6400,7 @@ '{0}' method for event '{1}' cannot be marked CLS compliant because its containing type '{2}' is not CLS compliant. - '"{0}" метод для события "{1}" не может быть помечен как совместимый с CLS, потому что тип, который он содержит, "{2}" несовместим с CLS. + "{0}" метод для события "{1}" не может быть помечен как совместимый с CLS, потому что тип, который он содержит, "{2}" несовместим с CLS. @@ -6366,7 +6410,7 @@ '{0}' in designer-generated type '{1}' should call InitializeComponent method. - '"{0}" в типе, созданном конструктором "{1}", должен вызывать метод InitializeComponent. + "{0}" в типе, созданном конструктором "{1}", должен вызывать метод InitializeComponent. @@ -7361,7 +7405,7 @@ '{0}' cannot expose type '{1}' in {2} '{3}' through {4} '{5}'. - '"{0}" не может представлять тип "{1}" в {2} "{3}" посредством {4} "{5}". + "{0}" не может представлять тип "{1}" в {2} "{3}" посредством {4} "{5}". @@ -7371,7 +7415,7 @@ '{0}' cannot be implemented by a {1} property. - '"{0}" невозможно реализовать с помощью свойства {1}. + "{0}" невозможно реализовать с помощью свойства {1}. @@ -7663,12 +7707,12 @@ '{0}' cannot be converted to '{1}'. Consider using '{2}' instead. - '"{0}" нельзя преобразовать в "{1}". Попробуйте использовать "{2}". + "{0}" нельзя преобразовать в "{1}". Попробуйте использовать "{2}". '{0}' cannot be converted to '{1}'. Consider using '{2}' instead. - '"{0}" нельзя преобразовать в "{1}". Попробуйте использовать "{2}". + "{0}" нельзя преобразовать в "{1}". Попробуйте использовать "{2}". @@ -7678,7 +7722,7 @@ '{4}' cannot be converted to '{5}' because '{0}' is not derived from '{1}', as required for the 'In' generic parameter '{2}' in '{3}'. - '"{4}" нельзя преобразовать в "{5}", так как "{0}" не наследованы из "{1}" в соответствии с требованием универсального параметра "In" "{2}" в "{3}". + "{4}" нельзя преобразовать в "{5}", так как "{0}" не наследованы из "{1}" в соответствии с требованием универсального параметра "In" "{2}" в "{3}". @@ -7708,17 +7752,17 @@ '{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an In type parameter, 'In {2}'. - '{0}" нельзя преобразовать в "{1}". Попробуйте изменить "{2}" в определении "{3}" на параметр In, "In {2}". + "{0}" нельзя преобразовать в "{1}". Попробуйте изменить "{2}" в определении "{3}" на параметр In, "In {2}". '{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an Out type parameter, 'Out {2}'. - '{0}" нельзя преобразовать в "{1}". Попробуйте изменить "{2}" в определении "{3}" на параметр типа Out, "Out {2}". + "{0}" нельзя преобразовать в "{1}". Попробуйте изменить "{2}" в определении "{3}" на параметр типа Out, "Out {2}". '{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an In type parameter, 'In {2}'. - '{0}" нельзя преобразовать в "{1}". Попробуйте изменить "{2}" в определении "{3}" на параметр In, "In {2}". + "{0}" нельзя преобразовать в "{1}". Попробуйте изменить "{2}" в определении "{3}" на параметр In, "In {2}". @@ -7728,7 +7772,7 @@ '{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an Out type parameter, 'Out {2}'. - '{0}" нельзя преобразовать в "{1}". Попробуйте изменить "{2}" в определении "{3}" на параметр типа Out, "Out {2}". + "{0}" нельзя преобразовать в "{1}". Попробуйте изменить "{2}" в определении "{3}" на параметр типа Out, "Out {2}". @@ -7998,7 +8042,7 @@ '{0}' does not implement '{1}'. - '"{0}" не реализует "{1}". + "{0}" не реализует "{1}". @@ -8038,7 +8082,7 @@ '{0}' does not return a Task and cannot be awaited. Consider changing it to an Async Function. - '"{0}" не возвращает значения типа Task, и его нельзя ожидать. Попробуйте заменить его на функцию с модификатором Async. + "{0}" не возвращает значения типа Task, и его нельзя ожидать. Попробуйте заменить его на функцию с модификатором Async. @@ -8093,7 +8137,7 @@ '{0}' cannot be used as a parameter type for an Iterator or Async method. - '"{0}" не может быть использовано в качестве типа параметра для метода Iterator или Async. + "{0}" не может быть использовано в качестве типа параметра для метода Iterator или Async. @@ -8103,7 +8147,7 @@ '{0}' cannot be declared 'Partial' because it has the 'Async' modifier. - '"{0}" не может быть объявлен "Partial", так как имеет модификатор "Async". + "{0}" не может быть объявлен "Partial", так как имеет модификатор "Async". @@ -8218,12 +8262,12 @@ '{0}.{1}' from 'implements {2}' is already implemented by the base class '{3}'. Re-implementation of Windows Runtime Interface '{4}' is not allowed - '"{0}.{1}" из "implements {2}" уже реализован базовым классом "{3}". Повторная реализация интерфейса среды выполнения Windows "{4}" не разрешена. + "{0}.{1}" из "implements {2}" уже реализован базовым классом "{3}". Повторная реализация интерфейса среды выполнения Windows "{4}" не разрешена. '{0}.{1}' is already implemented by the base class '{2}'. Re-implementation of Windows Runtime Interface '{3}' is not allowed - '"{0}.{1}" уже реализован базовым классом "{2}". Повторная реализация интерфейса среды выполнения Windows "{3}" не разрешена. + "{0}.{1}" уже реализован базовым классом "{2}". Повторная реализация интерфейса среды выполнения Windows "{3}" не разрешена. @@ -8448,12 +8492,12 @@ '{0}' is an unsupported .NET module. - '"{0}" не поддерживается модулем .NET. + "{0}" не поддерживается модулем .NET. '{0}' is an unsupported event. - '"{0}" является неподдерживаемым событием. + "{0}" является неподдерживаемым событием. @@ -8718,7 +8762,7 @@ '{0}' is not a valid format specifier - '{0}" не является допустимым описателем формата. + "{0}" не является допустимым описателем формата. @@ -8733,7 +8777,7 @@ '{0}' cannot be made nullable. - '"{0}" не может быть стать параметром, допускающим NULL. + "{0}" не может быть стать параметром, допускающим NULL. @@ -9103,7 +9147,7 @@ '{0}' is for evaluation purposes only and is subject to change or removal in future updates. - '"{0}" предназначен только для оценки и может быть изменен или удален в будущих обновлениях. + "{0}" предназначен только для оценки и может быть изменен или удален в будущих обновлениях. diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.tr.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.tr.xlf index 2df1e7145559e..6e338188158df 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.tr.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.tr.xlf @@ -14,7 +14,7 @@ Type '{0}' cannot be embedded because it has a non-abstract member. Consider setting the 'Embed Interop Types' property to false. - {0}' türünün soyut olmayan bir üyesi olduğundan bu tür eklenemiyor. 'Embed Interop Types' özelliğini false olarak ayarlamayı deneyin. + '{0}' türünün soyut olmayan bir üyesi olduğundan bu tür eklenemiyor. 'Embed Interop Types' özelliğini false olarak ayarlamayı deneyin. @@ -212,169 +212,169 @@ -vbruntime:<file> Compile with the alternate Visual Basic runtime in <file>. - Visual Basic Compiler Options + Visual Basic Derleyici Seçenekleri - - OUTPUT FILE - --out:<file> Specifies the output file name. --target:exe Create a console application (default). - (Short form: -t) --target:winexe Create a Windows application. --target:library Create a library assembly. --target:module Create a module that can be added to an - assembly. --target:appcontainerexe Create a Windows application that runs in - AppContainer. --target:winmdobj Create a Windows Metadata intermediate file --doc[+|-] Generates XML documentation file. --doc:<file> Generates XML documentation file to <file>. --refout:<file> Reference assembly output to generate + - ÇIKIŞ DOSYASI - +-out:<dosya> Çıkış dosyası adını belirtir. +-target:exe Konsol uygulaması oluştur (varsayılan). + (Kısa biçim: -t) +-target:winexe Windows uygulaması oluştur. +-target:library Kitaplık bütünleştirilmiş kodu oluştur. +-target:module Bütünleştirilmiş koda eklenebilecek bir modül + oluştur. +-target:appcontainerexe AppContainer içinde çalışan bir Windows + uygulaması oluştur. +-target:winmdobj Windows Meta Veri ara dosyası oluştur +-doc[+|-] XML belge dosyası oluşturur. +-doc:<dosya> <dosya> adlı XML belge dosyasını oluşturur. +-refout:<dosya> Oluşturulacak başvuru bütünleştirilmiş kodu çıkışı - - INPUT FILES - --addmodule:<file_list> Reference metadata from the specified modules --link:<file_list> Embed metadata from the specified interop - assembly. (Short form: -l) --recurse:<wildcard> Include all files in the current directory - and subdirectories according to the - wildcard specifications. --reference:<file_list> Reference metadata from the specified - assembly. (Short form: -r) --analyzer:<file_list> Run the analyzers from this assembly - (Short form: -a) --additionalfile:<file list> Additional files that don't directly affect code - generation but may be used by analyzers for producing - errors or warnings. + - GİRİŞ DOSYALARI - +-addmodule:<dosya_listesi> Belirtilen modüllerdeki meta verilere başvur +-link:<dosya_listesi> Belirtilen birlikte çalışma bütünleştirilmiş + kodundaki meta verileri ekle. (Kısa biçim: -l) +-recurse:<joker_karakter> Geçerli dizin ve alt dizinlerdeki tüm + dosyaları belirtilen joker karakterlere + göre ekle. +-reference:<dosya_listesi> Belirtilen bütünleştirilmiş koddaki meta verilere + başvur. (Kısa biçim: -r) +-analyzer:<dosya_listesi> Çözümleyicileri bu bütünleştirilmiş koddan çalıştır + (Kısa biçim: -a) +-additionalfile:<dosya listesi> Kod oluşturmayı doğrudan etkilemeyen ancak hata veya uyarılar + oluşturmak için çözümleyicilerin + kullanabileceği ek dosyalar. - - RESOURCES - --linkresource:<resinfo> Links the specified file as an external - assembly resource. - resinfo:<file>[,<name>[,public|private]] - (Short form: -linkres) --nowin32manifest The default manifest should not be embedded - in the manifest section of the output PE. --resource:<resinfo> Adds the specified file as an embedded - assembly resource. - resinfo:<file>[,<name>[,public|private]] - (Short form: -res) --win32icon:<file> Specifies a Win32 icon file (.ico) for the - default Win32 resources. --win32manifest:<file> The provided file is embedded in the manifest - section of the output PE. --win32resource:<file> Specifies a Win32 resource file (.res). + - KAYNAKLAR - +-linkresource:<kaynak_bilgileri> Belirtilen dosyayı dış bir bütünleştirilmiş + kod kaynağı olarak bağlar. + kaynak_bilgileri:<dosya>[,<ad>[,public|private]] + (Kısa biçim: -linkres) +-nowin32manifest Varsayılan bildirim, çıkış PE'nin bildirim + bölümüne eklenmemelidir. +-resource:<kaynak_bilgileri> Belirtilen dosyayı eklenen bütünleştirilmiş kod + kaynağı olarak ekler. + kaynak_bilgileri:<dosya>[,<ad>[,public|private]] + (Kısa biçim: -res) +-win32icon:<dosya> Varsayılan Win32 kaynakları için bir Win32 + simge dosyası (.ico) belirtir. +-win32manifest:<dosya> Belirtilen dosya, çıkış PE'sinin bildirim + bölümüne eklenir. +-win32resource:<dosya> Win32 kaynak dosyası (.res) belirtir. - - CODE GENERATION - --optimize[+|-] Enable optimizations. --removeintchecks[+|-] Remove integer checks. Default off. --debug[+|-] Emit debugging information. --debug:full Emit full debugging information (default). --debug:pdbonly Emit full debugging information. --debug:portable Emit cross-platform debugging information. --debug:embedded Emit cross-platform debugging information into - the target .dll or .exe. --deterministic Produce a deterministic assembly - (including module version GUID and timestamp) --refonly Produce a reference assembly in place of the main output --instrument:TestCoverage Produce an assembly instrumented to collect - coverage information --sourcelink:<file> Source link info to embed into PDB. + - KOD OLUŞTURMA - +-optimize[+|-] İyileştirmeleri etkinleştir. +-removeintchecks[+|-] Tamsayı denetimlerini kaldır. Varsayılan olarak kapalıdır. +-debug[+|-] Hata ayıklama bilgilerini göster. +-debug:full Tam hata ayıklama bilgilerini göster (varsayılan). +-debug:pdbonly Tam hata ayıklama bilgilerini göster. +-debug:portable Platformlar arası hata ayıklama bilgilerini göster. +-debug:embedded Platformlar arası hata ayıklama bilgilerini + hedef .dll veya .exe dosyasında göster. +-deterministic Belirlenimci bütünleştirilmiş kod oluştur + (modül sürümü GUID'si ve zaman damgası dahil) +-refonly Ana çıkış yerine başvuru bütünleştirilmiş kodu oluştur +-instrument:TestCoverage Kapsam bilgilerini toplamak üzere izleme eklenmiş bütünleştirilmiş + kod oluştur +-sourcelink:<dosya> PDB'ye eklenecek kaynak bağlantı bilgileri. - - ERRORS AND WARNINGS - --nowarn Disable all warnings. --nowarn:<number_list> Disable a list of individual warnings. --warnaserror[+|-] Treat all warnings as errors. --warnaserror[+|-]:<number_list> Treat a list of warnings as errors. --ruleset:<file> Specify a ruleset file that disables specific - diagnostics. --errorlog:<file>[,version=<sarif_version>] - Specify a file to log all compiler and analyzer - diagnostics in SARIF format. - sarif_version:{1|2|2.1} Default is 1. 2 and 2.1 - both mean SARIF version 2.1.0. --reportanalyzer Report additional analyzer information, such as - execution time. --skipanalyzers[+|-] Skip execution of diagnostic analyzers. + - HATALAR VE UYARILAR - +-nowarn Tüm uyarıları devre dışı bırak. +-nowarn:<numara_listesi> Ayrı ayrı uyarıların listesini devre dışı bırak. +-warnaserror[+|-] Tüm uyarıları hata olarak işle. +-warnaserror[+|-]:<numara_listesi> Listelenen uyarıları hata olarak işle. +-ruleset:<dosya> Belirli tanılamaları devre dışı bırakan bir kural + kümesi dosyası belirt. +-errorlog:<dosya>[,version=<sarif_sürümü>] + Tüm derleyici ve çözümleyici tanılamalarının SARIF + biçiminde kaydedilebileceği bir günlük dosyası belirt. + sarif_sürümü:{1|2|2.1} Varsayılan 1 sürümüdür. 2 ve 2.1 + sürümlerinin ikisi de SARIF 2.1.0 sürümü anlamına gelir. +-reportanalyzer Yürütme zamanı gibi ek çözümleyici + bilgilerini bildir. - - LANGUAGE - --define:<symbol_list> Declare global conditional compilation - symbol(s). symbol_list:name=value,... - (Short form: -d) --imports:<import_list> Declare global Imports for namespaces in - referenced metadata files. - import_list:namespace,... --langversion:? Display the allowed values for language version --langversion:<string> Specify language version such as - `default` (latest major version), or - `latest` (latest version, including minor versions), - or specific versions like `14` or `15.3` --optionexplicit[+|-] Require explicit declaration of variables. --optioninfer[+|-] Allow type inference of variables. --rootnamespace:<string> Specifies the root Namespace for all type - declarations. --optionstrict[+|-] Enforce strict language semantics. --optionstrict:custom Warn when strict language semantics are not - respected. --optioncompare:binary Specifies binary-style string comparisons. - This is the default. --optioncompare:text Specifies text-style string comparisons. + - DİL - +-define:<sembol_listesi> Genel koşullu derleme sembollerini + bildir. sembol_listesi:ad=değer,... + (Kısa biçim: -d) +-imports:<içeri_aktarma_listesi> Başvurulan meta veri dosyalarındaki ad + alanları için genel içeri aktarmaları bildir. + içeri_aktarma_listesi:ad_alanı,... +-langversion:? Dil sürümü için izin verilen değerleri görüntüle +-langversion:<dize> Dil sürümünü belirt. Örneğin: + `default` (en son birincil sürüm) veya + `latest` (ikincil sürümleri de içeren en son sürüm) + veya `14` ya da `15.3` gibi belirli sürümler +-optionexplicit[+|-] Değişkenlerin açık bir şekilde bildirilmesini gerektir. +-optioninfer[+|-] Değişkenlerde tür çıkarımına izin ver. +-rootnamespace:<dize> Tüm tür bildirimleri için kök Ad Alanını + belirtir. +-optionstrict[+|-] Katı dil kurallarını uygula. +-optionstrict:custom Katı dil kurallarına uyulmadığında + uyar. +-optioncompare:binary İkili stili dize karşılaştırmalarını belirtir. + Bu, varsayılandır. +-optioncompare:text Metin stili dize karşılaştırmalarını belirtir. - - MISCELLANEOUS - --help Display this usage message. (Short form: -?) --noconfig Do not auto-include VBC.RSP file. --nologo Do not display compiler copyright banner. --quiet Quiet output mode. --verbose Display verbose messages. --parallel[+|-] Concurrent build. --version Display the compiler version number and exit. + - DİĞER - +-help Bu kullanım iletisini görüntüle. (Kısa biçim: -?) +-noconfig VBC.RSP dosyasını otomatik olarak dahil etme. +-nologo Derleyici telif hakkı başlığını görüntüleme. +-quiet Sessiz çıkış modu. +-verbose Ayrıntılı iletileri görüntüle. +-parallel[+|-] Eş zamanlı derleme. +-version Derleyici sürüm numarasını görüntüleyip çıkış yap. - - ADVANCED - --baseaddress:<number> The base address for a library or module - (hex). --checksumalgorithm:<alg> Specify algorithm for calculating source file - checksum stored in PDB. Supported values are: - SHA1 or SHA256 (default). --codepage:<number> Specifies the codepage to use when opening - source files. --delaysign[+|-] Delay-sign the assembly using only the public - portion of the strong name key. --publicsign[+|-] Public-sign the assembly using only the public - portion of the strong name key. --errorreport:<string> Specifies how to handle internal compiler - errors; must be prompt, send, none, or queue - (default). --filealign:<number> Specify the alignment used for output file - sections. --highentropyva[+|-] Enable high-entropy ASLR. --keycontainer:<string> Specifies a strong name key container. --keyfile:<file> Specifies a strong name key file. --libpath:<path_list> List of directories to search for metadata - references. (Semi-colon delimited.) --main:<class> Specifies the Class or Module that contains - Sub Main. It can also be a Class that - inherits from System.Windows.Forms.Form. - (Short form: -m) --moduleassemblyname:<string> Name of the assembly which this module will - be a part of. --netcf Target the .NET Compact Framework. --nostdlib Do not reference standard libraries - (system.dll and VBC.RSP file). --pathmap:<K1>=<V1>,<K2>=<V2>,... - Specify a mapping for source path names output by - the compiler. --platform:<string> Limit which platforms this code can run on; - must be x86, x64, Itanium, arm, arm64 - AnyCPU32BitPreferred or anycpu (default). --preferreduilang Specify the preferred output language name. --nosdkpath Disable searching the default SDK path for standard library assemblies. --sdkpath:<path> Location of the .NET Framework SDK directory - (mscorlib.dll). --subsystemversion:<version> Specify subsystem version of the output PE. - version:<number>[.<number>] --utf8output[+|-] Emit compiler output in UTF8 character - encoding. -@<file> Insert command-line settings from a text file --vbruntime[+|-|*] Compile with/without the default Visual Basic - runtime. --vbruntime:<file> Compile with the alternate Visual Basic - runtime in <file>. + - GELİŞMİŞ - +-baseaddress:<sayı> Kitaplık veya modülün taban adresi + (onaltılık). +-checksumalgorithm:<alg> PDB'de depolanan kaynak dosya sağlama toplamını + hesaplama algoritmasını belirt. Desteklenen değerler: + SHA1 veya SHA256 (varsayılan). +-codepage:<sayı> Kaynak dosyalar açılırken kullanılacak kod + sayfasını belirtir. +-delaysign[+|-] Bütünleştirilmiş kodu, tanımlayıcı ad anahtarının + yalnızca genel kısmıyla geç imzala. +-publicsign[+|-] Bütünleştirilmiş kodu, tanımlayıcı ad anahtarının + yalnızca genel kısmıyla genel olarak imzala. +-errorreport:<dize> İç derleyici hatalarını işleme yöntemini + belirtir; prompt, send, none veya queue + (varsayılan) olmalıdır. +-filealign:<sayı> Çıktı dosyası bölümleri için kullanılan hizalamayı + belirt. +-highentropyva[+|-] Yüksek entropili ASLR'yi etkinleştir. +-keycontainer:<dize> Tanımlayıcı ad anahtarı kapsayıcısı belirtir. +-keyfile:<dosya> Tanımlayıcı ad anahtarı dosyası belirtir. +-libpath:<yol_listesi> Meta veri başvuruları için aranacak dizin + listesi. (Noktalı virgülle ayrılmış olarak.) +-main:<sınıf> Sub Main'i içeren sınıf veya modülü + belirtir. System.Windows.Forms.Form'dan + devralınan bir sınıf da olabilir. + (Kısa biçim: -m) +-moduleassemblyname:<dizi> Bu modülün bir parçası olacağı bütünleştirilmiş kodun + adı. +-netcf .NET Compact Framework'ü hedefle. +-nostdlib Standart kitaplıklara (system.dll ve VBC.RSP dosyası) + başvurma. +-pathmap:<A1>=<D1>,<A2>=<D2>,... + Derleyici tarafından kaynak yolu adları çıkışı için bir + eşleme belirt. +-platform:<dize> Bu kodun çalışabileceği platformları sınırla; + x86, x64, Itanium, arm, arm64, AnyCPU32BitPreferred + veya anycpu (varsayılan) olmalıdır. +-preferreduilang Tercih edilen çıkış dili adını belirt. +-nosdkpath Standart kitaplık bütünleştirilmiş kodları için varsayılan + SDK yolunu aramayı devre dışı bırak. +-sdkpath:<yol> .NET Framework SDK (mscorlib.dll) dizininin + konumu. +-subsystemversion:<sürüm> Çıkış PE'nin alt sistem sürümünü belirt. + version:<sayı>[.<sayı>] +-utf8output[+|-] Derleyici çıkışını UTF8 karakter kodlamasıyla + göster. +@<dosya> Bir metin dosyasından komut satırı ayarları ekle. +-vbruntime[+|-|*] Varsayılan Visual Basic çalışma zamanı dosyasıyla veya + bu dosya olmadan derle. +-vbruntime:<dosya> <dosya> içindeki alternatif Visual Basic çalışma zamanıyla + derle. @@ -463,6 +463,50 @@ Tür bağımsız değişkeni Nothing olamaz + + The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + '{1}' türünü içeren '{0}' bütünleştirilmiş kodu, desteklenmeyen .NET Framework'e başvuruyor. + {1} is the type that was loaded, {0} is the containing assembly. + + + The loaded assembly references .NET Framework, which is not supported. + Yüklenen bütünleştirilmiş kod, desteklenmeyen .NET Framework'e başvuruyor. + + + + Generator '{0}' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + '{0}' oluşturucusu kaynak oluşturamadı. Oluşturucu çıkışa katkıda bulunmayacağından, bunun sonucunda derleme hataları oluşabilir. Özel durum '{2}' iletisi ile '{1}' türündeydi + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + Oluşturucu aşağıdaki özel durumu oluşturdu: +'{0}'. + {0} is the string representation of the exception that was thrown. + + + Generator failed to generate source. + Oluşturucu kaynak oluşturamadı. + + + + Generator '{0}' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + '{0}' oluşturucusu başlatılamadı. Oluşturucu çıkışa katkıda bulunmayacağından, bunun sonucunda derleme hataları oluşabilir. Özel durum '{2}' iletisi ile '{1}' türündeydi + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + Oluşturucu aşağıdaki özel durumu oluşturdu: +'{0}'. + {0} is the string representation of the exception that was thrown. + + + Generator failed to initialize. + Oluşturucu başlatılamadı. + + Wrong number of type arguments Tür bağımsız değişkenlerinin yanlış sayısı @@ -470,32 +514,32 @@ file '{0}' could not be found - {0}' dosyası bulunamadı + '{0}' dosyası bulunamadı unable to open response file '{0}' - {0}' yanıt dosyası açılamadı + '{0}' yanıt dosyası açılamadı option '{0}' requires '{1}' - {0}' seçeneği için '{1}' gerekiyor + '{0}' seçeneği için '{1}' gerekiyor option '{0}' can be followed only by '+' or '-' - {0}' seçeneğinin arkasından yalnızca '+' veya '-' gelebilir + '{0}' seçeneğinin arkasından yalnızca '+' veya '-' gelebilir the value '{1}' is invalid for option '{0}' - {0}' seçeneği için '{1}' değeri geçersiz + '{0}' seçeneği için '{1}' değeri geçersiz Compilation options '{0}' and '{1}' can't both be specified at the same time. - {0}' ve '{1}' derleme seçenekleri aynı anda belirtilemez. + '{0}' ve '{1}' derleme seçenekleri aynı anda belirtilemez. @@ -525,7 +569,7 @@ Algorithm '{0}' is not supported - {0}' algoritması desteklenmiyor + '{0}' algoritması desteklenmiyor @@ -545,7 +589,7 @@ source file '{0}' specified multiple times - {0}' kaynak dosyası birden çok kez belirtildi + '{0}' kaynak dosyası birden çok kez belirtildi @@ -560,17 +604,17 @@ code page '{0}' is invalid or not installed - {0}' kod sayfası geçersiz veya yüklü değil + '{0}' kod sayfası geçersiz veya yüklü değil the file '{0}' is not a text file - {0}' dosyası bir metin dosyası değil + '{0}' dosyası bir metin dosyası değil could not find library '{0}' - {0}' kitaplığı bulunamadı + '{0}' kitaplığı bulunamadı @@ -595,7 +639,7 @@ warning number '{0}' for the option '{1}' is either not configurable or not valid - {1}' seçeneği için '{0}' uyarı numarası yapılandırılamıyor veya geçerli değil + '{1}' seçeneği için '{0}' uyarı numarası yapılandırılamıyor veya geçerli değil @@ -640,7 +684,7 @@ Type '{0}' is not defined. - {0}' türü tanımlı değil. + '{0}' türü tanımlı değil. @@ -655,12 +699,12 @@ Reference required to assembly '{0}' containing the definition for event '{1}'. Add one to your project. - {1}' olayının tanımını içeren '{0}' derlemesine başvuru gerekiyor. Projenize bir başvuru ekleyin. + '{1}' olayının tanımını içeren '{0}' derlemesine başvuru gerekiyor. Projenize bir başvuru ekleyin. Reference required to module '{0}' containing the definition for event '{1}'. Add one to your project. - {1}' olayının tanımını içeren '{0}' modülüne başvuru gerekiyor. Projenize bir başvuru ekleyin. + '{1}' olayının tanımını içeren '{0}' modülüne başvuru gerekiyor. Projenize bir başvuru ekleyin. @@ -680,7 +724,7 @@ Inheriting from '{0}' is not valid. - {0}' öğesinden devralma geçerli değil. + '{0}' öğesinden devralma geçerli değil. @@ -860,7 +904,7 @@ Too many arguments to '{0}'. - {0}' için çok fazla bağımsız değişken var. + '{0}' için çok fazla bağımsız değişken var. @@ -910,7 +954,7 @@ For loop control variable '{0}' already in use by an enclosing For loop. - {0}' For döngü denetim değişkeni zaten kapsayan bir For döngüsü tarafından kullanılıyor. + '{0}' For döngü denetim değişkeni zaten kapsayan bir For döngüsü tarafından kullanılıyor. @@ -1005,7 +1049,7 @@ Label '{0}' is already defined in the current method. - {0}' etiketi geçerli yöntemde zaten tanımlanmış. + '{0}' etiketi geçerli yöntemde zaten tanımlanmış. @@ -1115,12 +1159,12 @@ Attribute '{0}' is not valid: Incorrect argument value. - {0}' özniteliği geçerli değil: Bağımsız değişken değeri yanlış. + '{0}' özniteliği geçerli değil: Bağımsız değişken değeri yanlış. Label '{0}' is not defined. - {0}' etiketi tanımlanmadı. + '{0}' etiketi tanımlanmadı. @@ -1135,7 +1179,7 @@ First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class '{0}' of '{1}' does not have an accessible 'Sub New' that can be called with no arguments. - {1}' sınıfının temel sınıfı olan '{0}' sınıfında bağımsız değişken olmadan çağrılabilecek erişilebilir bir 'Sub New' olmadığından, bu 'Sub New' oluşturucusunun ilk deyimi bir 'MyBase.New' veya 'MyClass.New' çağrısı olmalıdır. + '{1}' sınıfının temel sınıfı olan '{0}' sınıfında bağımsız değişken olmadan çağrılabilecek erişilebilir bir 'Sub New' olmadığından, bu 'Sub New' oluşturucusunun ilk deyimi bir 'MyBase.New' veya 'MyClass.New' çağrısı olmalıdır. @@ -1320,7 +1364,7 @@ Delegate class '{0}' has no Invoke method, so an expression of this type cannot be the target of a method call. - {0}' temsilci sınıfında Invoke yöntemi yok, bu nedenle bu türdeki bir ifade bir yöntem çağrısının hedefi olamaz. + '{0}' temsilci sınıfında Invoke yöntemi yok, bu nedenle bu türdeki bir ifade bir yöntem çağrısının hedefi olamaz. @@ -1435,7 +1479,7 @@ Type '{0}' has no constructors. - {0}' türünün oluşturucusu yok. + '{0}' türünün oluşturucusu yok. @@ -1464,7 +1508,7 @@ Class '{0}' cannot inherit from itself: {1} - {0}' sınıfı kendi kendisinden devralamaz: {1} + '{0}' sınıfı kendi kendisinden devralamaz: {1} @@ -1514,7 +1558,7 @@ Parameter '{0}' of '{1}' already has a matching argument. - {0}' / '{1}' parametresinin zaten eşleşen bir bağımsız değişkeni var. + '{0}' / '{1}' parametresinin zaten eşleşen bir bağımsız değişkeni var. @@ -1524,7 +1568,7 @@ Type character '{0}' does not match declared data type '{1}'. - {0}' tür karakteri bildirilen '{1}' veri türüyle eşleşmiyor. + '{0}' tür karakteri bildirilen '{1}' veri türüyle eşleşmiyor. @@ -1534,7 +1578,7 @@ Enum '{0}' must contain at least one member. - {0}' sabit listesi en az bir üye içermelidir. + '{0}' sabit listesi en az bir üye içermelidir. @@ -1559,7 +1603,7 @@ Cannot update '{0}'; attribute '{1}' is missing. - {0}' güncelleştirilemiyor; '{1}' özniteliği eksik. + '{0}' güncelleştirilemiyor; '{1}' özniteliği eksik. @@ -1596,12 +1640,12 @@ Structure '{0}' cannot contain an instance of itself: {1} - {0}' yapısı kendi örneğini içeremez: {1} + '{0}' yapısı kendi örneğini içeremez: {1} Interface '{0}' cannot inherit from itself: {1} - {0}' arabirimi kendi kendinden devralamaz: {1} + '{0}' arabirimi kendi kendinden devralamaz: {1} @@ -1613,7 +1657,7 @@ Constructor '{0}' cannot call itself: {1} - {0}' oluşturucusu kendi kendini çağıramaz: {1} + '{0}' oluşturucusu kendi kendini çağıramaz: {1} @@ -1633,7 +1677,7 @@ Type character '{0}' cannot be used in a declaration with an explicit type. - {0}' tür karakteri açık bir türü olan bildirimde kullanılamaz. + '{0}' tür karakteri açık bir türü olan bildirimde kullanılamaz. @@ -1668,7 +1712,7 @@ Value of type '{0}' cannot be converted to '{1}'. - {0}' türündeki değer '{1}' olarak dönüştürülemez. + '{0}' türündeki değer '{1}' olarak dönüştürülemez. @@ -1678,12 +1722,12 @@ Value of type '{0}' cannot be converted to '{1}' because '{2}' is not derived from '{3}'. - {2}' '{3}' türünden türetilmediğinden, '{0}' türünün değeri '{1}' olarak dönüştürülemez. + '{2}' '{3}' türünden türetilmediğinden, '{0}' türünün değeri '{1}' olarak dönüştürülemez. Value of type '{0}' cannot be converted to '{1}' because '{2}' is not a reference type. - {2}' bir başvuru türü olmadığından '{0}' türünün değeri '{1}' olarak dönüştürülemez. + '{2}' bir başvuru türü olmadığından '{0}' türünün değeri '{1}' olarak dönüştürülemez. @@ -1708,7 +1752,7 @@ 'Default' can be applied to only one property name in a {0}. - '{0} içinde tek bir özellik adına 'Default' uygulanabilir. + {0} içinde tek bir özellik adına 'Default' uygulanabilir. @@ -1758,7 +1802,7 @@ Module '{0}' cannot be used as a type. - {0}' modülü tür olarak kullanılamaz. + '{0}' modülü tür olarak kullanılamaz. @@ -1963,7 +2007,7 @@ Operator '{0}' is not defined for types '{1}' and '{2}'. - {0}' işleci '{1}' ve '{2}' türleri için tanımlanmadı. + '{0}' işleci '{1}' ve '{2}' türleri için tanımlanmadı. @@ -1973,7 +2017,7 @@ Argument not specified for parameter '{0}' of '{1}'. - {0}' / '{1}' parametresi için bağımsız değişken belirtilmemiş. + '{0}' / '{1}' parametresi için bağımsız değişken belirtilmemiş. @@ -2043,7 +2087,7 @@ Operator '{0}' is not defined for type '{1}'. - {0}' işleci '{1}' türü için tanımlı değil. + '{0}' işleci '{1}' türü için tanımlı değil. @@ -2073,7 +2117,7 @@ Constant '{0}' cannot depend on its own value. - {0}' sabiti kendi değerine bağımlı olamaz. + '{0}' sabiti kendi değerine bağımlı olamaz. @@ -2138,7 +2182,7 @@ Argument matching parameter '{0}' narrows from '{1}' to '{2}'. - {0}' parametresiyle eşleşen bağımsız değişken '{1}' türünden '{2}' türüne daralıyor. + '{0}' parametresiyle eşleşen bağımsız değişken '{1}' türünden '{2}' türüne daralıyor. @@ -2160,12 +2204,12 @@ Property '{0}' is 'WriteOnly'. - {0}' özelliği 'WriteOnly'. + '{0}' özelliği 'WriteOnly'. Property '{0}' is 'ReadOnly'. - {0}' özelliği 'ReadOnly'. + '{0}' özelliği 'ReadOnly'. @@ -2210,12 +2254,12 @@ Attribute '{0}' cannot be applied to an assembly. - {0}' özniteliği bir derlemeye uygulanamaz. + '{0}' özniteliği bir derlemeye uygulanamaz. Attribute '{0}' cannot be applied to a module. - {0}' özniteliği bir modüle uygulanamaz. + '{0}' özniteliği bir modüle uygulanamaz. @@ -2225,7 +2269,7 @@ Default member of '{0}' is not a property. - {0}' varsayılan üyesi bir özellik değil. + '{0}' varsayılan üyesi bir özellik değil. @@ -2275,12 +2319,12 @@ Alias '{0}' is already declared. - {0}' diğer adı zaten bildirildi. + '{0}' diğer adı zaten bildirildi. XML namespace prefix '{0}' is already declared. - {0}' XML ad alanı ön eki zaten bildirildi. + '{0}' XML ad alanı ön eki zaten bildirildi. @@ -2345,7 +2389,7 @@ Event '{0}' cannot be found. - {0}' olayı bulunamadı. + '{0}' olayı bulunamadı. @@ -2385,7 +2429,7 @@ Class '{0}' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): {1}. - {0}' sınıfı 'MustInherit' olarak bildirilmeli veya devralınmış şu 'MustOverride' üyelerini geçersiz kılmalıdır: {1}. + '{0}' sınıfı 'MustInherit' olarak bildirilmeli veya devralınmış şu 'MustOverride' üyelerini geçersiz kılmalıdır: {1}. @@ -2410,7 +2454,7 @@ Variable '{0}' hides a variable in an enclosing block. - {0}' değişkeni kapsayan bir blokta bir değişkeni gizliyor. + '{0}' değişkeni kapsayan bir blokta bir değişkeni gizliyor. @@ -2550,12 +2594,12 @@ Property '{0}' is of an unsupported type. - {0}' özelliği desteklenmeyen türde. + '{0}' özelliği desteklenmeyen türde. Attribute '{0}' cannot be applied to a method with optional parameters. - {0}' özniteliği isteğe bağlı parametreleri olan bir yönteme uygulanamaz. + '{0}' özniteliği isteğe bağlı parametreleri olan bir yönteme uygulanamaz. @@ -2585,12 +2629,12 @@ Reference required to assembly '{0}' containing the type '{1}'. Add one to your project. - {1}' türünü içeren '{0}' derlemesine başvuru gerekiyor. Projenize bir başvuru ekleyin. + '{1}' türünü içeren '{0}' derlemesine başvuru gerekiyor. Projenize bir başvuru ekleyin. Reference required to module '{0}' containing the type '{1}'. Add one to your project. - {1}' türünü içeren '{0}' modülüne başvuru gerekiyor. Projenize bir başvuru ekleyin. + '{1}' türünü içeren '{0}' modülüne başvuru gerekiyor. Projenize bir başvuru ekleyin. @@ -2600,7 +2644,7 @@ Field '{0}' is of an unsupported type. - {0}' alanı desteklenmeyen türde. + '{0}' alanı desteklenmeyen türde. @@ -2615,7 +2659,7 @@ Property or field '{0}' does not have a valid attribute type. - {0}' özelliği veya alanının öznitelik türü geçerli değil. + '{0}' özelliği veya alanının öznitelik türü geçerli değil. @@ -2625,22 +2669,22 @@ Field or property '{0}' is not found. - {0}' alanı veya özelliği bulunamadı. + '{0}' alanı veya özelliği bulunamadı. Attribute '{0}' cannot be applied to '{1}' because the attribute is not valid on this declaration type. - {0}' özniteliği bu bildirim türünde geçerli olmadığından '{1}' öğesine uygulanamaz. + '{0}' özniteliği bu bildirim türünde geçerli olmadığından '{1}' öğesine uygulanamaz. Attribute '{0}' cannot be applied to '{1}' of '{2}' because the attribute is not valid on this declaration type. - {0}' özniteliği bu bildirim türünde geçerli olmadığından '{2}' '{1}' öğesine uygulanamaz. + '{0}' özniteliği bu bildirim türünde geçerli olmadığından '{2}' '{1}' öğesine uygulanamaz. Class '{0}' cannot reference its nested type '{1}' in Inherits clause. - {0}' sınıfı Inherits yan tümcesinde kendi iç içe '{1}' türüne başvuramaz. + '{0}' sınıfı Inherits yan tümcesinde kendi iç içe '{1}' türüne başvuramaz. @@ -2662,12 +2706,12 @@ Attribute '{0}' cannot be applied multiple times. - {0}' özniteliği birden çok kez uygulanamaz. + '{0}' özniteliği birden çok kez uygulanamaz. Attribute '{0}' in '{1}' cannot be applied multiple times. - {1}' içinde '{0}' özniteliği birden çok kez uygulanamaz. + '{1}' içinde '{0}' özniteliği birden çok kez uygulanamaz. @@ -2757,7 +2801,7 @@ Default property access is ambiguous between the inherited interface members '{0}' of interface '{1}' and '{2}' of interface '{3}'. - {1}' arabiriminin devralınan '{0}' arabirim üyeleriyle '{3}' arabiriminin '{2}' üyeleri arasında varsayılan özellik erişimi belirsiz. + '{1}' arabiriminin devralınan '{0}' arabirim üyeleriyle '{3}' arabiriminin '{2}' üyeleri arasında varsayılan özellik erişimi belirsiz. @@ -2772,7 +2816,7 @@ Structure '{0}' cannot be indexed because it has no default property. - {0}' yapısının varsayılan özelliği olmadığından yapı dizine alınamıyor. + '{0}' yapısının varsayılan özelliği olmadığından yapı dizine alınamıyor. @@ -2807,7 +2851,7 @@ Variable '{0}' is already declared as a parameter of this or an enclosing lambda expression. - {0}' değişkeni zaten bunun veya kapsayan bir lambda ifadesinin parametresi olarak bildirilmiş. + '{0}' değişkeni zaten bunun veya kapsayan bir lambda ifadesinin parametresi olarak bildirilmiş. @@ -2817,7 +2861,7 @@ No accessible 'Main' method with an appropriate signature was found in '{0}'. - {0}' içinde uygun imzaya sahip, erişilebilir bir 'Main' yöntemi bulunamadı. + '{0}' içinde uygun imzaya sahip, erişilebilir bir 'Main' yöntemi bulunamadı. @@ -2827,7 +2871,7 @@ Value '{0}' cannot be converted to '{1}'. - {0}' değeri, '{1}' olarak dönüştürülemez. + '{0}' değeri, '{1}' olarak dönüştürülemez. @@ -2932,12 +2976,12 @@ None of the accessible 'Main' methods with the appropriate signatures found in '{0}' can be the startup method since they are all either generic or nested in generic types. - {0}' içinde bulunan ve uygun imzalara sahip olan erişilebilir 'Main' yöntemlerinin hiçbiri başlangıç yöntemi olamaz çünkü bunlar geneldir veya genel türlerle iç içedir. + '{0}' içinde bulunan ve uygun imzalara sahip olan erişilebilir 'Main' yöntemlerinin hiçbiri başlangıç yöntemi olamaz çünkü bunlar geneldir veya genel türlerle iç içedir. Error in project-level import '{0}' at '{1}' : {2} - {0}' proje düzeyi içeri aktarmada '{1}' konumunda hata: {2} + '{0}' proje düzeyi içeri aktarmada '{1}' konumunda hata: {2} @@ -3072,27 +3116,27 @@ Type '{0}' is not supported because it either directly or indirectly inherits from itself. - {0}' türü, doğrudan veya dolaylı olarak kendi kendisinden devraldığından desteklenmiyor. + '{0}' türü, doğrudan veya dolaylı olarak kendi kendisinden devraldığından desteklenmiyor. Class '{0}' must declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete. - {2}' temel sınıfındaki '{1}' kullanılmıyor biçiminde işaretlendiğinden '{0}' sınıfı bir 'Sub New' bildirmelidir. + '{2}' temel sınıfındaki '{1}' kullanılmıyor biçiminde işaretlendiğinden '{0}' sınıfı bir 'Sub New' bildirmelidir. Class '{0}' must declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete: '{3}'. - {2}' temel sınıfındaki '{1}' kullanılmıyor biçiminde işaretlendiğinden '{0}' sınıfı bir 'Sub New' bildirmelidir: '{3}'. + '{2}' temel sınıfındaki '{1}' kullanılmıyor biçiminde işaretlendiğinden '{0}' sınıfı bir 'Sub New' bildirmelidir: '{3}'. First statement of this 'Sub New' must be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete. - {2}' öğesinin '{1}' temel sınıfında '{0}' artık kullanılmıyor olarak işaretlendiğinden, bu 'Sub New' yönteminin ilk deyimi açık bir 'MyBase.New' veya 'MyClass.New' çağrısı olmalıdır. + '{2}' öğesinin '{1}' temel sınıfında '{0}' artık kullanılmıyor olarak işaretlendiğinden, bu 'Sub New' yönteminin ilk deyimi açık bir 'MyBase.New' veya 'MyClass.New' çağrısı olmalıdır. First statement of this 'Sub New' must be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete: '{3}'. - {2}' öğesinin '{1}' temel sınıfında '{0}' artık kullanılmıyor olarak işaretlendiğinden, bu 'Sub New' yönteminin ilk deyimi açık bir 'MyBase.New' veya 'MyClass.New' çağrısı olmalıdır: '{3}'. + '{2}' öğesinin '{1}' temel sınıfında '{0}' artık kullanılmıyor olarak işaretlendiğinden, bu 'Sub New' yönteminin ilk deyimi açık bir 'MyBase.New' veya 'MyClass.New' çağrısı olmalıdır: '{3}'. @@ -3107,7 +3151,7 @@ Specified access '{0}' for '{1}' does not match the access '{2}' specified on one of its other partial types. - {1}' için belirtilen '{0}' erişimi, diğer kısmi türlerinden birinin üzerinde belirtilen '{2}' erişimiyle eşleşmiyor. + '{1}' için belirtilen '{0}' erişimi, diğer kısmi türlerinden birinin üzerinde belirtilen '{2}' erişimiyle eşleşmiyor. @@ -3122,12 +3166,12 @@ Base class '{0}' specified for class '{1}' cannot be different from the base class '{2}' of one of its other partial types. - {1}' sınıfı için belirtilen '{0}' temel sınıfı, diğer kısmi türlerinden birinin '{2}' temel sınıfından farklı olamaz. + '{1}' sınıfı için belirtilen '{0}' temel sınıfı, diğer kısmi türlerinden birinin '{2}' temel sınıfından farklı olamaz. Type parameter name '{0}' does not match the name '{1}' of the corresponding type parameter defined on one of the other partial types of '{2}'. - {0}' tür parametre adı, '{2}' öğesinin diğer kısmi türlerinden birinde tanımlanan ilgili tür parametresinin '{1}' adıyla eşleşmiyor. + '{0}' tür parametre adı, '{2}' öğesinin diğer kısmi türlerinden birinde tanımlanan ilgili tür parametresinin '{1}' adıyla eşleşmiyor. @@ -3147,7 +3191,7 @@ Member '{0}' that matches this signature cannot be overridden because the class '{1}' contains multiple members with this same name and signature: {2} - {1}' sınıfı aynı ada ve imzaya sahip birden çok üye içerdiğinden, bu imzayla eşleşen '{0}' üyesi geçersiz kılınamıyor: {2} + '{1}' sınıfı aynı ada ve imzaya sahip birden çok üye içerdiğinden, bu imzayla eşleşen '{0}' üyesi geçersiz kılınamıyor: {2} @@ -3161,7 +3205,7 @@ Member '{0}.{1}' that matches this signature cannot be implemented because the interface '{2}' contains multiple members with this same name and signature: '{3}' '{4}' - {2}' arabirimi aynı ada ve imzaya sahip birden çok üye içerdiğinden, bu imzayla eşleşen '{0}.{1}' üyesi uygulanamıyor: + '{2}' arabirimi aynı ada ve imzaya sahip birden çok üye içerdiğinden, bu imzayla eşleşen '{0}.{1}' üyesi uygulanamıyor: '{3}' '{4}' @@ -3188,7 +3232,7 @@ No accessible method '{0}' has a signature compatible with delegate '{1}':{2} - {1}':{2} temsilcisiyle uyumlu imzaya sahip bir erişilebilir '{0}' yöntemi yok + '{1}':{2} temsilcisiyle uyumlu imzaya sahip bir erişilebilir '{0}' yöntemi yok @@ -3198,7 +3242,7 @@ Range variable '{0}' hides a variable in an enclosing block or a range variable previously defined in the query expression. - {0}' aralık değişkeni kapsayan bir blok içinde bir değişkeni gizliyor veya daha önce sorgu ifadesinde aralık değişkeni tanımlandı. + '{0}' aralık değişkeni kapsayan bir blok içinde bir değişkeni gizliyor veya daha önce sorgu ifadesinde aralık değişkeni tanımlandı. @@ -3208,7 +3252,7 @@ Type of '{0}' cannot be inferred from an expression containing '{0}'. - {0}' türü '{0}' içeren bir ifadeden çıkarsanamaz. + '{0}' türü '{0}' içeren bir ifadeden çıkarsanamaz. @@ -3248,7 +3292,7 @@ Multiple initializations of '{0}'. Fields and properties can be initialized only once in an object initializer expression. - {0}' birden çok kez başlatıldı. Nesne başlatıcısı ifadesinde alanlar ve özellikler tek bir kez başlatılabilir. + '{0}' birden çok kez başlatıldı. Nesne başlatıcısı ifadesinde alanlar ve özellikler tek bir kez başlatılabilir. @@ -3258,7 +3302,7 @@ Member '{0}' cannot be initialized in an object initializer expression because it is shared. - {0}' üyesi paylaşıldığından bu üye nesne başlatıcısı ifadesinde başlatılamıyor. + '{0}' üyesi paylaşıldığından bu üye nesne başlatıcısı ifadesinde başlatılamıyor. @@ -3288,7 +3332,7 @@ Unable to load module file '{0}': {1} - {0}' modül dosyası yüklenemedi: {1} + '{0}' modül dosyası yüklenemedi: {1} @@ -3308,52 +3352,52 @@ Interface '{0}' can be implemented only once by this type. - {0}' arabirimi bu türle tek bir kez uygulanabilir. + '{0}' arabirimi bu türle tek bir kez uygulanabilir. Interface '{0}' can be implemented only once by this type, but already appears with different tuple element names, as '{1}'. - {0}' arabirimi bu tür tarafından yalnızca bir kez uygulanabilir, ancak '{1}' olarak farklı demet öğesi adları ile zaten görünüyor. + '{0}' arabirimi bu tür tarafından yalnızca bir kez uygulanabilir, ancak '{1}' olarak farklı demet öğesi adları ile zaten görünüyor. Interface '{0}' can be implemented only once by this type, but already appears with different tuple element names, as '{1}' (via '{2}'). - {0}' arabirimi bu tür tarafından yalnızca bir kez uygulanabilir, ancak '{1}' olarak ('{2}' aracılığıyla) farklı demet öğesi adları ile zaten görünüyor. + '{0}' arabirimi bu tür tarafından yalnızca bir kez uygulanabilir, ancak '{1}' olarak ('{2}' aracılığıyla) farklı demet öğesi adları ile zaten görünüyor. Interface '{0}' (via '{1}') can be implemented only once by this type, but already appears with different tuple element names, as '{2}'. - {0}' arabirimi ('{1}' aracılığıyla) bu tür tarafından yalnızca bir kez uygulanabilir, ancak '{2}' olarak farklı demet öğesi adları ile zaten görünüyor. + '{0}' arabirimi ('{1}' aracılığıyla) bu tür tarafından yalnızca bir kez uygulanabilir, ancak '{2}' olarak farklı demet öğesi adları ile zaten görünüyor. Interface '{0}' (via '{1}') can be implemented only once by this type, but already appears with different tuple element names, as '{2}' (via '{3}'). - {0}' arabirimi ('{1}' aracılığıyla) bu tür tarafından yalnızca bir kez uygulanabilir, ancak '{2}' olarak ('{3}' aracılığıyla) farklı demet öğesi adları ile zaten görünüyor. + '{0}' arabirimi ('{1}' aracılığıyla) bu tür tarafından yalnızca bir kez uygulanabilir, ancak '{2}' olarak ('{3}' aracılığıyla) farklı demet öğesi adları ile zaten görünüyor. Interface '{0}' can be inherited only once by this interface, but already appears with different tuple element names, as '{1}'. - {0}' arabirimi bu arabirim tarafından yalnızca bir kez devralınabilir, ancak '{1}' olarak farklı demet öğesi adları ile zaten görünüyor. + '{0}' arabirimi bu arabirim tarafından yalnızca bir kez devralınabilir, ancak '{1}' olarak farklı demet öğesi adları ile zaten görünüyor. Interface '{0}' can be inherited only once by this interface, but already appears with different tuple element names, as '{1}' (via '{2}'). - {0}' arabirimi bu arabirim tarafından yalnızca bir kez devralınabilir, ancak '{1}' olarak ('{2}' aracılığıyla) farklı demet öğesi adları ile zaten görünüyor. + '{0}' arabirimi bu arabirim tarafından yalnızca bir kez devralınabilir, ancak '{1}' olarak ('{2}' aracılığıyla) farklı demet öğesi adları ile zaten görünüyor. Interface '{0}' (via '{1}') can be inherited only once by this interface, but already appears with different tuple element names, as '{2}'. - {0}' arabirimi ('{1}' aracılığıyla) bu arabirim tarafından yalnızca bir kez devralınabilir, ancak '{2}' olarak farklı demet öğesi adları ile zaten görünüyor. + '{0}' arabirimi ('{1}' aracılığıyla) bu arabirim tarafından yalnızca bir kez devralınabilir, ancak '{2}' olarak farklı demet öğesi adları ile zaten görünüyor. Interface '{0}' (via '{1}') can be inherited only once by this interface, but already appears with different tuple element names, as '{2}' (via '{3}'). - {0}' arabirimi ('{1}' aracılığıyla) bu arabirim tarafından yalnızca bir kez devralınabilir, ancak '{2}' olarak ('{3}' aracılığıyla) farklı demet öğesi adları ile zaten görünüyor. + '{0}' arabirimi ('{1}' aracılığıyla) bu arabirim tarafından yalnızca bir kez devralınabilir, ancak '{2}' olarak ('{3}' aracılığıyla) farklı demet öğesi adları ile zaten görünüyor. Interface '{0}' is not implemented by this class. - {0}' arabirimi bu sınıf tarafından uygulanamaz. + '{0}' arabirimi bu sınıf tarafından uygulanamaz. @@ -3393,7 +3437,7 @@ Namespace or type '{0}' has already been imported. - {0}' ad alanı veya türü zaten içeri aktarıldı. + '{0}' ad alanı veya türü zaten içeri aktarıldı. @@ -3433,7 +3477,7 @@ Security attribute '{0}' has an invalid SecurityAction value '{1}'. - {0}' güvenlik özniteliğinin '{1}' SecurityAction değeri geçersiz. + '{0}' güvenlik özniteliğinin '{1}' SecurityAction değeri geçersiz. @@ -3523,7 +3567,7 @@ Operator '{0}' is not defined for types '{1}' and '{2}'. Use 'Is' operator to compare two reference types. - {0}' işleci '{1}' ve '{2}' türleri için tanımlı değil. İki başvuru türünü karşılaştırmak için 'Is' işlecini kullanın. + '{0}' işleci '{1}' ve '{2}' türleri için tanımlı değil. İki başvuru türünü karşılaştırmak için 'Is' işlecini kullanın. @@ -3568,7 +3612,7 @@ Import of type '{0}' from assembly or module '{1}' failed. - {1}' derleme veya modülünden '{0}' türünü içeri aktarma işlemi başarısız oldu. + '{1}' derleme veya modülünden '{0}' türünü içeri aktarma işlemi başarısız oldu. @@ -3583,12 +3627,12 @@ Implementing class '{0}' for interface '{1}' cannot be found. - {1}' arabirimi için '{0}' uygulama sınıfı bulunamadı. + '{1}' arabirimi için '{0}' uygulama sınıfı bulunamadı. Type '{0}' cannot be used as an implementing class. - {0}' türü uygulayan sınıfı olarak kullanılamaz. + '{0}' türü uygulayan sınıfı olarak kullanılamaz. @@ -3603,7 +3647,7 @@ Member '{0}' cannot be found in class '{1}'. This condition is usually the result of a mismatched 'Microsoft.VisualBasic.dll'. - {0}' üyesi '{1}' sınıfı içinde bulunamadı. Bu durum genellikle 'Microsoft.VisualBasic.dll' uyuşmazlığından kaynaklanır. + '{0}' üyesi '{1}' sınıfı içinde bulunamadı. Bu durum genellikle 'Microsoft.VisualBasic.dll' uyuşmazlığından kaynaklanır. @@ -3613,7 +3657,7 @@ Access modifier '{0}' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level. - {0}' erişim değiştiricisi geçerli değil. 'Get' ve 'Set' erişim değiştiricisi, özellik erişim düzeyinden daha kısıtlayıcı olmalıdır. + '{0}' erişim değiştiricisi geçerli değil. 'Get' ve 'Set' erişim değiştiricisi, özellik erişim düzeyinden daha kısıtlayıcı olmalıdır. @@ -3658,7 +3702,7 @@ Implementing class '{0}' for interface '{1}' is not accessible in this context because it is '{2}'. - {2}' olduğundan bu bağlamda '{1}' arabirimi için '{0}' uygulayan sınıfı erişilebilir değil. + '{2}' olduğundan bu bağlamda '{1}' arabirimi için '{0}' uygulayan sınıfı erişilebilir değil. @@ -3808,7 +3852,7 @@ Method '{0}' does not have a signature compatible with delegate '{1}'. - {0}' yönteminin '{1}' temsilcisiyle uyumlu bir imzası yok. + '{0}' yönteminin '{1}' temsilcisiyle uyumlu bir imzası yok. @@ -3818,7 +3862,7 @@ XML namespace prefix '{0}' is not defined. - {0}' XML ad alanı ön eki tanımlanmadı. + '{0}' XML ad alanı ön eki tanımlanmadı. @@ -3838,7 +3882,7 @@ XML namespace prefix '{0}' is reserved for use by XML and the namespace URI cannot be changed. - {0}' XML ad alanı ön eki XML'nin kullanımına ayrılmıştır ve ad alanı URI'si değiştirilemez. + '{0}' XML ad alanı ön eki XML'nin kullanımına ayrılmıştır ve ad alanı URI'si değiştirilemez. @@ -3863,7 +3907,7 @@ XML attribute '{0}' must appear before XML attribute '{1}'. - {0}' XML özniteliği, '{1}' XML özniteliğinden önce gelmelidir. + '{0}' XML özniteliği, '{1}' XML özniteliğinden önce gelmelidir. @@ -3943,7 +3987,7 @@ XML processing instruction name '{0}' is not valid. - {0}' XML işleme yönergesi adı geçerli değil. + '{0}' XML işleme yönergesi adı geçerli değil. @@ -3983,7 +4027,7 @@ Prefix '{0}' cannot be bound to namespace name reserved for '{1}'. - {0}' ön eki '{1}' için ayrılmış ad alanı adına bağımlı olamaz. + '{0}' ön eki '{1}' için ayrılmış ad alanı adına bağımlı olamaz. @@ -4013,12 +4057,12 @@ Unable to open Win32 manifest file '{0}' : {1} - {0}' Win32 bildirim dosyası açılamadı: {1} + '{0}' Win32 bildirim dosyası açılamadı: {1} Cannot convert '{0}' to '{1}'. You can use the 'Value' property to get the string value of the first element of '{2}'. - {0}' - '{1}' dönüştürmesi yapılamıyor. İlk '{2}' öğesinin dize değerini almak için 'Value' özelliğini kullanabilirsiniz. + '{0}' - '{1}' dönüştürmesi yapılamıyor. İlk '{2}' öğesinin dize değerini almak için 'Value' özelliğini kullanabilirsiniz. @@ -4028,12 +4072,12 @@ Value of type '{0}' cannot be converted to '{1}'. You can use the 'Value' property to get the string value of the first element of '{2}'. - {0}' türündeki değer '{1}' olarak dönüştürülemez. İlk '{2}' öğesinin dize değerini almak için 'Value' özelliğini kullanabilirsiniz. + '{0}' türündeki değer '{1}' olarak dönüştürülemez. İlk '{2}' öğesinin dize değerini almak için 'Value' özelliğini kullanabilirsiniz. Operator '{0}' is not defined for types '{1}' and '{2}'. You can use the 'Value' property to get the string value of the first element of '{3}'. - {0}' işleci '{1}' ve '{2}' türleri için tanımlanmadı. İlk '{3}' öğesinin dize değerini almak için 'Value' özelliğini kullanabilirsiniz. + '{0}' işleci '{1}' ve '{2}' türleri için tanımlanmadı. İlk '{3}' öğesinin dize değerini almak için 'Value' özelliğini kullanabilirsiniz. @@ -4043,7 +4087,7 @@ The value '{0}' is not a valid subsystem version. The version must be 6.02 or greater for ARM or AppContainerExe, and 4.00 or greater otherwise. - {0}' değeri geçerli bir alt sistem sürümü değil. Sürüm, ARM veya AppContainerExe için 6.02 veya daha büyük, bunun dışındaki durumlarda 4.00 veya daha büyük olmalıdır. + '{0}' değeri geçerli bir alt sistem sürümü değil. Sürüm, ARM veya AppContainerExe için 6.02 veya daha büyük, bunun dışındaki durumlarda 4.00 veya daha büyük olmalıdır. @@ -4073,7 +4117,7 @@ Expression of type '{0}' cannot be converted to 'Object' or 'ValueType'. - {0}' türündeki ifade 'Object' veya 'ValueType' olarak değiştirilemez. + '{0}' türündeki ifade 'Object' veya 'ValueType' olarak değiştirilemez. @@ -4093,7 +4137,7 @@ Class '{0}' has no accessible 'Sub New' and cannot be inherited. - {0}' sınıfında erişilebilir 'Sub New' yok ve devralınamıyor. + '{0}' sınıfında erişilebilir 'Sub New' yok ve devralınamıyor. @@ -4108,7 +4152,7 @@ Imports alias '{0}' conflicts with '{1}' declared in the root namespace. - {0}' Imports diğer adı kök ad alanında bildirilen '{1}' ile çakışıyor. + '{0}' Imports diğer adı kök ad alanında bildirilen '{1}' ile çakışıyor. @@ -4118,7 +4162,7 @@ Event '{0}' cannot implement event '{2}.{1}' because its delegate type does not match the delegate type of another event implemented by '{0}'. - {0}' olayı, temsilci türü '{0}' tarafından uygulanan başka bir olayın temsilci türüyle eşleşmediğinden '{2}.{1}' olayını uygulayamıyor. + '{0}' olayı, temsilci türü '{0}' tarafından uygulanan başka bir olayın temsilci türüyle eşleşmediğinden '{2}.{1}' olayını uygulayamıyor. @@ -4143,7 +4187,7 @@ '{0}', implicitly declared for {1} '{2}', cannot shadow a 'MustOverride' method in the base {3} '{4}'. - '{1} '{2}' için örtük olarak bildirilen '{0}', {3} '{4}' temelinde 'MustOverride' yöntemini gölgeleyemez. + {1} '{2}' için örtük olarak bildirilen '{0}', {3} '{4}' temelinde 'MustOverride' yöntemini gölgeleyemez. @@ -4183,7 +4227,7 @@ Type '{0}' in assembly '{1}' has been forwarded to assembly '{2}'. Either a reference to '{2}' is missing from your project or the type '{0}' is missing from assembly '{2}'. - {1}' derlemesinin içindeki '{0}' türü '{2}' derlemesine iletildi. Projenizde bir '{2}' başvurusu eksik veya '{2}' derlemesinde '{0}' türü eksik. + '{1}' derlemesinin içindeki '{0}' türü '{2}' derlemesine iletildi. Projenizde bir '{2}' başvurusu eksik veya '{2}' derlemesinde '{0}' türü eksik. @@ -4208,12 +4252,12 @@ '{0}' is ambiguous because multiple kinds of members with this name exist in {1} '{2}'. - '{1} '{2}' içinde bu ada sahip birden çok türde üye olduğundan '{0}' belirsiz. + {1} '{2}' içinde bu ada sahip birden çok türde üye olduğundan '{0}' belirsiz. Expression of type '{0}' can never be of type '{1}'. - {0}' türünün ifadesi hiçbir zaman '{1}' türünde olamaz. + '{0}' türünün ifadesi hiçbir zaman '{1}' türünde olamaz. @@ -4233,7 +4277,7 @@ Method '{0}' cannot implement partial method '{1}' because '{2}' already implements it. Only one method can implement a partial method. - {0}' yöntemi '{1}' kısmi yöntemini uygulayamaz çünkü bu '{2}' tarafından zaten uygulanıyor. Yalnızca bir yöntem kısmi bir yöntem uygulayabilir. + '{0}' yöntemi '{1}' kısmi yöntemini uygulayamaz çünkü bu '{2}' tarafından zaten uygulanıyor. Yalnızca bir yöntem kısmi bir yöntem uygulayabilir. @@ -4248,12 +4292,12 @@ Method '{0}' does not have the same generic constraints as the partial method '{1}'. - {0}' yöntemi, '{1}' kısmi yöntemiyle aynı genel kısıtlamalara sahip değil. + '{0}' yöntemi, '{1}' kısmi yöntemiyle aynı genel kısıtlamalara sahip değil. Partial method '{0}' cannot use the 'Implements' keyword. - {0}' kısmi yöntemi 'Implements' anahtar sözcüğünü kullanamaz. + '{0}' kısmi yöntemi 'Implements' anahtar sözcüğünü kullanamaz. @@ -4263,17 +4307,17 @@ Method '{0}' must be declared 'Private' in order to implement partial method '{1}'. - {1}' kısmi yönteminin uygulanması için '{0}' yönteminin 'Private' olarak bildirilmesi gerekir. + '{1}' kısmi yönteminin uygulanması için '{0}' yönteminin 'Private' olarak bildirilmesi gerekir. Parameter name '{0}' does not match the name of the corresponding parameter, '{1}', defined on the partial method declaration '{2}'. - {0}' parametre adı, '{2}' kısmi yöntem bildiriminde tanımlanan karşılık gelen '{1}' parametresinin adıyla eşleşmiyor. + '{0}' parametre adı, '{2}' kısmi yöntem bildiriminde tanımlanan karşılık gelen '{1}' parametresinin adıyla eşleşmiyor. Name of type parameter '{0}' does not match '{1}', the corresponding type parameter defined on the partial method declaration '{2}'. - {0}' parametresinin adı, '{2}' kısmi yöntem bildiriminde tanımlanmış, buna karşılık gelen '{1}' tür parametresiyle eşleşmiyor. + '{0}' parametresinin adı, '{2}' kısmi yöntem bildiriminde tanımlanmış, buna karşılık gelen '{1}' tür parametresiyle eşleşmiyor. @@ -4288,7 +4332,7 @@ Resource name '{0}' cannot be used more than once. - {0}' kaynak adı birden çok kez kullanılamaz. + '{0}' kaynak adı birden çok kez kullanılamaz. @@ -4313,7 +4357,7 @@ Unable to open resource file '{0}': {1} - {0}' kaynak dosyası açılamadı: {1} + '{0}' kaynak dosyası açılamadı: {1} @@ -4328,7 +4372,7 @@ Project '{0}' makes an indirect reference to assembly '{1}', which contains '{2}'. Add a file reference to '{3}' to your project. - {0}' projesi '{2}' içeren '{1}' derlemesine dolaylı başvuruda bulunuyor. Projenizde '{3}' için bir dosya başvurusu ekleyin. + '{0}' projesi '{2}' içeren '{1}' derlemesine dolaylı başvuruda bulunuyor. Projenizde '{3}' için bir dosya başvurusu ekleyin. @@ -4383,12 +4427,12 @@ Friend assembly reference '{0}' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. - {0}' friend derleme başvurusu geçersiz. InternalsVisibleTo bildirimlerinde sürüm, kültür, ortak anahtar simgesi veya işlemci mimarisi belirtilemez. + '{0}' friend derleme başvurusu geçersiz. InternalsVisibleTo bildirimlerinde sürüm, kültür, ortak anahtar simgesi veya işlemci mimarisi belirtilemez. Friend assembly reference '{0}' is invalid. Strong-name signed assemblies must specify a public key in their InternalsVisibleTo declarations. - {0}' friend derleme başvurusu geçersiz. Kesin ad imzalı derlemelerin kendi InternalsVisibleTo bildirmelerinde bir ortak anahtar belirtmesi gerekir. + '{0}' friend derleme başvurusu geçersiz. Kesin ad imzalı derlemelerin kendi InternalsVisibleTo bildirmelerinde bir ortak anahtar belirtmesi gerekir. @@ -4403,7 +4447,7 @@ Local variable '{0}' cannot be referred to before it is declared. - {0}' yerel değişkeni bildirilmeden önce çıkarsanamaz. + '{0}' yerel değişkeni bildirilmeden önce çıkarsanamaz. @@ -4428,7 +4472,7 @@ Delegate '{0}' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. - {0}' temsilcisi oluşturucusuna bağımsız değişken olarak yalnızca tek bir 'AddressOf' ifadesi veya lambda ifadesi gerektirir. + '{0}' temsilcisi oluşturucusuna bağımsız değişken olarak yalnızca tek bir 'AddressOf' ifadesi veya lambda ifadesi gerektirir. @@ -4478,7 +4522,7 @@ Parameter '{0}' in '{1}' already has a matching omitted argument. - {1}' içindeki '{0}' parametresiyle eşleşen atlanmış bir bağımsız değişken zaten var. + '{1}' içindeki '{0}' parametresiyle eşleşen atlanmış bir bağımsız değişken zaten var. @@ -4523,7 +4567,7 @@ Class '{0}' must declare a 'Sub New' because its base class '{1}' has more than one accessible 'Sub New' that can be called with no arguments. - {0}' sınıfı, temel sınıfı olan '{1}' sınıfı bağımsız değişken olmadan çağrılabilen birden çok erişilebilir 'Sub New' içerdiğinden bir 'Sub New' bildirmelidir. + '{0}' sınıfı, temel sınıfı olan '{1}' sınıfı bağımsız değişken olmadan çağrılabilen birden çok erişilebilir 'Sub New' içerdiğinden bir 'Sub New' bildirmelidir. @@ -4533,7 +4577,7 @@ First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class '{0}' of '{1}' has more than one accessible 'Sub New' that can be called with no arguments. - {1}' sınıfının temel sınıfı olan '{0}' sınıfında bağımsız değişken olmadan çağrılabilecek erişilebilir birden fazla 'Sub New' olduğundan, bu 'Sub New' oluşturucusunun ilk deyimi bir 'MyBase.New' veya 'MyClass.New' çağrısı olmalıdır. + '{1}' sınıfının temel sınıfı olan '{0}' sınıfında bağımsız değişken olmadan çağrılabilecek erişilebilir birden fazla 'Sub New' olduğundan, bu 'Sub New' oluşturucusunun ilk deyimi bir 'MyBase.New' veya 'MyClass.New' çağrısı olmalıdır. @@ -4543,7 +4587,7 @@ The '{0}' keyword is used to overload inherited members; do not use the '{0}' keyword when overloading 'Sub New'. - {0}' anahtar sözcüğü devralınan üyeleri aşırı yüklemek için kullanılır; 'Sub New' öğesinin aşırı yüklemesinde '{0}' anahtar sözcüğünü kullanmayın. + '{0}' anahtar sözcüğü devralınan üyeleri aşırı yüklemek için kullanılır; 'Sub New' öğesinin aşırı yüklemesinde '{0}' anahtar sözcüğünü kullanmayın. @@ -4553,17 +4597,17 @@ Too few type arguments to '{0}'. - {0}' için çok az tür bağımsız değişkeni var. + '{0}' için çok az tür bağımsız değişkeni var. Too many type arguments to '{0}'. - {0}' için çok fazla tür bağımsız değişkeni var. + '{0}' için çok fazla tür bağımsız değişkeni var. Type argument '{0}' does not inherit from or implement the constraint type '{1}'. - {0}' tür bağımsız değişkeni '{1}' kısıtlama türünden devralamaz veya bu türü uygulayamaz. + '{0}' tür bağımsız değişkeni '{1}' kısıtlama türünden devralamaz veya bu türü uygulayamaz. @@ -4578,12 +4622,12 @@ Type parameter '{0}' can only have one constraint that is a class. - {0}' tür parametresinde sınıf olan tek bir kısıtlama olabilir. + '{0}' tür parametresinde sınıf olan tek bir kısıtlama olabilir. Type constraint '{0}' must be either a class, interface or type parameter. - {0}' tür kısıtlaması bir sınıf, arabirim veya tür parametresi olmalıdır. + '{0}' tür kısıtlaması bir sınıf, arabirim veya tür parametresi olmalıdır. @@ -4593,7 +4637,7 @@ Type parameter '{0}' for '{1}' cannot be inferred. - {1}' için '{0}' tür parametresi çıkarsanamıyor. + '{1}' için '{0}' tür parametresi çıkarsanamıyor. @@ -4668,7 +4712,7 @@ Cannot implement interface '{0}' because its implementation could conflict with the implementation of another implemented interface '{1}' for some type arguments. - {0}' arabirimi uygulanamıyor çünkü bu uygulama bazı tür bağımsız değişkenlerinde başka bir uygulanan '{1}' arabiriminin uygulanmasıyla çakışabilir. + '{0}' arabirimi uygulanamıyor çünkü bu uygulama bazı tür bağımsız değişkenlerinde başka bir uygulanan '{1}' arabiriminin uygulanmasıyla çakışabilir. @@ -4713,17 +4757,17 @@ Type argument '{0}' is declared 'MustInherit' and does not satisfy the 'New' constraint for type parameter '{1}'. - {0}' tür bağımsız değişkeni 'MustInherit' olarak bildirildi ve '{1}' tür parametresi için 'New' kısıtlamasını karşılamıyor. + '{0}' tür bağımsız değişkeni 'MustInherit' olarak bildirildi ve '{1}' tür parametresi için 'New' kısıtlamasını karşılamıyor. Type argument '{0}' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter '{1}'. - {0}' tür bağımsız değişkeninde, '{1}' tür parametresinin 'New' kısıtlamasını karşılayacak ortak parametresi olmayan bir örnek oluşturucusu olmalıdır. + '{0}' tür bağımsız değişkeninde, '{1}' tür parametresinin 'New' kısıtlamasını karşılayacak ortak parametresi olmayan bir örnek oluşturucusu olmalıdır. Type parameter '{0}' must have either a 'New' constraint or a 'Structure' constraint to satisfy the 'New' constraint for type parameter '{1}'. - {0}' tür parametresinde, '{1}' tür parametresinin 'New' kısıtlamasını karşılamak için bir 'New' kısıtlaması veya 'Structure' kısıtlaması olmalıdır. + '{0}' tür parametresinde, '{1}' tür parametresinin 'New' kısıtlamasını karşılamak için bir 'New' kısıtlaması veya 'Structure' kısıtlaması olmalıdır. @@ -4733,7 +4777,7 @@ Generic type '{0}' cannot be imported more than once. - {0}' genel türü birden çok kez içeri aktarılamaz. + '{0}' genel türü birden çok kez içeri aktarılamaz. @@ -4818,12 +4862,12 @@ Type argument '{0}' does not satisfy the 'Structure' constraint for type parameter '{1}'. - {0}' tür bağımsız değişkeni, '{1}' tür parametresi için 'Structure' kısıtlamasını karşılamıyor. + '{0}' tür bağımsız değişkeni, '{1}' tür parametresi için 'Structure' kısıtlamasını karşılamıyor. Type argument '{0}' does not satisfy the 'Class' constraint for type parameter '{1}'. - {0}' tür bağımsız değişkeni, '{1}' tür parametresi için 'Class' kısıtlamasını karşılamıyor. + '{0}' tür bağımsız değişkeni, '{1}' tür parametresi için 'Class' kısıtlamasını karşılamıyor. @@ -4838,17 +4882,17 @@ Indirect constraint '{0}' obtained from the type parameter constraint '{1}' conflicts with the indirect constraint '{2}' obtained from the type parameter constraint '{3}'. - {1}' tür parametresi kısıtlamasından elde edilen dolaylı '{0}' kısıtlaması, '{3}' tür parametresi kısıtlamasından elde edilen dolaylı '{2}' kısıtlamasıyla çakışıyor. + '{1}' tür parametresi kısıtlamasından elde edilen dolaylı '{0}' kısıtlaması, '{3}' tür parametresi kısıtlamasından elde edilen dolaylı '{2}' kısıtlamasıyla çakışıyor. Constraint '{0}' conflicts with the indirect constraint '{1}' obtained from the type parameter constraint '{2}'. - {0}' kısıtlaması, '{2}' tür parametresi kısıtlamasından elde edilen dolaylı '{1}' kısıtlamasıyla çakışıyor. + '{0}' kısıtlaması, '{2}' tür parametresi kısıtlamasından elde edilen dolaylı '{1}' kısıtlamasıyla çakışıyor. Indirect constraint '{0}' obtained from the type parameter constraint '{1}' conflicts with the constraint '{2}'. - {1}' tür parametresi kısıtlamasından elde edilen dolaylı '{0}' kısıtlaması, '{2}' kısıtlamasıyla çakışıyor. + '{1}' tür parametresi kısıtlamasından elde edilen dolaylı '{0}' kısıtlaması, '{2}' kısıtlamasıyla çakışıyor. @@ -4860,7 +4904,7 @@ Type parameter '{0}' cannot be constrained to itself: {1} - {0}' tür parametresi kendi kendini kısıtlayamaz: {1} + '{0}' tür parametresi kendi kendini kısıtlayamaz: {1} @@ -4875,7 +4919,7 @@ Constraint '{0}' conflicts with the constraint '{1}' already specified for type parameter '{2}'. - {0}' kısıtlaması, '{2}' tür parametresi için zaten belirtilmiş olan '{1}' kısıtlamasıyla çakışıyor. + '{0}' kısıtlaması, '{2}' tür parametresi için zaten belirtilmiş olan '{1}' kısıtlamasıyla çakışıyor. @@ -4965,7 +5009,7 @@ Conflict between the default property and the 'DefaultMemberAttribute' defined on '{0}'. - {0}' üzerinde tanımlanan 'DefaultMemberAttribute' ile varsayılan özellik arasında çakışma var. + '{0}' üzerinde tanımlanan 'DefaultMemberAttribute' ile varsayılan özellik arasında çakışma var. @@ -5080,17 +5124,17 @@ Operator '{0}' must have one parameter. - {0}' işlecinde bir parametre olmalıdır. + '{0}' işlecinde bir parametre olmalıdır. Operator '{0}' must have two parameters. - {0}' işlecinin iki parametresi olmalıdır. + '{0}' işlecinin iki parametresi olmalıdır. Operator '{0}' must have either one or two parameters. - {0}' işlecinde bir veya iki parametre olmalıdır. + '{0}' işlecinde bir veya iki parametre olmalıdır. @@ -5125,7 +5169,7 @@ Operator '{0}' must have a return type of Boolean. - {0}' işlecinin dönüş türü Boole olmalıdır. + '{0}' işlecinin dönüş türü Boole olmalıdır. @@ -5175,27 +5219,27 @@ Matching '{0}' operator is required for '{1}'. - {1}' için eşleşen '{0}' işleci gerekir. + '{1}' için eşleşen '{0}' işleci gerekir. Return and parameter types of '{0}' must be '{1}' to be used in a '{2}' expression. - {2}' ifadesinde kullanılabilmesi için, '{0}' parametre türleri '{1}' olmalıdır. + '{2}' ifadesinde kullanılabilmesi için, '{0}' parametre türleri '{1}' olmalıdır. Type '{0}' must define operator '{1}' to be used in a '{2}' expression. - {0}' türü, '{2}' ifadesinde kullanılmak üzere '{1}' işlecini tanımlamalıdır. + '{0}' türü, '{2}' ifadesinde kullanılmak üzere '{1}' işlecini tanımlamalıdır. Cannot copy the value of 'ByRef' parameter '{0}' back to the matching argument because type '{1}' cannot be converted to type '{2}'. - {1}' türü '{2}' türüne dönüştürülemediğinden, 'ByRef' parametresinin '{0}' değeri eşleşen bağımsız değişkene geri kopyalanamıyor. + '{1}' türü '{2}' türüne dönüştürülemediğinden, 'ByRef' parametresinin '{0}' değeri eşleşen bağımsız değişkene geri kopyalanamıyor. Type '{0}' must define operator '{1}' to be used in a 'For' statement. - {0}' türü, 'For' deyiminde kullanılacak '{1}' işlecini tanımlamalıdır. + '{0}' türü, 'For' deyiminde kullanılacak '{1}' işlecini tanımlamalıdır. @@ -5210,7 +5254,7 @@ Operator '{0}' must have a second parameter of type 'Integer' or 'Integer?'. - {0}' işlecinin 'Integer' veya 'Integer?' türünde ikinci bir parametresi olmalıdır. + '{0}' işlecinin 'Integer' veya 'Integer?' türünde ikinci bir parametresi olmalıdır. @@ -5345,7 +5389,7 @@ Implicit variable '{0}' is invalid because of '{1}'. - {1}' nedeniyle '{0}' örtük değişkeni geçersiz. + '{1}' nedeniyle '{0}' örtük değişkeni geçersiz. @@ -5405,7 +5449,7 @@ Anonymous type property '{0}' cannot be used in the definition of a lambda expression within the same initialization list. - {0}' anonim tür özelliği aynı başlatma listesindeki bir lambda ifadesi tanımında kullanılamaz. + '{0}' anonim tür özelliği aynı başlatma listesindeki bir lambda ifadesi tanımında kullanılamaz. @@ -5475,7 +5519,7 @@ Extension method '{0}' has type constraints that can never be satisfied. - {0}' genişletme yönteminin asla karşılanamayacak tür kısıtlamaları var. + '{0}' genişletme yönteminin asla karşılanamayacak tür kısıtlamaları var. @@ -5502,12 +5546,12 @@ Parameter '{0}' already has a matching omitted argument. - {0}' parametresinin zaten eşleşen bir atlanmış bağımsız değişkeni var. + '{0}' parametresinin zaten eşleşen bir atlanmış bağımsız değişkeni var. Parameter '{0}' already has a matching argument. - {0}' parametresinin zaten eşleşen bir bağımsız değişkeni var. + '{0}' parametresinin zaten eşleşen bir bağımsız değişkeni var. @@ -5517,12 +5561,12 @@ Argument not specified for parameter '{0}'. - {0}' parametresi için bağımsız değişken belirtilmemiş. + '{0}' parametresi için bağımsız değişken belirtilmemiş. Type parameter '{0}' cannot be inferred. - {0}' tür parametresi çıkarsanamıyor. + '{0}' tür parametresi çıkarsanamıyor. @@ -5549,17 +5593,17 @@ Too many arguments to extension method '{0}' defined in '{1}'. - {1}' içinde tanımlanan '{0}' genişletme yöntemi için çok fazla bağımsız değişken var. + '{1}' içinde tanımlanan '{0}' genişletme yöntemi için çok fazla bağımsız değişken var. Parameter '{0}' in extension method '{1}' defined in '{2}' already has a matching omitted argument. - {2}' içinde tanımlanan '{1}' genişletme yöntemindeki '{0}' parametresinin zaten eşleşen atlanmış bir bağımsız değişkeni var. + '{2}' içinde tanımlanan '{1}' genişletme yöntemindeki '{0}' parametresinin zaten eşleşen atlanmış bir bağımsız değişkeni var. Parameter '{0}' of extension method '{1}' defined in '{2}' already has a matching argument. - {2}' içinde tanımlanan '{1}' genişletme yöntemindeki '{0}' parametresinin zaten eşleşen bir bağımsız değişkeni var. + '{2}' içinde tanımlanan '{1}' genişletme yöntemindeki '{0}' parametresinin zaten eşleşen bir bağımsız değişkeni var. @@ -5569,22 +5613,22 @@ Argument not specified for parameter '{0}' of extension method '{1}' defined in '{2}'. - {2}' içinde tanımlanan '{1}' genişletme yönteminin '{0}' parametresi için bağımsız değişken belirtilmemiş. + '{2}' içinde tanımlanan '{1}' genişletme yönteminin '{0}' parametresi için bağımsız değişken belirtilmemiş. Type parameter '{0}' for extension method '{1}' defined in '{2}' cannot be inferred. - {2}' içinde tanımlanan '{1}' genişletme yöntemi için '{0}' tür parametresi çıkarsanamıyor. + '{2}' içinde tanımlanan '{1}' genişletme yöntemi için '{0}' tür parametresi çıkarsanamıyor. Too few type arguments to extension method '{0}' defined in '{1}'. - {1}' içinde tanımlanan '{0}' genişletme yöntemi için çok az tür bağımsız değişkeni var. + '{1}' içinde tanımlanan '{0}' genişletme yöntemi için çok az tür bağımsız değişkeni var. Too many type arguments to extension method '{0}' defined in '{1}'. - {1}' içinde tanımlanan '{0}' genişletme yöntemi için çok fazla tür bağımsız değişkeni var. + '{1}' içinde tanımlanan '{0}' genişletme yöntemi için çok fazla tür bağımsız değişkeni var. @@ -5594,12 +5638,12 @@ Expression of type '{0}' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider. - {0}' türündeki ifade sorgulanabilir değil. LINQ sağlayıcısı için bir derleme başvurusunun ve/veya ad alanı içeri aktarmasının eksik olmadığından emin olun. + '{0}' türündeki ifade sorgulanabilir değil. LINQ sağlayıcısı için bir derleme başvurusunun ve/veya ad alanı içeri aktarmasının eksik olmadığından emin olun. Definition of method '{0}' is not accessible in this context. - {0}' yönteminin tanımına bu bağlamda erişilemiyor. + '{0}' yönteminin tanımına bu bağlamda erişilemiyor. @@ -5624,7 +5668,7 @@ Range variable '{0}' is already declared. - {0}' aralık değişkeni zaten bildirildi. + '{0}' aralık değişkeni zaten bildirildi. @@ -5664,12 +5708,12 @@ Name '{0}' is either not declared or not in the current scope. - {0}' adı bildirilmedi veya geçerli bağlamda yer almıyor. + '{0}' adı bildirilmedi veya geçerli bağlamda yer almıyor. Return type of nested function matching parameter '{0}' narrows from '{1}' to '{2}'. - {0}' parametresiyle eşleşen iç içe işlevin dönüş türü '{1}' iken '{2}' olarak daralıyor. + '{0}' parametresiyle eşleşen iç içe işlevin dönüş türü '{1}' iken '{2}' olarak daralıyor. @@ -5719,17 +5763,17 @@ Lambda expression cannot be converted to '{0}' because '{0}' is not a delegate type. - {0}' bir temsilci türü olmadığından lambda ifadesi '{0}' türüne dönüştürülemiyor. + '{0}' bir temsilci türü olmadığından lambda ifadesi '{0}' türüne dönüştürülemiyor. Lambda expression cannot be converted to '{0}' because type '{0}' is declared 'MustInherit' and cannot be created. - {0}' türü 'MustInherit' olarak bildirildiğinden ve oluşturulamadığından, lambda ifadesi '{0}' türüne dönüştürülemiyor. + '{0}' türü 'MustInherit' olarak bildirildiğinden ve oluşturulamadığından, lambda ifadesi '{0}' türüne dönüştürülemiyor. A nullable type cannot be inferred for variable '{0}'. - {0}' değişkeni için null yapılabilir bir tür çıkarsanamıyor. + '{0}' değişkeni için null yapılabilir bir tür çıkarsanamıyor. @@ -5749,7 +5793,7 @@ Range variable '{0}' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression. - {0}' aralık değişkeni kapsayan bir blok içinde bir değişken, daha önce tanımlanmış bir aralık değişkeni veya sorgu ifadesinde örtük olarak bildirilmiş bir değişken gizliyor. + '{0}' aralık değişkeni kapsayan bir blok içinde bir değişken, daha önce tanımlanmış bir aralık değişkeni veya sorgu ifadesinde örtük olarak bildirilmiş bir değişken gizliyor. @@ -5789,7 +5833,7 @@ Lambda parameter '{0}' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression. - {0}' lambda parametresi kapsayan bir blok içinde bir değişken, daha önce tanımlanmış bir aralık değişkeni veya sorgu ifadesinde örtük olarak bildirilmiş bir değişken gizliyor. + '{0}' lambda parametresi kapsayan bir blok içinde bir değişken, daha önce tanımlanmış bir aralık değişkeni veya sorgu ifadesinde örtük olarak bildirilmiş bir değişken gizliyor. @@ -5809,12 +5853,12 @@ Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. - {0}' yöntemindeki tür parametrelerinin veri türleri bu bağımsız değişkenlerden çıkarsanamıyor. Veri türlerinin açıkça belirtilmesi bu hatayı düzeltebilir. + '{0}' yöntemindeki tür parametrelerinin veri türleri bu bağımsız değişkenlerden çıkarsanamıyor. Veri türlerinin açıkça belirtilmesi bu hatayı düzeltebilir. Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. - {1}' içinde tanımlanan '{0}' genişletme yöntemindeki tür parametrelerinin veri türleri bu bağımsız değişkenlerden çıkarsanamıyor. Veri türlerinin açıkça belirtilmesi bu hatayı düzeltebilir. + '{1}' içinde tanımlanan '{0}' genişletme yöntemindeki tür parametrelerinin veri türleri bu bağımsız değişkenlerden çıkarsanamıyor. Veri türlerinin açıkça belirtilmesi bu hatayı düzeltebilir. @@ -5824,12 +5868,12 @@ Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments. - {0}' yöntemindeki tür parametrelerinin veri türleri bu bağımsız değişkenlerden çıkarsanamıyor. + '{0}' yöntemindeki tür parametrelerinin veri türleri bu bağımsız değişkenlerden çıkarsanamıyor. Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments. - {1}' içinde tanımlanan '{0}' genişletme yöntemindeki tür parametrelerinin veri türleri bu bağımsız değişkenlerden çıkarsanamıyor. + '{1}' içinde tanımlanan '{0}' genişletme yöntemindeki tür parametrelerinin veri türleri bu bağımsız değişkenlerden çıkarsanamıyor. @@ -5839,12 +5883,12 @@ Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error. - {0}' yöntemindeki tür parametrelerinin veri türleri, birden çok tür olasılığı bulunduğundan, bu bağımsız değişkenlerden çıkarsanamıyor. Veri türlerinin açıkça belirtilmesi bu hatayı düzeltebilir. + '{0}' yöntemindeki tür parametrelerinin veri türleri, birden çok tür olasılığı bulunduğundan, bu bağımsız değişkenlerden çıkarsanamıyor. Veri türlerinin açıkça belirtilmesi bu hatayı düzeltebilir. Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error. - {1}' içinde tanımlanan '{0}' genişletme yöntemindeki tür parametrelerinin veri türleri, birden çok tür olasılığı bulunduğundan, bu bağımsız değişkenlerden çıkarsanamıyor. Veri türlerinin açıkça belirtilmesi bu hatayı düzeltebilir. + '{1}' içinde tanımlanan '{0}' genişletme yöntemindeki tür parametrelerinin veri türleri, birden çok tür olasılığı bulunduğundan, bu bağımsız değişkenlerden çıkarsanamıyor. Veri türlerinin açıkça belirtilmesi bu hatayı düzeltebilir. @@ -5854,12 +5898,12 @@ Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because more than one type is possible. - {0}' yöntemindeki tür parametrelerinin veri türleri, birden çok tür olasılığı bulunduğundan, bu bağımsız değişkenlerden çıkarsanamıyor. + '{0}' yöntemindeki tür parametrelerinin veri türleri, birden çok tür olasılığı bulunduğundan, bu bağımsız değişkenlerden çıkarsanamıyor. Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because more than one type is possible. - {1}' içinde tanımlanan '{0}' genişletme yöntemindeki tür parametrelerinin veri türleri, birden çok tür olasılığı bulunduğundan, bu bağımsız değişkenlerden çıkarsanamıyor. + '{1}' içinde tanımlanan '{0}' genişletme yöntemindeki tür parametrelerinin veri türleri, birden çok tür olasılığı bulunduğundan, bu bağımsız değişkenlerden çıkarsanamıyor. @@ -5869,12 +5913,12 @@ Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error. - {0}' yöntemindeki tür parametrelerinin veri türleri, aynı türe dönüştürülmediklerinden, bu bağımsız değişkenlerden çıkarsanamıyor. Veri türlerinin açıkça belirtilmesi bu hatayı düzeltebilir. + '{0}' yöntemindeki tür parametrelerinin veri türleri, aynı türe dönüştürülmediklerinden, bu bağımsız değişkenlerden çıkarsanamıyor. Veri türlerinin açıkça belirtilmesi bu hatayı düzeltebilir. Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error. - {1}' içinde tanımlanan '{0}' genişletme yöntemindeki tür parametrelerinin veri türleri, aynı türe dönüştürülmediklerinden, bu bağımsız değişkenlerden çıkarsanamıyor. Veri türlerinin açıkça belirtilmesi bu hatayı düzeltebilir. + '{1}' içinde tanımlanan '{0}' genişletme yöntemindeki tür parametrelerinin veri türleri, aynı türe dönüştürülmediklerinden, bu bağımsız değişkenlerden çıkarsanamıyor. Veri türlerinin açıkça belirtilmesi bu hatayı düzeltebilir. @@ -5884,12 +5928,12 @@ Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because they do not convert to the same type. - {0}' yöntemindeki tür parametrelerinin veri türleri, aynı türe dönüştürülmediklerinden, bu bağımsız değişkenlerden çıkarsanamıyor. + '{0}' yöntemindeki tür parametrelerinin veri türleri, aynı türe dönüştürülmediklerinden, bu bağımsız değişkenlerden çıkarsanamıyor. Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because they do not convert to the same type. - {1}' içinde tanımlanan '{0}' genişletme yöntemindeki tür parametrelerinin veri türleri, aynı türe dönüştürülmediklerinden, bu bağımsız değişkenlerden çıkarsanamıyor. + '{1}' içinde tanımlanan '{0}' genişletme yöntemindeki tür parametrelerinin veri türleri, aynı türe dönüştürülmediklerinden, bu bağımsız değişkenlerden çıkarsanamıyor. @@ -5919,12 +5963,12 @@ Extension Method '{0}' defined in '{2}' does not have a signature compatible with delegate '{1}'. - {2}' içinde tanımlanan '{0}' Genişletme Yönteminin '{1}' temsilcisiyle uyumlu bir imzası yok. + '{2}' içinde tanımlanan '{0}' Genişletme Yönteminin '{1}' temsilcisiyle uyumlu bir imzası yok. Argument matching parameter '{0}' narrows to '{1}'. - {0}' parametresiyle eşleşen bağımsız değişken '{1}' olarak daralıyor. + '{0}' parametresiyle eşleşen bağımsız değişken '{1}' olarak daralıyor. @@ -5956,7 +6000,7 @@ Extension method '{0}' defined in '{1}' is not generic (or has no free type parameters) and so cannot have type arguments. - {1}' içinde tanımlanan '{0}' genişletme yöntemi genel olmadığından (boş tür parametresi yok), tür bağımsız değişkenleri olamaz. + '{1}' içinde tanımlanan '{0}' genişletme yöntemi genel olmadığından (boş tür parametresi yok), tür bağımsız değişkenleri olamaz. @@ -5976,12 +6020,12 @@ Type '{0}' cannot be embedded because it has generic argument. Consider disabling the embedding of interop types. - {0}' türünün genel bağımsız değişkeni olduğundan, bu tür eklenemez. Birlikte çalışma türlerinde eklemeyi devre dışı bırakabilirsiniz. + '{0}' türünün genel bağımsız değişkeni olduğundan, bu tür eklenemez. Birlikte çalışma türlerinde eklemeyi devre dışı bırakabilirsiniz. Type '{0}' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. - {0}' türü, bir gömülü birlikte çalışma türü olan genel tür bağımsız değişkeni içerdiğinden bütünleştirilmiş kod sınırları arasında kullanılamaz. + '{0}' türü, bir gömülü birlikte çalışma türü olan genel tür bağımsız değişkeni içerdiğinden bütünleştirilmiş kod sınırları arasında kullanılamaz. @@ -6026,7 +6070,7 @@ Default property '{0}' conflicts with the default property '{1}' in the base {2} '{3}'. '{0}' will be the default property. '{0}' should be declared 'Shadows'. - {0}' varsayılan özelliği {2} '{3}' temelinde '{1}' varsayılan özelliğiyle çakışıyor. Varsayılan özellik '{0}' olacak. '{0}' 'Shadows' olarak bildirilmelidir. + '{0}' varsayılan özelliği {2} '{3}' temelinde '{1}' varsayılan özelliğiyle çakışıyor. Varsayılan özellik '{0}' olacak. '{0}' 'Shadows' olarak bildirilmelidir. @@ -6056,7 +6100,7 @@ Possible problem detected while building assembly '{0}': {1} - {0}' derlemesi oluşturulurken olası bir sorun algılandı: {1} + '{0}' derlemesi oluşturulurken olası bir sorun algılandı: {1} @@ -6126,7 +6170,7 @@ Type of member '{0}' is not CLS-compliant. - {0}' üyesinin türü CLS uyumlu değil. + '{0}' üyesinin türü CLS uyumlu değil. @@ -6146,7 +6190,7 @@ Return type of function '{0}' is not CLS-compliant. - {0}' işlevinin dönüş türü CLS uyumlu değil. + '{0}' işlevinin dönüş türü CLS uyumlu değil. @@ -6156,7 +6200,7 @@ Type of parameter '{0}' is not CLS-compliant. - {0}' parametresinin türü CLS uyumlu değil. + '{0}' parametresinin türü CLS uyumlu değil. @@ -6186,7 +6230,7 @@ Name '{0}' is not CLS-compliant. - {0}' adı CLS uyumlu değil. + '{0}' adı CLS uyumlu değil. @@ -6236,7 +6280,7 @@ Root namespace '{0}' is not CLS-compliant. - {0}' kök ad alanı CLS uyumlu değil. + '{0}' kök ad alanı CLS uyumlu değil. @@ -6246,7 +6290,7 @@ Name '{0}' in the root namespace '{1}' is not CLS-compliant. - {1}' kök ad alanındaki '{0}' adı CLS uyumlu değil. + '{1}' kök ad alanındaki '{0}' adı CLS uyumlu değil. @@ -6256,7 +6300,7 @@ Generic parameter constraint type '{0}' is not CLS-compliant. - {0}' genel parametre kısıtlama türü CLS uyumlu değil. + '{0}' genel parametre kısıtlama türü CLS uyumlu değil. @@ -6266,7 +6310,7 @@ Type '{0}' is not CLS-compliant. - {0}' türü CLS uyumlu değil. + '{0}' türü CLS uyumlu değil. @@ -6306,7 +6350,7 @@ Type parameter '{0}' has the same name as a type parameter of an enclosing type. Enclosing type's type parameter will be shadowed. - {0}' tür parametresi, kapsayan türün tür parametresiyle aynı ada sahip. Kapsayan türün tür parametresi gölgelenir. + '{0}' tür parametresi, kapsayan türün tür parametresiyle aynı ada sahip. Kapsayan türün tür parametresi gölgelenir. @@ -6316,7 +6360,7 @@ Could not find standard library '{0}'. - {0}' standart kitaplığı bulunamadı. + '{0}' standart kitaplığı bulunamadı. @@ -6326,7 +6370,7 @@ Delegate type '{0}' of event '{1}' is not CLS-compliant. - {1}' olayının '{0}' temsilci türü CLS uyumlu değil. + '{1}' olayının '{0}' temsilci türü CLS uyumlu değil. @@ -6376,7 +6420,7 @@ Casing of namespace name '{0}' does not match casing of namespace name '{1}' in '{2}'. - {0}' ad alanı adındaki büyük/küçük harf kullanımı, '{2}' içindeki '{1}' ad alanı adının büyük/küçük harf kullanımıyla eşleşmiyor. + '{0}' ad alanı adındaki büyük/küçük harf kullanımı, '{2}' içindeki '{1}' ad alanı adının büyük/küçük harf kullanımıyla eşleşmiyor. @@ -6406,7 +6450,7 @@ A reference was created to embedded interop assembly '{0}' because of an indirect reference to that assembly from assembly '{1}'. Consider changing the 'Embed Interop Types' property on either assembly. - {1}' derlemesinden '{0}' gömülü birlikte çalışma derlemesine dolaylı bir başvuru olduğundan, bu birlikte çalışma derlemesine bir başvuru oluşturuldu. İki derlemeden birinde 'Embed Interop Types' özelliğini değiştirebilirsiniz. + '{1}' derlemesinden '{0}' gömülü birlikte çalışma derlemesine dolaylı bir başvuru olduğundan, bu birlikte çalışma derlemesine bir başvuru oluşturuldu. İki derlemeden birinde 'Embed Interop Types' özelliğini değiştirebilirsiniz. @@ -6436,7 +6480,7 @@ First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete. - {2}' öğesinin '{1}' temel sınıfında '{0}' artık kullanılmıyor olarak işaretlendiğinden, bu 'Sub New' yönteminin ilk deyimi açık bir 'MyBase.New' veya 'MyClass.New' çağrısı olmalıdır. + '{2}' öğesinin '{1}' temel sınıfında '{0}' artık kullanılmıyor olarak işaretlendiğinden, bu 'Sub New' yönteminin ilk deyimi açık bir 'MyBase.New' veya 'MyClass.New' çağrısı olmalıdır. @@ -6446,7 +6490,7 @@ First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete: '{3}' - {2}' öğesinin '{1}' temel sınıfında '{0}' artık kullanılmıyor olarak işaretlendiğinden, bu 'Sub New' yönteminin ilk deyimi açık bir 'MyBase.New' veya 'MyClass.New' çağrısı olmalıdır: '{3}' + '{2}' öğesinin '{1}' temel sınıfında '{0}' artık kullanılmıyor olarak işaretlendiğinden, bu 'Sub New' yönteminin ilk deyimi açık bir 'MyBase.New' veya 'MyClass.New' çağrısı olmalıdır: '{3}' @@ -6466,7 +6510,7 @@ Type arguments inferred for method '{0}' result in the following warnings :{1} - {0}' yöntemi için çıkarsanan tür bağımsız değişkenleri şu uyarıyı veriyor:{1} + '{0}' yöntemi için çıkarsanan tür bağımsız değişkenleri şu uyarıyı veriyor:{1} @@ -6486,7 +6530,7 @@ Use command-line option '{0}' or appropriate project settings instead of '{1}'. - {1}' yerine '{0}' komut satırı seçeneğini veya uygun proje ayarlarını kullanın. + '{1}' yerine '{0}' komut satırı seçeneğini veya uygun proje ayarlarını kullanın. @@ -6506,7 +6550,7 @@ Implicit conversion from '{1}' to '{2}' in copying the value of 'ByRef' parameter '{0}' back to the matching argument. - {0}' 'ByRef' parametresinin değeri eşleşen bağımsız değişkene geri kopyalanırken '{1}' ile '{2}' arasında örtük dönüştürme. + '{0}' 'ByRef' parametresinin değeri eşleşen bağımsız değişkene geri kopyalanırken '{1}' ile '{2}' arasında örtük dönüştürme. @@ -6536,7 +6580,7 @@ Implicit conversion from '{0}' to '{1}'. - {1}' ile '{0}' arasında örtük dönüştürme. + '{1}' ile '{0}' arasında örtük dönüştürme. @@ -6546,7 +6590,7 @@ Local variable '{0}' is read-only and its type is a structure. Invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block. - {0}' yerel değişkeni salt okunur ve yapı türünde. Üyelerini çağırmak veya bunu ByRef olarak geçirmek içeriğini değiştirmez ve beklenmeyen sonuçlara neden olabilir. Bu değişkeni 'Using' bloğu dışında bildirebilirsiniz. + '{0}' yerel değişkeni salt okunur ve yapı türünde. Üyelerini çağırmak veya bunu ByRef olarak geçirmek içeriğini değiştirmez ve beklenmeyen sonuçlara neden olabilir. Bu değişkeni 'Using' bloğu dışında bildirebilirsiniz. @@ -6556,7 +6600,7 @@ Local variable '{0}' is read-only. When its type is a structure, invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block. - {0}' yerel değişkeni salt okunur. Bunun türü yapı olduğunda, üyelerini çağırmak veya bunu ByRef olarak geçirmek içeriğini değiştirmez ve beklenmeyen sonuçlara neden olabilir. Bu değişkeni 'Using' bloğu dışında bildirebilirsiniz. + '{0}' yerel değişkeni salt okunur. Bunun türü yapı olduğunda, üyelerini çağırmak veya bunu ByRef olarak geçirmek içeriğini değiştirmez ve beklenmeyen sonuçlara neden olabilir. Bu değişkeni 'Using' bloğu dışında bildirebilirsiniz. @@ -6586,7 +6630,7 @@ Operands of type Object used for operator '{0}'; use the 'Is' operator to test object identity. - {0}' işleci için kullanılan Object türünde işlenenler; nesne kimliğini test etmek için 'Is' işlecini kullanın. + '{0}' işleci için kullanılan Object türünde işlenenler; nesne kimliğini test etmek için 'Is' işlecini kullanın. @@ -6596,7 +6640,7 @@ Operands of type Object used for operator '{0}'; runtime errors could occur. - {0}' işleci için kullanılan Object türünde işlenenler; çalışma zamanı hataları oluşabilir. + '{0}' işleci için kullanılan Object türünde işlenenler; çalışma zamanı hataları oluşabilir. @@ -6706,7 +6750,7 @@ Variable '{0}' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. - {0}' değişkeni, bir değere atanmadan önce başvuru olarak geçirildi. Çalışma zamanında null başvurusu özel durumu oluşabilir. + '{0}' değişkeni, bir değere atanmadan önce başvuru olarak geçirildi. Çalışma zamanında null başvurusu özel durumu oluşabilir. @@ -6726,7 +6770,7 @@ Operands of type Object used for operator '{0}'; use the 'IsNot' operator to test object identity. - {0}' işleci için kullanılan Object türünde işlenenler; nesne kimliğini test etmek için 'IsNot' işlecini kullanın. + '{0}' işleci için kullanılan Object türünde işlenenler; nesne kimliğini test etmek için 'IsNot' işlecini kullanın. @@ -6826,7 +6870,7 @@ Variable '{0}' is used before it has been assigned a value. A null reference exception could result at runtime. - {0}' değişkeni bir değere atanmadan önce kullanıldı. Çalışma zamanında null başvurusu özel durumu oluşabilir. + '{0}' değişkeni bir değere atanmadan önce kullanıldı. Çalışma zamanında null başvurusu özel durumu oluşabilir. @@ -6836,7 +6880,7 @@ Function '{0}' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. - {0}' işlevi tüm kod yollarında değer döndürmüyor. Sonuç kullanıldığında çalışma zamanında null başvurusu özel durumu oluşabilir. + '{0}' işlevi tüm kod yollarında değer döndürmüyor. Sonuç kullanıldığında çalışma zamanında null başvurusu özel durumu oluşabilir. @@ -6846,7 +6890,7 @@ Operator '{0}' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. - {0}' işleci tüm kod yollarında değer döndürmüyor. Sonuç kullanıldığında çalışma zamanında null başvurusu özel durumu oluşabilir. + '{0}' işleci tüm kod yollarında değer döndürmüyor. Sonuç kullanıldığında çalışma zamanında null başvurusu özel durumu oluşabilir. @@ -6856,7 +6900,7 @@ Property '{0}' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. - {0}' özelliği tüm kod yollarında değer döndürmüyor. Sonuç kullanıldığında çalışma zamanında null başvurusu özel durumu oluşabilir. + '{0}' özelliği tüm kod yollarında değer döndürmüyor. Sonuç kullanıldığında çalışma zamanında null başvurusu özel durumu oluşabilir. @@ -6866,7 +6910,7 @@ Variable '{0}' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use - {0}' değişkeni, bir değere atanmadan önce başvuru olarak geçirildi. Çalışma zamanında null başvurusu özel durumu oluşabilir. Yapının veya tüm başvuru üyelerinin kullanılmadan önce başlatıldığından emin olun + '{0}' değişkeni, bir değere atanmadan önce başvuru olarak geçirildi. Çalışma zamanında null başvurusu özel durumu oluşabilir. Yapının veya tüm başvuru üyelerinin kullanılmadan önce başlatıldığından emin olun @@ -6876,7 +6920,7 @@ Variable '{0}' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use - {0}' değişkeni bir değere atanmadan önce kullanıldı. Çalışma zamanında null başvurusu özel durumu oluşabilir. Yapının ve tüm başvuru üyelerinin kullanılmadan önce başlatıldığından emin olun + '{0}' değişkeni bir değere atanmadan önce kullanıldı. Çalışma zamanında null başvurusu özel durumu oluşabilir. Yapının ve tüm başvuru üyelerinin kullanılmadan önce başlatıldığından emin olun @@ -6896,7 +6940,7 @@ Assembly reference '{0}' is invalid and cannot be resolved. - {0}' derleme başvurusu geçersiz ve çözülemiyor. + '{0}' derleme başvurusu geçersiz ve çözülemiyor. @@ -6956,7 +7000,7 @@ XML comment tag '{0}' appears with identical attributes more than once in the same XML comment block. - {0}' XML açıklama etiketi, özdeş özniteliklerle aynı XML açıklama bloğunda birden çok kez geçiyor. + '{0}' XML açıklama etiketi, özdeş özniteliklerle aynı XML açıklama bloğunda birden çok kez geçiyor. @@ -6966,7 +7010,7 @@ XML comment tag '{0}' is not permitted on a '{1}' language element. - {1}' dil öğesinde '{0}' XML açıklama etiketine izin verilmez. + '{1}' dil öğesinde '{0}' XML açıklama etiketine izin verilmez. @@ -6976,7 +7020,7 @@ XML comment parameter '{0}' does not match a parameter on the corresponding '{1}' statement. - {0}' açıklama türü parametresi, buna karşılık gelen '{1}' deyimindeki bir parametreyle eşleşmiyor. + '{0}' açıklama türü parametresi, buna karşılık gelen '{1}' deyimindeki bir parametreyle eşleşmiyor. @@ -7016,7 +7060,7 @@ Unable to create XML documentation file '{0}': {1} - {0}' XML belge dosyası oluşturulamadı: {1} + '{0}' XML belge dosyası oluşturulamadı: {1} @@ -7076,7 +7120,7 @@ XML comment type parameter '{0}' does not match a type parameter on the corresponding '{1}' statement. - {0}' açıklama türü parametresi, buna karşılık gelen '{1}' deyimindeki bir tür parametresiyle eşleşmiyor. + '{0}' açıklama türü parametresi, buna karşılık gelen '{1}' deyimindeki bir tür parametresiyle eşleşmiyor. @@ -7106,7 +7150,7 @@ Unable to include XML fragment '{0}' of file '{1}'. - {1}' dosyasının '{0}' XML parçası eklenemedi. + '{1}' dosyasının '{0}' XML parçası eklenemedi. @@ -7116,7 +7160,7 @@ Unable to include XML fragment '{1}' of file '{0}'. {2} - {0}' dosyasının '{1}' XML parçası eklenemedi. {2} + '{0}' dosyasının '{1}' XML parçası eklenemedi. {2} @@ -7126,7 +7170,7 @@ Runtime errors might occur when converting '{0}' to '{1}'. - {0}' - '{1}' dönüştürmesi sırasında çalışma zamanı hataları oluşabilir. + '{0}' - '{1}' dönüştürmesi sırasında çalışma zamanı hataları oluşabilir. @@ -7296,7 +7340,7 @@ Type or namespace '{0}' is not defined. - {0}' türü veya ad alanı tanımlanmadı. + '{0}' türü veya ad alanı tanımlanmadı. @@ -7326,7 +7370,7 @@ Function '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement? - {0}' işlevi tüm kod yollarında değer döndürmüyor. 'Return' deyiminiz eksik olabilir mi? + '{0}' işlevi tüm kod yollarında değer döndürmüyor. 'Return' deyiminiz eksik olabilir mi? @@ -7336,7 +7380,7 @@ Operator '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement? - {0}' işleci tüm kod yollarında değer döndürmüyor. 'Return' deyiminiz eksik olabilir mi? + '{0}' işleci tüm kod yollarında değer döndürmüyor. 'Return' deyiminiz eksik olabilir mi? @@ -7346,7 +7390,7 @@ Property '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement? - {0}' özelliği tüm kod yollarında değer döndürmüyor. 'Return' deyiminiz eksik olabilir mi? + '{0}' özelliği tüm kod yollarında değer döndürmüyor. 'Return' deyiminiz eksik olabilir mi? @@ -7418,22 +7462,22 @@ Error extracting public key from file '{0}': {1} - {0}' dosyasından ortak anahtar ayıklanırken hata oluştu: {1} + '{0}' dosyasından ortak anahtar ayıklanırken hata oluştu: {1} Error extracting public key from container '{0}': {1} - {0}' kapsayıcısından ortak anahtar ayıklanırken hata oluştu: {1} + '{0}' kapsayıcısından ortak anahtar ayıklanırken hata oluştu: {1} Friend access was granted by '{0}', but the public key of the output assembly does not match that specified by the attribute in the granting assembly. - {0}' öğesine friend erişimi izni verildi, ancak çıkış derlemesinin ortak anahtarı, izin veren derlemedeki öznitelik tarafından belirtilenle eşleşmiyor. + '{0}' öğesine friend erişimi izni verildi, ancak çıkış derlemesinin ortak anahtarı, izin veren derlemedeki öznitelik tarafından belirtilenle eşleşmiyor. Friend access was granted by '{0}', but the strong name signing state of the output assembly does not match that of the granting assembly. - {0}' öğesine friend erişimi izni verildi, ancak çıkış derlemesinin kesin ad imzalama durumu, izin veren derlemeninkiyle eşleşmiyor. + '{0}' öğesine friend erişimi izni verildi, ancak çıkış derlemesinin kesin ad imzalama durumu, izin veren derlemeninkiyle eşleşmiyor. @@ -7468,12 +7512,12 @@ Key file '{0}' is missing the private key needed for signing. - {0}' anahtar dosyasında imzalama için gereken özel anahtar eksik. + '{0}' anahtar dosyasında imzalama için gereken özel anahtar eksik. Error signing assembly '{0}': {1} - {0}' derlemesini imzalama hatası: {1} + '{0}' derlemesini imzalama hatası: {1} @@ -7538,7 +7582,7 @@ The assembly name '{0}' is reserved and cannot be used as a reference in an interactive session - {0}' derleme adı ayrıldı ve etkileşimli bir oturumda başvuru olarak kullanılamıyor + '{0}' derleme adı ayrıldı ve etkileşimli bir oturumda başvuru olarak kullanılamıyor @@ -7593,7 +7637,7 @@ The command line switch '{0}' is not yet implemented and was ignored. - {0}' komut satırı geçişi henüz uygulanmadı ve yoksayıldı. + '{0}' komut satırı geçişi henüz uygulanmadı ve yoksayıldı. @@ -7638,7 +7682,7 @@ Data type of '{0}' in '{1}' could not be inferred. '{2}' assumed. - {1}' içinde '{0}' veri türü çıkarsanamadı. '{2}' varsayıldı. + '{1}' içinde '{0}' veri türü çıkarsanamadı. '{2}' varsayıldı. @@ -7653,7 +7697,7 @@ Conversion from '{0}' to '{1}' may be ambiguous. - {0}' - '{1}' dönüştürmesi belirsiz olabilir. + '{0}' - '{1}' dönüştürmesi belirsiz olabilir. @@ -7688,7 +7732,7 @@ Implicit conversion from '{4}' to '{5}'; this conversion may fail because '{0}' is not derived from '{1}', as required for the 'In' generic parameter '{2}' in '{3}'. - {4}' ile '{5}' arasında örtük dönüşüm; '{3}' içinde '{2}' 'In' genel parametresinin gerektirdiği gibi '{0}' öğesi '{1}' öğesinden türetilmediği için, bu dönüşüm başarısız olabilir. + '{4}' ile '{5}' arasında örtük dönüşüm; '{3}' içinde '{2}' 'In' genel parametresinin gerektirdiği gibi '{0}' öğesi '{1}' öğesinden türetilmediği için, bu dönüşüm başarısız olabilir. @@ -7698,7 +7742,7 @@ Implicit conversion from '{4}' to '{5}'; this conversion may fail because '{0}' is not derived from '{1}', as required for the 'Out' generic parameter '{2}' in '{3}'. - {4}' ile '{5}' arasında örtük dönüşüm; '{3}' içinde '{2}' 'Out' genel parametresinin gerektirdiği gibi '{0}' öğesi '{1}' öğesinden türetilmediği için, bu dönüşüm başarısız olabilir. + '{4}' ile '{5}' arasında örtük dönüşüm; '{3}' içinde '{2}' 'Out' genel parametresinin gerektirdiği gibi '{0}' öğesi '{1}' öğesinden türetilmediği için, bu dönüşüm başarısız olabilir. @@ -7738,7 +7782,7 @@ Interface '{0}' is ambiguous with another implemented interface '{1}' due to the 'In' and 'Out' parameters in '{2}'. - {2}' içindeki 'In' ve 'Out' parametreleri nedeniyle '{0}' arabirimi uygulanmış diğer '{1}' arabirimiyle birlikte belirsiz. + '{2}' içindeki 'In' ve 'Out' parametreleri nedeniyle '{0}' arabirimi uygulanmış diğer '{1}' arabirimiyle birlikte belirsiz. @@ -7768,37 +7812,37 @@ Type '{0}' cannot be used in this context because '{0}' is an 'In' type parameter. - {0}' bir 'In' tür parametresi olduğundan, bu bağlamda '{0}' türü kullanılamaz. + '{0}' bir 'In' tür parametresi olduğundan, bu bağlamda '{0}' türü kullanılamaz. Type '{0}' cannot be used for the '{1}' in '{2}' in this context because '{0}' is an 'In' type parameter. - {0}' bir 'In' tür parametresi olduğundan, bu bağlamda '{2}' içindeki '{1}' için '{0}' türü kullanılamaz. + '{0}' bir 'In' tür parametresi olduğundan, bu bağlamda '{2}' içindeki '{1}' için '{0}' türü kullanılamaz. Type '{0}' cannot be used in '{1}' in this context because '{0}' is an 'In' type parameter. - {0}' bir 'In' tür parametresi olduğundan, bu bağlamda '{1}' içinde '{0}' türü kullanılamaz. + '{0}' bir 'In' tür parametresi olduğundan, bu bağlamda '{1}' içinde '{0}' türü kullanılamaz. Type '{0}' cannot be used for the '{2}' of '{3}' in '{1}' in this context because '{0}' is an 'In' type parameter. - {0}' bir 'In' tür parametresi olduğundan, bu bağlamda '{1}' içinde '{2}' / '{3}' için '{0}' türü kullanılamaz. + '{0}' bir 'In' tür parametresi olduğundan, bu bağlamda '{1}' içinde '{2}' / '{3}' için '{0}' türü kullanılamaz. Type '{0}' cannot be used as a property type in this context because '{0}' is an 'In' type parameter and the property is not marked WriteOnly. - {0}' bir 'In' tür parametresi olduğundan ve özellik WriteOnly olarak işaretlenmediğinden, bu bağlamda özellik türü olarak '{0}' türü kullanılamaz. + '{0}' bir 'In' tür parametresi olduğundan ve özellik WriteOnly olarak işaretlenmediğinden, bu bağlamda özellik türü olarak '{0}' türü kullanılamaz. Type '{0}' cannot be used as a ReadOnly property type because '{0}' is an 'In' type parameter. - {0}' bir 'In' tür parametresi olduğundan, ReadOnly özellik türü olarak '{0}' türü kullanılamaz. + '{0}' bir 'In' tür parametresi olduğundan, ReadOnly özellik türü olarak '{0}' türü kullanılamaz. Type '{0}' cannot be used as a return type because '{0}' is an 'In' type parameter. - {0}' bir 'In' tür parametresi olduğundan, dönüş türü olarak '{0}' türü kullanılamaz. + '{0}' bir 'In' tür parametresi olduğundan, dönüş türü olarak '{0}' türü kullanılamaz. @@ -7808,12 +7852,12 @@ Type '{0}' cannot be used as a ByVal parameter type because '{0}' is an 'Out' type parameter. - {0}' bir 'Out' tür parametresi olduğundan, ByVal parametre türü olarak '{0}' türü kullanılamaz. + '{0}' bir 'Out' tür parametresi olduğundan, ByVal parametre türü olarak '{0}' türü kullanılamaz. Type '{0}' cannot be used as a generic type constraint because '{0}' is an 'Out' type parameter. - {0}' bir 'Out' tür parametresi olduğundan, genel tür kısıtlaması olarak '{0}' türü kullanılamaz. + '{0}' bir 'Out' tür parametresi olduğundan, genel tür kısıtlaması olarak '{0}' türü kullanılamaz. @@ -7823,52 +7867,52 @@ Type '{0}' cannot be used in this context because '{0}' is an 'Out' type parameter. - {0}' bir 'Out' tür parametresi olduğundan, bu bağlamda '{0}' türü kullanılamaz. + '{0}' bir 'Out' tür parametresi olduğundan, bu bağlamda '{0}' türü kullanılamaz. Type '{0}' cannot be used for the '{1}' in '{2}' in this context because '{0}' is an 'Out' type parameter. - {0}' bir 'Out' tür parametresi olduğundan, bu bağlamda '{2}' içindeki '{1}' için '{0}' türü kullanılamaz. + '{0}' bir 'Out' tür parametresi olduğundan, bu bağlamda '{2}' içindeki '{1}' için '{0}' türü kullanılamaz. Type '{0}' cannot be used in '{1}' in this context because '{0}' is an 'Out' type parameter. - {0}' bir 'Out' tür parametresi olduğundan, bu bağlamda '{1}' içinde '{0}' türü kullanılamaz. + '{0}' bir 'Out' tür parametresi olduğundan, bu bağlamda '{1}' içinde '{0}' türü kullanılamaz. Type '{0}' cannot be used for the '{2}' of '{3}' in '{1}' in this context because '{0}' is an 'Out' type parameter. - {0}' bir 'Out' tür parametresi olduğundan, bu bağlamda '{1}' içinde '{2}' / '{3}' için '{0}' türü kullanılamaz. + '{0}' bir 'Out' tür parametresi olduğundan, bu bağlamda '{1}' içinde '{2}' / '{3}' için '{0}' türü kullanılamaz. Type '{0}' cannot be used as a property type in this context because '{0}' is an 'Out' type parameter and the property is not marked ReadOnly. - {0}' bir 'Out' türü parametre olduğundan ve özellik ReadOnly olarak işaretlenmediğinden, '{0}' türü bu bağlamda özellik türü olarak kullanılamaz. + '{0}' bir 'Out' türü parametre olduğundan ve özellik ReadOnly olarak işaretlenmediğinden, '{0}' türü bu bağlamda özellik türü olarak kullanılamaz. Type '{0}' cannot be used as a WriteOnly property type because '{0}' is an 'Out' type parameter. - {0}' bir 'Out' türü parametre olduğundan, '{0}' bir WriteOnly özellik türü olarak kullanılamaz. + '{0}' bir 'Out' türü parametre olduğundan, '{0}' bir WriteOnly özellik türü olarak kullanılamaz. Type '{0}' cannot be used in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'. - {0}' türünün hem bağlamı hem de tanımı '{1}' arabiriminde iç içe yer aldığından ve '{1}' arabiriminin 'In' veya 'Out' türü parametreleri olduğundan, '{0}' türü bu bağlamda kullanılamaz. '{0}' tanımını '{1}' arabiriminin dışına taşıyabilirsiniz. + '{0}' türünün hem bağlamı hem de tanımı '{1}' arabiriminde iç içe yer aldığından ve '{1}' arabiriminin 'In' veya 'Out' türü parametreleri olduğundan, '{0}' türü bu bağlamda kullanılamaz. '{0}' tanımını '{1}' arabiriminin dışına taşıyabilirsiniz. Type '{0}' cannot be used for the '{2}' in '{3}' in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'. - {0}' türünün hem bağlamı hem de tanımı '{1}' arabiriminde iç içe yer aldığından ve '{1}' arabiriminin 'In' veya 'Out' türü parametreleri olduğundan, '{0}' türü bu bağlamda '{3}' içinde '{2}' için kullanılamaz. '{0}' tanımını '{1}' arabiriminin dışına taşıyabilirsiniz. + '{0}' türünün hem bağlamı hem de tanımı '{1}' arabiriminde iç içe yer aldığından ve '{1}' arabiriminin 'In' veya 'Out' türü parametreleri olduğundan, '{0}' türü bu bağlamda '{3}' içinde '{2}' için kullanılamaz. '{0}' tanımını '{1}' arabiriminin dışına taşıyabilirsiniz. Type '{0}' cannot be used in '{2}' in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'. - {0}' türünün hem bağlamı hem de tanımı '{1}' arabiriminde iç içe yer aldığından ve '{1}' arabiriminin 'In' veya 'Out' türü parametreleri olduğundan, '{0}' türü bu bağlamda '{2}' için kullanılamaz. '{0}' tanımını '{1}' arabiriminin dışına taşıyabilirsiniz. + '{0}' türünün hem bağlamı hem de tanımı '{1}' arabiriminde iç içe yer aldığından ve '{1}' arabiriminin 'In' veya 'Out' türü parametreleri olduğundan, '{0}' türü bu bağlamda '{2}' için kullanılamaz. '{0}' tanımını '{1}' arabiriminin dışına taşıyabilirsiniz. Type '{0}' cannot be used for the '{3}' of '{4}' in '{2}' in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'. - {0}' türünün hem bağlamı hem de tanımı '{1}' arabiriminde iç içe yer aldığından ve '{1}' arabiriminin 'In' veya 'Out' türü parametreleri olduğundan, '{0}' türü bu bağlamda '{2}' içinde '{4}' öğesindeki '{3}' için kullanılamaz. '{0}' tanımını '{1}' arabiriminin dışına taşıyabilirsiniz. + '{0}' türünün hem bağlamı hem de tanımı '{1}' arabiriminde iç içe yer aldığından ve '{1}' arabiriminin 'In' veya 'Out' türü parametreleri olduğundan, '{0}' türü bu bağlamda '{2}' içinde '{4}' öğesindeki '{3}' için kullanılamaz. '{0}' tanımını '{1}' arabiriminin dışına taşıyabilirsiniz. @@ -7888,12 +7932,12 @@ Attribute parameter '{0}' must be specified. - {0}' öznitelik parametresi belirtilmelidir. + '{0}' öznitelik parametresi belirtilmelidir. Attribute parameter '{0}' or '{1}' must be specified. - {0}' veya '{1}' öznitelik parametresi belirtilmelidir. + '{0}' veya '{1}' öznitelik parametresi belirtilmelidir. @@ -7918,7 +7962,7 @@ Security attribute '{0}' is not valid on this declaration type. Security attributes are only valid on assembly, type and method declarations. - {0}' güvenlik özniteliği bu bildirim türü için geçerli değil. Güvenlik öznitelikleri yalnızca derleme, tür ve yöntem bildirimlerinde geçerlidir. + '{0}' güvenlik özniteliği bu bildirim türü için geçerli değil. Güvenlik öznitelikleri yalnızca derleme, tür ve yöntem bildirimlerinde geçerlidir. @@ -7943,7 +7987,7 @@ Cannot embed interop types from assembly '{0}' because it is missing the '{1}' attribute. - {1}' özniteliği eksik olduğundan '{0}' derlemesinden birlikte çalışma türleri katıştırılamıyor. + '{1}' özniteliği eksik olduğundan '{0}' derlemesinden birlikte çalışma türleri katıştırılamıyor. @@ -7953,27 +7997,27 @@ Cannot embed interop types from assembly '{0}' because it is missing either the '{1}' attribute or the '{2}' attribute. - {1}' veya '{2}' özniteliği eksik olduğundan '{0}' derlemesinden birlikte çalışma türleri katıştırılamıyor. + '{1}' veya '{2}' özniteliği eksik olduğundan '{0}' derlemesinden birlikte çalışma türleri katıştırılamıyor. Interface '{0}' has an invalid source interface which is required to embed event '{1}'. - {0}' arabiriminde '{1}' olayını katıştırmak için gereken geçersiz bir kaynak arabirimi var. + '{0}' arabiriminde '{1}' olayını katıştırmak için gereken geçersiz bir kaynak arabirimi var. Source interface '{0}' is missing method '{1}', which is required to embed event '{2}'. - {0}' kaynak arabirimde, '{2}' olayını eklemek için gereken '{1}' yöntemi eksik. + '{0}' kaynak arabirimde, '{2}' olayını eklemek için gereken '{1}' yöntemi eksik. Nested type '{0}' cannot be embedded. - {0}' iç içe türü eklenemiyor. + '{0}' iç içe türü eklenemiyor. Embedding the interop type '{0}' from assembly '{1}' causes a name clash in the current assembly. Consider disabling the embedding of interop types. - {1}' derlemesinden '{0}' birlikte çalışma türünün eklenmesi geçerli derlemede ad çakışmasına neden oluyor. Birlikte çalışma türlerini ekleme işlemini devre dışı bırakabilirsiniz. + '{1}' derlemesinden '{0}' birlikte çalışma türünün eklenmesi geçerli derlemede ad çakışmasına neden oluyor. Birlikte çalışma türlerini ekleme işlemini devre dışı bırakabilirsiniz. @@ -8153,7 +8197,7 @@ Security attribute '{0}' cannot be applied to an Async or Iterator method. - {0}' güvenlik özniteliği Zaman Uyumsuz veya Yineleyici bir yönteme uygulanamaz. + '{0}' güvenlik özniteliği Zaman Uyumsuz veya Yineleyici bir yönteme uygulanamaz. @@ -8198,7 +8242,7 @@ Event '{0}' cannot implement a Windows Runtime event '{1}' and a regular .NET event '{2}' - {0}' olayı '{1}' Windows Çalışma Zamanı olayını ve normal '{2}' .NET olayını uygulayamaz + '{0}' olayı '{1}' Windows Çalışma Zamanı olayını ve normal '{2}' .NET olayını uygulayamaz @@ -8258,7 +8302,7 @@ The AddHandler for Windows Runtime event '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement? - {0}' AddHandler for Windows Runtime olayı tüm kod yollarında değer döndürmüyor. 'Return' deyiminiz eksik olabilir mi? + '{0}' AddHandler for Windows Runtime olayı tüm kod yollarında değer döndürmüyor. 'Return' deyiminiz eksik olabilir mi? @@ -8268,17 +8312,17 @@ Optional parameter of a method '{0}' does not have the same default value as the corresponding parameter of the partial method '{1}'. - {0}' yönteminin isteğe bağlı parametresinin varsayılan değeri, '{1}' kısmi yönteminde buna karşılık gelen parametreninkiyle aynı değil. + '{0}' yönteminin isteğe bağlı parametresinin varsayılan değeri, '{1}' kısmi yönteminde buna karşılık gelen parametreninkiyle aynı değil. Parameter of a method '{0}' differs by ParamArray modifier from the corresponding parameter of the partial method '{1}'. - {0}' yönteminin parametresinin ParamArray değiştiricisi, '{1}' kısmi yönteminde buna karşılık gelen parametreninkinden farklı. + '{0}' yönteminin parametresinin ParamArray değiştiricisi, '{1}' kısmi yönteminde buna karşılık gelen parametreninkinden farklı. Module name '{0}' stored in '{1}' must match its filename. - {1}' öğesinde depolanan '{0}' modül adı dosya adıyla eşleşmelidir. + '{1}' öğesinde depolanan '{0}' modül adı dosya adıyla eşleşmelidir. @@ -8288,7 +8332,7 @@ Attribute '{0}' from module '{1}' will be ignored in favor of the instance appearing in source. - {1}' modülünde '{0}' özniteliği yoksayılacak, bunun yerine kaynakta gösterilen örnek kullanılacak. + '{1}' modülünde '{0}' özniteliği yoksayılacak, bunun yerine kaynakta gösterilen örnek kullanılacak. @@ -8303,7 +8347,7 @@ Referenced assembly '{0}' does not have a strong name. - {0}' başvurulan derlemesinin güçlü bir adı yok. + '{0}' başvurulan derlemesinin güçlü bir adı yok. @@ -8318,22 +8362,22 @@ Type '{0}' conflicts with public type defined in added module '{1}'. - {0}' türü, eklenen '{1}' modülünde tanımlanan genel türle çakışıyor. + '{0}' türü, eklenen '{1}' modülünde tanımlanan genel türle çakışıyor. Type '{0}' exported from module '{1}' conflicts with type declared in primary module of this assembly. - {1}' modülünden dışarı aktarılan '{0}' türü, bu derlemenin birinci modülünde ifade edilen tür ile çakışıyor. + '{1}' modülünden dışarı aktarılan '{0}' türü, bu derlemenin birinci modülünde ifade edilen tür ile çakışıyor. Type '{0}' exported from module '{1}' conflicts with type '{2}' exported from module '{3}'. - {1}' modülünden dışarı aktarılan '{0}' türü, '{3}' modülünden dışarı aktarılan '{2}' türü ile çakışıyor. + '{1}' modülünden dışarı aktarılan '{0}' türü, '{3}' modülünden dışarı aktarılan '{2}' türü ile çakışıyor. Referenced assembly '{0}' has different culture setting of '{1}'. - {0}' başvurulan derlemesinin '{1}' için farklı kültür ayarı var. + '{0}' başvurulan derlemesinin '{1}' için farklı kültür ayarı var. @@ -8353,7 +8397,7 @@ Referenced assembly '{0}' targets a different processor. - {0}' başvurulan derlemesi farklı bir işlemciyi hedef alır. + '{0}' başvurulan derlemesi farklı bir işlemciyi hedef alır. @@ -8373,37 +8417,37 @@ Forwarded type '{0}' conflicts with type declared in primary module of this assembly. - {0}' iletilen türü bu derlemenin birincil modülünde ifade edilen türle çakışıyor. + '{0}' iletilen türü bu derlemenin birincil modülünde ifade edilen türle çakışıyor. Type '{0}' forwarded to assembly '{1}' conflicts with type '{2}' forwarded to assembly '{3}'. - {1}' derlemesine iletilen '{0}' türü, '{3}' derlemesine iletilen '{2}' türü ile çakışıyor. + '{1}' derlemesine iletilen '{0}' türü, '{3}' derlemesine iletilen '{2}' türü ile çakışıyor. Name '{0}' exceeds the maximum length allowed in metadata. - {0}' adı, meta verilerde izin verilen maksimum uzunluğu aşıyor. + '{0}' adı, meta verilerde izin verilen maksimum uzunluğu aşıyor. Reference to '{0}' netmodule missing. - {0}' netmodule başvurusu eksik. + '{0}' netmodule başvurusu eksik. Module '{0}' is already defined in this assembly. Each module must have a unique filename. - {0}' modülü bu derlemeden zaten tanımlanmış. Her modülün benzersiz bir dosya adı olmalıdır. + '{0}' modülü bu derlemeden zaten tanımlanmış. Her modülün benzersiz bir dosya adı olmalıdır. Type '{0}' forwarded to assembly '{1}' conflicts with type '{2}' exported from module '{3}'. - {1}' derlemesine iletilen '{0}' türü '{3}' modülünden dışarı aktarılan '{2}' türü ile çakışıyor. + '{1}' derlemesine iletilen '{0}' türü '{3}' modülünden dışarı aktarılan '{2}' türü ile çakışıyor. Adding assembly reference '{0}' - {0}' derleme başvurusu ekleniyor + '{0}' derleme başvurusu ekleniyor @@ -8413,12 +8457,12 @@ Adding module reference '{0}' - {0}' modül başvurusu ekleniyor + '{0}' modül başvurusu ekleniyor Type '{0}' does not inherit the generic type parameters of its container. - {0}' türü kapsayıcısı olarak genel türdeki parametreleri devralmıyor. + '{0}' türü kapsayıcısı olarak genel türdeki parametreleri devralmıyor. @@ -8623,7 +8667,7 @@ Local name '{0}' is too long for PDB. Consider shortening or compiling without /debug. - {0}' yerel adı PDB için çok uzun. Kısaltmayı veya /debug olmadan derlemeyi deneyin. + '{0}' yerel adı PDB için çok uzun. Kısaltmayı veya /debug olmadan derlemeyi deneyin. @@ -8633,7 +8677,7 @@ Import string '{0}' is too long for PDB. Consider shortening or compiling without /debug. - {0}' içeri aktarma dizesi PDB için fazla uzun. Kısaltabilir veya /debug olmadan derleyebilirsiniz. + '{0}' içeri aktarma dizesi PDB için fazla uzun. Kısaltabilir veya /debug olmadan derleyebilirsiniz. @@ -8723,7 +8767,7 @@ Preprocessor constant '{0}' of type '{1}' is not supported, only primitive types are allowed. - {1}' türündeki '{0}' ön işlemci sabiti desteklenmiyor; yalnızca temel türlere izin verilir. + '{1}' türündeki '{0}' ön işlemci sabiti desteklenmiyor; yalnızca temel türlere izin verilir. @@ -8818,7 +8862,7 @@ Error reading debug information for '{0}' - {0}' için hata ayıklama bilgileri okunurken hata oluştu + '{0}' için hata ayıklama bilgileri okunurken hata oluştu @@ -8983,7 +9027,7 @@ Option '{0}' must be an absolute path. - {0}' seçeneği mutlak yol olmalıdır. + '{0}' seçeneği mutlak yol olmalıdır. @@ -8998,7 +9042,7 @@ The tuple element name '{0}' is ignored because a different name or no name is specified by the target type '{1}'. - {0}' demet öğesi adı, hedef tür olan '{1}' tarafından farklı bir ad belirtildiği veya hiçbir ad belirtilmediği için yoksayılıyor. + '{0}' demet öğesi adı, hedef tür olan '{1}' tarafından farklı bir ad belirtildiği veya hiçbir ad belirtilmediği için yoksayılıyor. @@ -9008,12 +9052,12 @@ Tuple element name '{0}' is only allowed at position {1}. - {0}' demet öğesi adına yalnızca {1} konumunda izin verilir. + '{0}' demet öğesi adına yalnızca {1} konumunda izin verilir. Tuple element name '{0}' is disallowed at any position. - {0}' demet öğesi adına hiçbir konumda izin verilmez. + '{0}' demet öğesi adına hiçbir konumda izin verilmez. @@ -9023,7 +9067,7 @@ Cannot define a class or member that utilizes tuples because the compiler required type '{0}' cannot be found. Are you missing a reference? - {0}' türünü gerektiren derleyici bulunamadığından demetleri kullanan sınıf veya üye tanımlanamıyor. Bir başvuru eksik olabilir mi? + '{0}' türünü gerektiren derleyici bulunamadığından demetleri kullanan sınıf veya üye tanımlanamıyor. Bir başvuru eksik olabilir mi? @@ -9058,7 +9102,7 @@ Module '{0}' in assembly '{1}' is forwarding the type '{2}' to multiple assemblies: '{3}' and '{4}'. - {1}' bütünleştirilmiş kodundaki '{0}' modülü, '{2}' türünü birden çok bütünleştirilmiş koda iletiyor: '{3}' ve '{4}'. + '{1}' bütünleştirilmiş kodundaki '{0}' modülü, '{2}' türünü birden çok bütünleştirilmiş koda iletiyor: '{3}' ve '{4}'. @@ -9078,7 +9122,7 @@ Named argument '{0}' is used out-of-position but is followed by an unnamed argument - {0}' adlandırılmış bağımsız değişkeni, pozisyonu dışında kullanıldı ancak ardından adlandırılmamış bir bağımsız değişken geliyor + '{0}' adlandırılmış bağımsız değişkeni, pozisyonu dışında kullanıldı ancak ardından adlandırılmamış bir bağımsız değişken geliyor @@ -9098,7 +9142,7 @@ Tuple element name '{0}' is inferred. Please use language version {1} or greater to access an element by its inferred name. - {0}' demet öğesi adı çıkarsandı. Bir öğeye çıkarsanan adıyla erişmek için lütfen {1} veya üzeri dil sürümünü kullanın. + '{0}' demet öğesi adı çıkarsandı. Bir öğeye çıkarsanan adıyla erişmek için lütfen {1} veya üzeri dil sürümünü kullanın. @@ -9113,7 +9157,7 @@ Unable to read debug information of method '{0}' (token 0x{1}) from assembly '{2}' - {2}' bütünleştirilmiş kodundan '{0}' (simge 0 x{1}) metodunun hata ayıklama bilgileri okunamıyor + '{2}' bütünleştirilmiş kodundan '{0}' (simge 0 x{1}) metodunun hata ayıklama bilgileri okunamıyor diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.zh-Hans.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.zh-Hans.xlf index eada1fbfd36fd..a2d19a6339d01 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.zh-Hans.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Command-line syntax error: '{0}' is not a valid value for the '{1}' option. The value must be of the form '{2}'. @@ -212,169 +212,169 @@ -vbruntime:<file> Compile with the alternate Visual Basic runtime in <file>. - Visual Basic Compiler Options + Visual Basic 编译器选项 - - OUTPUT FILE - --out:<file> Specifies the output file name. --target:exe Create a console application (default). - (Short form: -t) --target:winexe Create a Windows application. --target:library Create a library assembly. --target:module Create a module that can be added to an - assembly. --target:appcontainerexe Create a Windows application that runs in - AppContainer. --target:winmdobj Create a Windows Metadata intermediate file --doc[+|-] Generates XML documentation file. --doc:<file> Generates XML documentation file to <file>. --refout:<file> Reference assembly output to generate + - 输出文件 - +-out:<file> 指定输出文件名称。 +-target:exe 创建控制台应用程序(默认)。 + (缩写: -t) +-target:winexe 创建 Windows 应用程序。 +-target:library 创建库程序集。 +-target:module 创建可添加到程序集的 + 模块。 +-target:appcontainerexe 创建在 AppContainer 中运行的 + Windows 应用程序。 +-target:winmdobj 创建 Windows 元数据中间文件 +-doc[+|-] 生成 XML 文档文件。 +-doc:<file> 将 XML 文档文件生成到 <file> +-refout:<file> 引用要生成的引用程序集 - - INPUT FILES - --addmodule:<file_list> Reference metadata from the specified modules --link:<file_list> Embed metadata from the specified interop - assembly. (Short form: -l) --recurse:<wildcard> Include all files in the current directory - and subdirectories according to the - wildcard specifications. --reference:<file_list> Reference metadata from the specified - assembly. (Short form: -r) --analyzer:<file_list> Run the analyzers from this assembly - (Short form: -a) --additionalfile:<file list> Additional files that don't directly affect code - generation but may be used by analyzers for producing - errors or warnings. + - 输入文件 - +-addmodule:<file_list> 从指定模块中引用元数据 +-link:<file_list> 嵌入指定互操作程序集中的 + 元数据。(缩写: -l) +-recurse:<wildcard> 根据通配符规范包括 + 当前目录和子目录中 + 的所有文件。 +-reference:<file_list> 从指定程序集中引用 + 元数据。(缩写: -r) +-analyzer:<file_list> 运行此程序集的分析器 + (缩写: -a) +-additionalfile:<file list> 不直接影响代码 + 生成但可能被分析器用于生成 + 错误或警告的其他文件。 - - RESOURCES - --linkresource:<resinfo> Links the specified file as an external - assembly resource. + - 资源 - +-linkresource:<resinfo> 将指定文件作为外部 + 程序集资源进行链接。 resinfo:<file>[,<name>[,public|private]] - (Short form: -linkres) --nowin32manifest The default manifest should not be embedded - in the manifest section of the output PE. --resource:<resinfo> Adds the specified file as an embedded - assembly resource. + (缩写: -linkres) +-nowin32manifest 默认清单不应嵌入 + 输出 PE 的清单部分。 +-resource:<resinfo> 将指定文件作为嵌入式 + 程序集资源进行添加。 resinfo:<file>[,<name>[,public|private]] - (Short form: -res) --win32icon:<file> Specifies a Win32 icon file (.ico) for the - default Win32 resources. --win32manifest:<file> The provided file is embedded in the manifest - section of the output PE. --win32resource:<file> Specifies a Win32 resource file (.res). + (缩写: -res) +-win32icon:<file> 为默认的 Win32 资源 + 指定 Win32 图标文件(.ico)。 +-win32manifest:<file> 提供的文件嵌入在 + 输出 PE 的清单部分。 +-win32resource:<file> 指定 Win32 资源文件(.res)。 - - CODE GENERATION - --optimize[+|-] Enable optimizations. --removeintchecks[+|-] Remove integer checks. Default off. --debug[+|-] Emit debugging information. --debug:full Emit full debugging information (default). --debug:pdbonly Emit full debugging information. --debug:portable Emit cross-platform debugging information. --debug:embedded Emit cross-platform debugging information into - the target .dll or .exe. --deterministic Produce a deterministic assembly - (including module version GUID and timestamp) --refonly Produce a reference assembly in place of the main output --instrument:TestCoverage Produce an assembly instrumented to collect - coverage information --sourcelink:<file> Source link info to embed into PDB. + - 代码生成 - +-optimize[+|-] 启用优化。 +-removeintchecks[+|-] 删除整数检查。默认为“关”。 +-debug[+|-] 发出调试信息。 +-debug:full 发出完全调试信息(默认)。 +-debug:pdbonly 发出完全调试信息。 +-debug:portable 发出跨平台调试信息。 +-debug:embedded 发出跨平台调试信息到 + 目标 .dll 或 .exe. +-deterministic 生成确定性程序集 + (包括模块版本 GUID 和时间戳) +-refonly 生成引用程序集来替代主要输出 +-instrument:TestCoverage 生成对其检测以收集覆盖率信息的t + 程序集 +-sourcelink:<file> 要嵌入到 PDB 中的源链接信息。 - - ERRORS AND WARNINGS - --nowarn Disable all warnings. --nowarn:<number_list> Disable a list of individual warnings. --warnaserror[+|-] Treat all warnings as errors. --warnaserror[+|-]:<number_list> Treat a list of warnings as errors. --ruleset:<file> Specify a ruleset file that disables specific - diagnostics. + - 错误和警告 - +-nowarn 禁用所有警告。 +-nowarn:<number_list> 禁用个人警告列表。 +-warnaserror[+|-] 将所有警告视为错误。 +-warnaserror[+|-]:<number_list> 将警告列表视为错误。 +-ruleset:<file> 指定禁用特定诊断的 + 规则集文件。 -errorlog:<file>[,version=<sarif_version>] - Specify a file to log all compiler and analyzer - diagnostics in SARIF format. - sarif_version:{1|2|2.1} Default is 1. 2 and 2.1 - both mean SARIF version 2.1.0. --reportanalyzer Report additional analyzer information, such as - execution time. --skipanalyzers[+|-] Skip execution of diagnostic analyzers. + 指定用于以 SARIF 格式记录所有编译器和分析器诊断的 + 文件。 + sarif_version:{1|2|2.1} 默认为 1. 2 和 2.1 + 两者均表示 SARIF 版本 2.1.0。 +-reportanalyzer 报告其他分析器信息,如 + 执行时间。 +-skipanalyzers[+|-] 跳过诊断分析器的执行。 + - 语言 - - - LANGUAGE - --define:<symbol_list> Declare global conditional compilation - symbol(s). symbol_list:name=value,... - (Short form: -d) --imports:<import_list> Declare global Imports for namespaces in - referenced metadata files. +-define:<symbol_list> 声明全局条件编译 + 符号。symbol_list:name=value,... + (缩写: -d) +-imports:<import_list> 为引用的元数据文件中的命名空间声明 + 全局导入。 import_list:namespace,... --langversion:? Display the allowed values for language version --langversion:<string> Specify language version such as - `default` (latest major version), or - `latest` (latest version, including minor versions), - or specific versions like `14` or `15.3` --optionexplicit[+|-] Require explicit declaration of variables. --optioninfer[+|-] Allow type inference of variables. --rootnamespace:<string> Specifies the root Namespace for all type - declarations. --optionstrict[+|-] Enforce strict language semantics. --optionstrict:custom Warn when strict language semantics are not - respected. --optioncompare:binary Specifies binary-style string comparisons. - This is the default. --optioncompare:text Specifies text-style string comparisons. +-langversion:? 显示允许的语言版本值 +-langversion:<string> 指定语言版本,如 + “default” (最新主要版本)、 + “latest” (最新版本,包括次要版本) + 或 “14”、”15.3”等特定版本 +-optionexplicit[+|-] 需要显示声明变量。 +-optioninfer[+|-] 允许变量的类型推理。 +-rootnamespace:<string> 指定所有类型声明的根 + 命名空间。 +-optionstrict[+|-] 强制严格语言语义。 +-optionstrict:custom 不遵从严格语言语义时 + 发出警告。 +-optioncompare:binary 指定二进制样式的字符串比较。 + 这是默认设置。 +-optioncompare:text 指定文本样式字符串比较。 - - MISCELLANEOUS - --help Display this usage message. (Short form: -?) --noconfig Do not auto-include VBC.RSP file. --nologo Do not display compiler copyright banner. --quiet Quiet output mode. --verbose Display verbose messages. --parallel[+|-] Concurrent build. --version Display the compiler version number and exit. + - 杂项 - +-help 显示此用法消息。(缩写: -?) +-noconfig 不自动包括 VBC.RSP 文件。 +-nologo 不显示编译器版权横幅。 +-quiet 安静输出模式。 +-verbose 显示详细消息。 +-parallel[+|-] 并发生成。 +-version 显示编译器版本号并退出。 - - ADVANCED - --baseaddress:<number> The base address for a library or module - (hex). --checksumalgorithm:<alg> Specify algorithm for calculating source file - checksum stored in PDB. Supported values are: - SHA1 or SHA256 (default). --codepage:<number> Specifies the codepage to use when opening - source files. --delaysign[+|-] Delay-sign the assembly using only the public - portion of the strong name key. --publicsign[+|-] Public-sign the assembly using only the public - portion of the strong name key. --errorreport:<string> Specifies how to handle internal compiler - errors; must be prompt, send, none, or queue - (default). --filealign:<number> Specify the alignment used for output file - sections. --highentropyva[+|-] Enable high-entropy ASLR. --keycontainer:<string> Specifies a strong name key container. --keyfile:<file> Specifies a strong name key file. --libpath:<path_list> List of directories to search for metadata - references. (Semi-colon delimited.) --main:<class> Specifies the Class or Module that contains - Sub Main. It can also be a Class that - inherits from System.Windows.Forms.Form. - (Short form: -m) --moduleassemblyname:<string> Name of the assembly which this module will - be a part of. --netcf Target the .NET Compact Framework. --nostdlib Do not reference standard libraries - (system.dll and VBC.RSP file). + - 高级 - +-baseaddress:<number> 库或模块的基址 + (十六进制)。 +-checksumalgorithm:<alg> 指定计算存储在 PDB 中的源文件校验和 + 的算法。支持的值是: + SHA1 或 SHA256 (默认)。 +-codepage:<number> 指定打开源文件时要使用的 + 代码页。 +-delaysign[+|-] 仅使用强名称密钥的公共部分 + 对程序集进行延迟签名。 +-publicsign[+|-] 仅使用强名称密钥的公共部分 + 对程序集进行公共签名 +-errorreport:<string> 指定处理内部编译器错误的方式; + 必须是 prompt、send、none 或 queue + (默认)。 +-filealign:<number> 指定用于输出文件节的对齐 + 方式。 +-highentropyva[+|-] 启用高平均信息量的 ASLR。 +-keycontainer:<string> 指定强名称密钥容器。 +-keyfile:<file> 指定强名称密钥文件。 +-libpath:<path_list> 搜索元数据引用的目录 + 列表。(分号分隔。) +-main:<class> 指定包含 Sub Main 的类 + 或模块。也可为从 + System.Windows.Forms.Form 继承的类。 + (缩写: -m) +-moduleassemblyname:<string> 此模块所属程序集 + 的名称。 +-netcf 以 .NET Compact Framework 为目标。 +-nostdlib 不引用标准库 + (system.dll 和 VBC.RSP 文件)。 -pathmap:<K1>=<V1>,<K2>=<V2>,... - Specify a mapping for source path names output by - the compiler. --platform:<string> Limit which platforms this code can run on; - must be x86, x64, Itanium, arm, arm64 - AnyCPU32BitPreferred or anycpu (default). --preferreduilang Specify the preferred output language name. --nosdkpath Disable searching the default SDK path for standard library assemblies. --sdkpath:<path> Location of the .NET Framework SDK directory + 按编译器指定源路径名称输出的 + 映射。 +-platform:<string> 限制此代码可以在其上运行的平台; + 必须是 x86、x64、Itanium、arm、arm64、 + AnyCPU32BitPreferred 或 anycpu (默认)。 +-preferreduilang 指定首选输出语言名称。 +-nosdkpath 禁用搜索标准库程序集的默认 SDK 路径 +-sdkpath:<path> .NET Framework SDK 目录的位置 (mscorlib.dll). --subsystemversion:<version> Specify subsystem version of the output PE. +-subsystemversion:<version> 指定输出 PE 的子系统版本。 version:<number>[.<number>] --utf8output[+|-] Emit compiler output in UTF8 character - encoding. -@<file> Insert command-line settings from a text file --vbruntime[+|-|*] Compile with/without the default Visual Basic - runtime. --vbruntime:<file> Compile with the alternate Visual Basic - runtime in <file>. +-utf8output[+|-] 以 UTF8 字符编码格式 + 发出编译器输出。 +@<file> 从文本文件插入命令行设置 +-vbruntime[+|-|*] 用/不用默认的 Visual Basic + 运行时进行编译。 +-vbruntime:<file> 使用 <file> 中的备用 Visual Basic 运行时 + 进行编译。 @@ -420,7 +420,7 @@ SyntaxTree '{0}' not found to remove - 未找到要删除的 SyntaxTree“{0}”。 + 未找到要删除的 SyntaxTree“{0}” @@ -463,6 +463,50 @@ 类型参数不能是任何内容 + + The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + 包含类型“{1}”的程序集“{0}”引用了 .NET Framework,而此操作不受支持。 + {1} is the type that was loaded, {0} is the containing assembly. + + + The loaded assembly references .NET Framework, which is not supported. + 加载的程序集引用了 .NET Framework,而此操作不受支持。 + + + + Generator '{0}' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + 生成器“{0}”未能生成源。它不会影响输出,因此可能会造成编译错误。异常的类型为“{1}”,显示消息“{2}” + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + 生成器引发以下异常: +“{0}”。 + {0} is the string representation of the exception that was thrown. + + + Generator failed to generate source. + 生成器无法生成源。 + + + + Generator '{0}' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + 生成器“{0}”未能初始化。它不会影响输出,因此可能会造成编译错误。异常的类型为“{1}”,显示消息“{2}” + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + 生成器引发以下异常: +“{0}”。 + {0} is the string representation of the exception that was thrown. + + + Generator failed to initialize. + 生成器初始化失败。 + + Wrong number of type arguments 类型参数的数目不正确 @@ -470,7 +514,7 @@ file '{0}' could not be found - 找不到文件“{0}”。 + 找不到文件“{0}” @@ -615,7 +659,7 @@ '{0}' is not a valid value for /moduleassemblyname - '“{0}”不是 /moduleassemblyname 的有效值。 + “{0}”不是 /moduleassemblyname 的有效值 @@ -815,12 +859,12 @@ '{0}' is valid only within an instance method. - '“{0}”仅在实例方法中有效。 + “{0}”仅在实例方法中有效。 '{0}' is not valid within a structure. - '“{0}”在结构中无效。 + “{0}”在结构中无效。 @@ -835,7 +879,7 @@ '{0}' statement requires an array. - '“{0}”语句需要数组。 + “{0}”语句需要数组。 @@ -1055,42 +1099,42 @@ '{0}' is an Enum type and cannot be used as an expression. - '“{0}”是一个枚举类型,不能用作表达式。 + “{0}”是一个枚举类型,不能用作表达式。 '{0}' is a type and cannot be used as an expression. - '“{0}”是一个类型,不能用作表达式。 + “{0}”是一个类型,不能用作表达式。 '{0}' is a class type and cannot be used as an expression. - '“{0}”是一个类类型,不能用作表达式。 + “{0}”是一个类类型,不能用作表达式。 '{0}' is a structure type and cannot be used as an expression. - '“{0}”是一个结构类型,不能用作表达式。 + “{0}”是一个结构类型,不能用作表达式。 '{0}' is an interface type and cannot be used as an expression. - '“{0}”是一个接口类型,不能用作表达式。 + “{0}”是一个接口类型,不能用作表达式。 '{0}' is a namespace and cannot be used as an expression. - '“{0}”是一个命名空间,不能用作表达式。 + “{0}”是一个命名空间,不能用作表达式。 '{0}' is not a valid name and cannot be used as the root namespace name. - '“{0}”不是有效名称,不能用作根命名空间名称。 + “{0}”不是有效名称,不能用作根命名空间名称。 '{0}' is an XML prefix and cannot be used as an expression. Use the GetXmlNamespace operator to create a namespace object. - '“{0}”是 XML 前缀,不能用作表达式。请使用 GetXmlNamespace 运算符创建命名空间对象。 + “{0}”是 XML 前缀,不能用作表达式。请使用 GetXmlNamespace 运算符创建命名空间对象。 @@ -1350,17 +1394,17 @@ '{0}' is not valid on a constant declaration. - '“{0}”在常量声明中无效。 + “{0}”在常量声明中无效。 '{0}' is not valid on a WithEvents declaration. - '“{0}”在 WithEvents 声明中无效。 + “{0}”在 WithEvents 声明中无效。 '{0}' is not valid on a member variable declaration. - '“{0}”在成员变量声明中无效。 + “{0}”在成员变量声明中无效。 @@ -1400,27 +1444,27 @@ '{0}' is not valid on a method declaration. - '“{0}”在方法声明中无效。 + “{0}”在方法声明中无效。 '{0}' is not valid on an event declaration. - '“{0}”在事件声明中无效。 + “{0}”在事件声明中无效。 '{0}' is not valid on a Declare. - '“{0}”在 Declare 中无效。 + “{0}”在 Declare 中无效。 '{0}' is not valid on a local constant declaration. - '“{0}”在局部常量声明中无效。 + “{0}”在局部常量声明中无效。 '{0}' is not valid on a local variable declaration. - '“{0}”在局部变量声明中无效。 + “{0}”在局部变量声明中无效。 @@ -1474,42 +1518,42 @@ '{0}' is already declared as '{1}' in this {2}. - '“{0}”已在此 {2} 中声明为“{1}”。 + “{0}”已在此 {2} 中声明为“{1}”。 '{0}' cannot override '{1}' because they have different access levels. - '“{0}”无法重写“{1}”,因为它们具有不同的访问级别。 + “{0}”无法重写“{1}”,因为它们具有不同的访问级别。 '{0}' cannot override '{1}' because it is declared 'NotOverridable'. - '“{0}”无法重写“{1}”,因为后者已声明为“NotOverridable”。 + “{0}”无法重写“{1}”,因为后者已声明为“NotOverridable”。 '{0}' has multiple definitions with identical signatures. - '“{0}”具有多个带相同签名的定义。 + “{0}”具有多个带相同签名的定义。 '{0}' has multiple definitions with identical signatures with different tuple element names, including '{1}'. - '“{0}”具有多个带不同元组元素名称却有相同签名的定义,包括“{1}”。 + “{0}”具有多个带不同元组元素名称却有相同签名的定义,包括“{1}”。 '{0}' is not valid on an interface method declaration. - '“{0}”在接口方法声明中无效。 + “{0}”在接口方法声明中无效。 '{0}' is not a parameter of '{1}'. - '“{0}”不是“{1}”的参数。 + “{0}”不是“{1}”的参数。 '{0}' is not valid on an interface property declaration. - '“{0}”在接口属性声明中无效。 + “{0}”在接口属性声明中无效。 @@ -1519,7 +1563,7 @@ '{0}' is not valid on an interface event declaration. - '“{0}”在接口事件声明中无效。 + “{0}”在接口事件声明中无效。 @@ -1618,17 +1662,17 @@ '{0}' cannot inherit from {2} '{1}' because '{1}' is declared 'NotInheritable'. - '“{1}”已声明为“NotInheritable”,因此“{0}”无法从 {2}“{1}”继承。 + “{1}”已声明为“NotInheritable”,因此“{0}”无法从 {2}“{1}”继承。 '{0}' and '{1}' cannot overload each other because they differ only by optional parameters. - '“{0}” 和“{1}”的差异仅在于可选参数,因此它们无法重载对方。 + “{0}” 和“{1}”的差异仅在于可选参数,因此它们无法重载对方。 '{0}' and '{1}' cannot overload each other because they differ only by return types. - '“{0}”和“{1}”的差异仅在于返回类型,因此它们无法重载对方。 + “{0}”和“{1}”的差异仅在于返回类型,因此它们无法重载对方。 @@ -1643,7 +1687,7 @@ '{0}' and '{1}' cannot overload each other because they differ only by the default values of optional parameters. - '“{0}”和“{1}”的差异仅在于可选参数的默认值,因此它们无法重载对方。 + “{0}”和“{1}”的差异仅在于可选参数的默认值,因此它们无法重载对方。 @@ -1653,12 +1697,12 @@ '{0}' cannot override '{1}' because they differ by the default values of optional parameters. - '“{0}”无法重写“{1}”,因为它们在可选参数的默认值上存在差异。 + “{0}”无法重写“{1}”,因为它们在可选参数的默认值上存在差异。 '{0}' cannot override '{1}' because they differ by optional parameters. - '“{0}”无法重写“{1}”,因为它们在可选参数上存在差异。 + “{0}”无法重写“{1}”,因为它们在可选参数上存在差异。 @@ -1693,7 +1737,7 @@ '{0}' and '{1}' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'. - '“{0}”和“{1}”的差异仅在于声明为“ByRef”或“ByVal”的参数,因此它们无法重载对方。 + “{0}”和“{1}”的差异仅在于声明为“ByRef”或“ByVal”的参数,因此它们无法重载对方。 @@ -1713,12 +1757,12 @@ '{0}' and '{1}' cannot overload each other because only one is declared 'Default'. - '“{0}”和“{1}”中只有一个声明为“Default”,因此它们无法相互重载。 + “{0}”和“{1}”中只有一个声明为“Default”,因此它们无法相互重载。 '{0}' cannot override '{1}' because they differ by 'ReadOnly' or 'WriteOnly'. - '“{0}”无法重写“{1}”,因为它们在是“ReadOnly”还是“WriteOnly”上不同。 + “{0}”无法重写“{1}”,因为它们在是“ReadOnly”还是“WriteOnly”上不同。 @@ -1733,7 +1777,7 @@ '{0}' and '{1}' cannot overload each other because they differ only by 'ReadOnly' or 'WriteOnly'. - '“{0}” 和“{1}”的差异仅在于“ReadOnly”和“WriteOnly”,因此它们无法重载对方。 + “{0}” 和“{1}”的差异仅在于“ReadOnly”和“WriteOnly”,因此它们无法重载对方。 @@ -1798,7 +1842,7 @@ '{0}' is not valid on a Delegate declaration. - '“{0}”在委托声明中无效。 + “{0}”在委托声明中无效。 @@ -1808,12 +1852,12 @@ '{0}' is not accessible in this context because it is '{1}'. - '“{0}”是“{1}”,因此它在此上下文中不可访问。 + “{0}”是“{1}”,因此它在此上下文中不可访问。 '{0}.{1}' is not accessible in this context because it is '{2}'. - '“{0}.{1}”是“{2}” ,因此它在此上下文中不可访问。 + “{0}.{1}”是“{2}” ,因此它在此上下文中不可访问。 @@ -1828,22 +1872,22 @@ '{0}' is not valid on a Structure declaration. - '“{0}”在结构声明中无效。 + “{0}”在结构声明中无效。 '{0}' is not valid on an Enum declaration. - '“{0}”在枚举声明中无效。 + “{0}”在枚举声明中无效。 '{0}' is not valid on an Interface declaration. - '“{0}”在接口声明中无效。 + “{0}”在接口声明中无效。 '{0}' cannot override '{1}' because they differ by a parameter that is marked as 'ByRef' versus 'ByVal'. - '“{0}”无法重写“{1}”,因为它们在某个参数上存在差异,一个被标记为“ByRef”,而另一个被标记为“ByVal”。 + “{0}”无法重写“{1}”,因为它们在某个参数上存在差异,一个被标记为“ByRef”,而另一个被标记为“ByVal”。 @@ -1853,12 +1897,12 @@ '{0}' cannot implement '{1}' because there is no matching {2} on interface '{3}'. - '“{0}”无法实现“{1}”,因为接口“{3}”上不存在匹配的 {2}。 + “{0}”无法实现“{1}”,因为接口“{3}”上不存在匹配的 {2}。 '{0}' cannot implement {1} '{2}' on interface '{3}' because the tuple element names in '{4}' do not match those in '{5}'. - '“{0}”不能在接口“{3}”上实现{1}“{2}”,因为“{4}”中的元组元素名称与“{5}”中的名称不匹配。 + “{0}”不能在接口“{3}”上实现{1}“{2}”,因为“{4}”中的元组元素名称与“{5}”中的名称不匹配。 @@ -1883,7 +1927,7 @@ 'Sub Main' was not found in '{0}'. - '“{0}”中找不到“Sub Main”。 + “{0}”中找不到“Sub Main”。 @@ -1923,12 +1967,12 @@ '{0}' cannot override '{1}' because they differ by their return types. - '“{0}”无法重写“{1}”,因为它们的返回类型不同。 + “{0}”无法重写“{1}”,因为它们的返回类型不同。 '{0}' cannot override '{1}' because they differ by their tuple element names. - '“{0}”不能替代“{1}”,因为它们的元组元素名称不同。 + “{0}”不能替代“{1}”,因为它们的元组元素名称不同。 @@ -1978,7 +2022,7 @@ '{0}' is not a member of '{1}'. - '“{0}”不是“{1}”的成员。 + “{0}”不是“{1}”的成员。 @@ -2103,7 +2147,7 @@ '{0}' cannot inherit from {1} '{2}' because it expands the access of the base {1} to {3} '{4}'. - '“{0}”将对基 {1} 的访问扩展到 {3}“{4}”,因此无法从 {1}“{2}”继承。 + “{0}”将对基 {1} 的访问扩展到 {3}“{4}”,因此无法从 {1}“{2}”继承。 @@ -2220,7 +2264,7 @@ '{0}' is ambiguous. - '“{0}”不明确。 + “{0}”不明确。 @@ -2230,22 +2274,22 @@ '{0}' is ambiguous in the namespace '{1}'. - '“{1}”在命名空间中“{0}”不明确。 + “{1}”在命名空间中“{0}”不明确。 '{0}' is ambiguous, imported from the namespaces or types '{1}'. - '“{0}”不明确,从命名空间或类型“{1}”导入。 + “{0}”不明确,从命名空间或类型“{1}”导入。 '{0}' is ambiguous between declarations in Modules '{1}'. - '“{0}”在模块“{1}”中的声明之间不明确。 + “{0}”在模块“{1}”中的声明之间不明确。 '{0}' is ambiguous between declarations in namespaces '{1}'. - '“{0}”在命名空间“{1}”中的声明之间不明确。 + “{0}”在命名空间“{1}”中的声明之间不明确。 @@ -2320,12 +2364,12 @@ '{0}.{1}' cannot be implemented more than once. - '“{0}.{1}”不能多次实现。 + “{0}.{1}”不能多次实现。 '{0}' cannot be inherited more than once. - '“{0}”不能被继承多次。 + “{0}”不能被继承多次。 @@ -2390,7 +2434,7 @@ '{0}' is a MustOverride event in the base class '{1}'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class '{2}' MustInherit. - '“{0}”是基类“{1}” 中的 MustOverride 事件。Visual Basic 不支持事件替代。必须提供基类中事件的实现或让类“{2}“成为 MustInherit。 + “{0}”是基类“{1}” 中的 MustOverride 事件。Visual Basic 不支持事件替代。必须提供基类中事件的实现或让类“{2}“成为 MustInherit。 @@ -2570,7 +2614,7 @@ '{0}' is an unsupported type. - '“{0}”是不受支持的类型。 + “{0}”是不受支持的类型。 @@ -2605,7 +2649,7 @@ '{0}' has a return type that is not supported or parameter types that are not supported. - '“{0}”有不受支持的返回类型或不受支持的参数类型。 + “{0}”有不受支持的返回类型或不受支持的参数类型。 @@ -2687,7 +2731,7 @@ '{0}' is obsolete: '{1}'. - '“{0}”已过时:“{1}”。 + “{0}”已过时:“{1}”。 @@ -2717,7 +2761,7 @@ '{0}' is not an event of '{1}'. - '“{0}”不是“{1}”的事件。 + “{0}”不是“{1}”的事件。 @@ -2752,7 +2796,7 @@ '{0}' is ambiguous across the inherited interfaces '{1}' and '{2}'. - '“{0}”在继承接口“{1}”和“{2}”之间不明确。 + “{0}”在继承接口“{1}”和“{2}”之间不明确。 @@ -2782,7 +2826,7 @@ '{0}' cannot override '{1}' because they differ by the types of optional parameters. - '“{0}”无法重写“{1}”,因为它们在可选参数类型上存在差异。 + “{0}”无法重写“{1}”,因为它们在可选参数类型上存在差异。 @@ -2802,7 +2846,7 @@ '{0}' is already declared as a parameter of this method. - '“{0}”已声明为此方法的参数。 + “{0}”已声明为此方法的参数。 @@ -2942,7 +2986,7 @@ '{1}' for the Imports alias to '{0}' does not refer to a Namespace, Class, Structure, Interface, Enum or Module. - '“{0}”的 Imports 别名的“{1}”不引用命名空间、类、结构、接口、枚举或模块。 + “{0}”的 Imports 别名的“{1}”不引用命名空间、类、结构、接口、枚举或模块。 @@ -3042,32 +3086,32 @@ '{0}' cannot expose type '{1}' outside the project through {2} '{3}'. - '“{0}”不能通过 {2}“{3}”在项目外部公开类型“{1}”。 + “{0}”不能通过 {2}“{3}”在项目外部公开类型“{1}”。 '{0}' cannot inherit from {1} '{2}' because it expands the access of the base {1} outside the assembly. - '“{0}”将对基 {1} 的访问扩展到程序集之外,因此无法从 {1}“{2}”继承。 + “{0}”将对基 {1} 的访问扩展到程序集之外,因此无法从 {1}“{2}”继承。 '{0}' accessor of '{1}' is obsolete: '{2}'. - '“{1}”的“{0}”访问器已过时:“{2}”。 + “{1}”的“{0}”访问器已过时:“{2}”。 '{0}' accessor of '{1}' is obsolete. - '“{1}”的“{0}”访问器已过时。 + “{1}”的“{0}”访问器已过时。 '{0}' cannot expose the underlying delegate type '{1}' of the event it is implementing to {2} '{3}' through {4} '{5}'. - '“{0}”不能通过 {4}“{5}”向 {2}“{3}”公开它正在实现的事件的基础委托类型“{1}”。 + “{0}”不能通过 {4}“{5}”向 {2}“{3}”公开它正在实现的事件的基础委托类型“{1}”。 '{0}' cannot expose the underlying delegate type '{1}' of the event it is implementing outside the project through {2} '{3}'. - '“{0}”不能通过 {2}“{3}”公开它正在实现的事件的基础委托类型“{1}”。 + “{0}”不能通过 {2}“{3}”公开它正在实现的事件的基础委托类型“{1}”。 @@ -3097,12 +3141,12 @@ '{0}' cannot inherit from {1} '{2}' because it expands the access of type '{3}' to {4} '{5}'. - '“{0}”将对类型“{3}”的访问扩展到{4}“{5}”,因此无法从 {1}“{2}”继承。 + “{0}”将对类型“{3}”的访问扩展到{4}“{5}”,因此无法从 {1}“{2}”继承。 '{0}' cannot inherit from {1} '{2}' because it expands the access of type '{3}' outside the assembly. - '“{0}”将对类型“{3}”的访问扩展到程序集之外,因此无法从 {1}“{2}”继承。 + “{0}”将对类型“{3}”的访问扩展到程序集之外,因此无法从 {1}“{2}”继承。 @@ -3358,7 +3402,7 @@ '{0}' exists in multiple base interfaces. Use the name of the interface that declares '{0}' in the 'Implements' clause instead of the name of the derived interface. - '“{0}”存在于多个基接口中。请使用在“Implements”子句中声明“{0}”的接口的名称,而不要使用派生接口的名称。 + “{0}”存在于多个基接口中。请使用在“Implements”子句中声明“{0}”的接口的名称,而不要使用派生接口的名称。 @@ -3508,17 +3552,17 @@ '{0}' is obsolete. - '“{0}”已过时。 + “{0}”已过时。 '{0}' is a module and cannot be referenced as an assembly. - '“{0}”是一个模块,不能作为程序集引用。 + “{0}”是一个模块,不能作为程序集引用。 '{0}' is an assembly and cannot be referenced as a module. - '“{0}”是一个程序集,不能作为模块引用。 + “{0}”是一个程序集,不能作为模块引用。 @@ -3528,7 +3572,7 @@ '{0}' is not a local variable or parameter, and so cannot be used as a 'Catch' variable. - '“{0}”不是局部变量或参数,因此不能用作“Catch”变量。 + “{0}”不是局部变量或参数,因此不能用作“Catch”变量。 @@ -3548,7 +3592,7 @@ '{0}' cannot override '{1}' because it is not declared 'Overridable'. - '“{0}”无法重写“{1}”,因为后者未声明为“Overridable”。 + “{0}”无法重写“{1}”,因为后者未声明为“Overridable”。 @@ -3788,7 +3832,7 @@ '{0}' cannot refer to itself through its default instance; use 'Me' instead. - '“{0}”不能通过其默认实例指代自身;请改用“Me”。 + “{0}”不能通过其默认实例指代自身;请改用“Me”。 @@ -3803,7 +3847,7 @@ '{0}' cannot be applied to the 'AddHandler', 'RemoveHandler', or 'RaiseEvent' definitions. If required, apply the attribute directly to the event. - '“{0}”不能应用于“'AddHandler”、“RemoveHandler”或“'RaiseEvent”定义。如有必要,请将该属性直接应用于事件。 + “{0}”不能应用于“'AddHandler”、“RemoveHandler”或“'RaiseEvent”定义。如有必要,请将该属性直接应用于事件。 @@ -4113,7 +4157,7 @@ '{0}' cannot shadow a method declared 'MustOverride'. - '“{0}”不能隐藏声明为“MustOverride”的方法。 + “{0}”不能隐藏声明为“MustOverride”的方法。 @@ -4123,7 +4167,7 @@ '{0}' and '{1}' cannot be combined. - '“{0}”不能与“{1}”组合。 + “{0}”不能与“{1}”组合。 @@ -4133,7 +4177,7 @@ '{0}' must be declared 'MustInherit' because it contains methods declared 'MustOverride'. - '“{0}”包含声明为“MustOverride”的方法,因此它必须声明为“MustInherit”。 + “{0}”包含声明为“MustOverride”的方法,因此它必须声明为“MustInherit”。 @@ -4148,7 +4192,7 @@ '{0}' cannot override '{1}' because it is not accessible in this context. - '“{0}”无法重写“{1}”,因为它在此上下文中是无法访问的。 + “{0}”无法重写“{1}”,因为它在此上下文中是无法访问的。 @@ -4163,7 +4207,7 @@ '{0}' conflicts with the reserved member by this name that is implicitly declared in all enums. - '“{0}”与在所有枚举中隐式声明的同名保留成员冲突。 + “{0}”与在所有枚举中隐式声明的同名保留成员冲突。 @@ -4208,7 +4252,7 @@ '{0}' is ambiguous because multiple kinds of members with this name exist in {1} '{2}'. - '“{0}”不明确,因为 {1}“{2}”中存在多种具有此名称的成员 + “{0}”不明确,因为 {1}“{2}”中存在多种具有此名称的成员 @@ -4243,7 +4287,7 @@ '{0}' cannot be declared 'Partial' because partial methods must be Subs. - '“{0}”不能声明为“Partial”,因为分部方法必须为 Subs。 + “{0}”不能声明为“Partial”,因为分部方法必须为 Subs。 @@ -4298,17 +4342,17 @@ '{0}' cannot be used as an attribute because it is not a class. - '“{0}”不是类,因此不能用作属性。 + “{0}”不是类,因此不能用作属性。 '{0}' cannot be used as an attribute because it does not inherit from 'System.Attribute'. - '“{0}”不从“System.Attribute”继承,因此不能用作属性。 + “{0}”不从“System.Attribute”继承,因此不能用作属性。 '{0}' cannot be used as an attribute because it is declared 'MustInherit'. - '“{0}”已声明为“MustInherit”,因此不能用作属性。 + “{0}”已声明为“MustInherit”,因此不能用作属性。 @@ -4408,7 +4452,7 @@ '{0}' is not valid within a Module. - '“{0}”在模块中无效。 + “{0}”在模块中无效。 @@ -4423,7 +4467,7 @@ '{0}' values cannot be converted to 'Char'. Use 'Microsoft.VisualBasic.ChrW' to interpret a numeric value as a Unicode character or first convert it to 'String' to produce a digit. - '“{0}”值不能转换为“Char”。使用“Microsoft.VisualBasic.ChrW”将数值解释为 Unicode 字符或先将其转换为“String”以产生数字。 + “{0}”值不能转换为“Char”。使用“Microsoft.VisualBasic.ChrW”将数值解释为 Unicode 字符或先将其转换为“String”以产生数字。 @@ -4438,7 +4482,7 @@ '{0}' cannot be named as a parameter in an attribute specifier because it is not a field or property. - '“{0}”不是字段或属性(Property),因此不能命名为属性(Attribute)说明符中的参数。 + “{0}”不是字段或属性(Property),因此不能命名为属性(Attribute)说明符中的参数。 @@ -4458,7 +4502,7 @@ '{0}' has no parameters and its return type cannot be indexed. - '“{0}”没有任何参数,并且无法对它的返回类型进行索引。 + “{0}”没有任何参数,并且无法对它的返回类型进行索引。 @@ -4483,7 +4527,7 @@ '{0}' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event. - '“{0}”是事件,不能直接调用。请使用“RaiseEvent”语句引发事件。 + “{0}”是事件,不能直接调用。请使用“RaiseEvent”语句引发事件。 @@ -4568,7 +4612,7 @@ '{0}' has no type parameters and so cannot have type arguments. - '“{0}”没有类型形参,因此不能有类型实参。 + “{0}”没有类型形参,因此不能有类型实参。 @@ -4608,7 +4652,7 @@ '{0}' has the same name as a type parameter. - '“{0}”与一个类型参数同名。 + “{0}”与一个类型参数同名。 @@ -4633,7 +4677,7 @@ '{0}' cannot be used as a type constraint. - '“{0}”不能用作类型约束。 + “{0}”不能用作类型约束。 @@ -4688,12 +4732,12 @@ '{0}' cannot override '{1}' because they differ by type parameter constraints. - '“{0}”无法重写“{1}”,因为它们在类型参数约束上存在差异。 + “{0}”无法重写“{1}”,因为它们在类型参数约束上存在差异。 '{0}' cannot implement '{1}.{2}' because they differ by type parameter constraints. - '“{0}”无法实现“{1}.{2}”,因为它们在类型参数约束上存在差异。 + “{0}”无法实现“{1}.{2}”,因为它们在类型参数约束上存在差异。 @@ -4748,7 +4792,7 @@ '{0}' is already declared as a type parameter of this method. - '“{0}”已声明为此方法的类型参数。 + “{0}”已声明为此方法的类型参数。 @@ -4935,7 +4979,7 @@ '{0}' cannot be declared 'Shadows' outside of a class, structure, or interface. - '“{0}”不能在类、结构或接口外声明为“Shadows”。 + “{0}”不能在类、结构或接口外声明为“Shadows”。 @@ -4995,7 +5039,7 @@ 'InterfaceId' and 'EventsId' parameters for 'Microsoft.VisualBasic.ComClassAttribute' on '{0}' cannot have the same value. - '“{0}”上“Microsoft.VisualBasic.ComClassAttribute”的“InterfaceId”和“EventsId”参数的值不能相同。 + “{0}”上“Microsoft.VisualBasic.ComClassAttribute”的“InterfaceId”和“EventsId”参数的值不能相同。 @@ -5060,7 +5104,7 @@ '{0}' parameters cannot be declared 'Optional'. - '“{0}”参数不能声明为“Optional”。 + “{0}”参数不能声明为“Optional”。 @@ -5320,7 +5364,7 @@ 'Using' operand of type '{0}' must implement 'System.IDisposable'. - '“{0}”类型的“Using”操作数必须实现“System.IDisposable”。 + “{0}”类型的“Using”操作数必须实现“System.IDisposable”。 @@ -5340,7 +5384,7 @@ '{0}' has the same name as a member used for type '{1}' exposed in a 'My' group. Rename the type or its enclosing namespace. - '“{0}”与“My”组中公开的类型“{1}”所使用的成员同名。请重命名该类型或其封闭命名空间。 + “{0}”与“My”组中公开的类型“{1}”所使用的成员同名。请重命名该类型或其封闭命名空间。 @@ -5440,7 +5484,7 @@ '{0}' is not a member of '{1}'; it does not exist in the current context. - '“{0}”不是“{1}”的成员;它不存在于当前上下文。 + “{0}”不是“{1}”的成员;它不存在于当前上下文。 @@ -5512,7 +5556,7 @@ '{0}' is not a method parameter. - '“{0}”不是方法参数。 + “{0}”不是方法参数。 @@ -5564,7 +5608,7 @@ '{0}' is not a parameter of extension method '{1}' defined in '{2}'. - '“{0}”不是“{2}”中定义的扩展方法“{1}”的参数。 + “{0}”不是“{2}”中定义的扩展方法“{1}”的参数。 @@ -5609,7 +5653,7 @@ '{0}{1}' is not valid because '{2}' is inside a scope that defines a variable that is used in a lambda or query expression. - '“{0}{1}”无效,因为“{2}”所在的范围定义一个用在 lambda 表达式或查询表达式中的变量。 + “{0}{1}”无效,因为“{2}”所在的范围定义一个用在 lambda 表达式或查询表达式中的变量。 @@ -5899,7 +5943,7 @@ '{0}' is not accessible in this context because the return type is not accessible. - '“{0}”是不可访问的返回类型,因此它在此上下文中不可访问。 + “{0}”是不可访问的返回类型,因此它在此上下文中不可访问。 @@ -5986,7 +6030,7 @@ '{0}' is obsolete: '{1}'. - '“{0}”已过时:“{1}”。 + “{0}”已过时:“{1}”。 @@ -6036,7 +6080,7 @@ '{0}' is obsolete. - '“{0}”已过时。 + “{0}”已过时。 @@ -6106,7 +6150,7 @@ '{0}' accessor of '{1}' is obsolete: '{2}'. - '“{1}”的“{0}”访问器已过时:“{2}”。 + “{1}”的“{0}”访问器已过时:“{2}”。 @@ -6116,7 +6160,7 @@ '{0}' accessor of '{1}' is obsolete. - '“{1}”的“{0}”访问器已过时。 + “{1}”的“{0}”访问器已过时。 @@ -6136,7 +6180,7 @@ '{0}' is not CLS-compliant because it derives from '{1}', which is not CLS-compliant. - '“{0}”不符合 CLS,因为它是从不符合 CLS 的“{1}”派生的。 + “{0}”不符合 CLS,因为它是从不符合 CLS 的“{1}”派生的。 @@ -6166,7 +6210,7 @@ '{0}' is not CLS-compliant because the interface '{1}' it inherits from is not CLS-compliant. - '“{0}”不符合 CLS,因为它所继承的接口“{1}”不符合 CLS。 + “{0}”不符合 CLS,因为它所继承的接口“{1}”不符合 CLS。 @@ -6226,7 +6270,7 @@ '{0}' is not CLS-compliant because it overloads '{1}' which differs from it only by array of array parameter types or by the rank of the array parameter types. - '“{0}”不符合 CLS,因为它重载仅在数组参数类型的数组或数组参数类型的秩方面与它不同的“{1}”。 + “{0}”不符合 CLS,因为它重载仅在数组参数类型的数组或数组参数类型的秩方面与它不同的“{1}”。 @@ -6816,7 +6860,7 @@ '{0}' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement. - '“{0}”无法作为属性“Let”向 COM 公开。将无法使用“Let”语句从 Visual Basic 6.0 向该属性分配非对象值(如数字或字符串)。 + “{0}”无法作为属性“Let”向 COM 公开。将无法使用“Let”语句从 Visual Basic 6.0 向该属性分配非对象值(如数字或字符串)。 @@ -7111,7 +7155,7 @@ Unable to include XML fragment - 无法包括 XML 段落。 + 无法包括 XML 段落 @@ -7121,7 +7165,7 @@ Unable to include XML fragment - 无法包括 XML 段落。 + 无法包括 XML 段落 @@ -7361,17 +7405,17 @@ '{0}' cannot expose type '{1}' in {2} '{3}' through {4} '{5}'. - '“{0}”不能通过 {4}“{5}”在 {2}“{3}”中公开类型“{1}”。 + “{0}”不能通过 {4}“{5}”在 {2}“{3}”中公开类型“{1}”。 '{0}' cannot be referenced because it is not a valid assembly. - '“{0}”不是有效程序集,因此无法引用它。 + “{0}”不是有效程序集,因此无法引用它。 '{0}' cannot be implemented by a {1} property. - '“{0}”无法由 {1} 属性实现。 + “{0}”无法由 {1} 属性实现。 @@ -7663,12 +7707,12 @@ '{0}' cannot be converted to '{1}'. Consider using '{2}' instead. - '“{0}”不能转换为“{1}”。考虑改用“{2}”。 + “{0}”不能转换为“{1}”。考虑改用“{2}”。 '{0}' cannot be converted to '{1}'. Consider using '{2}' instead. - '“{0}”不能转换为“{1}”。考虑改用“{2}”。 + “{0}”不能转换为“{1}”。考虑改用“{2}”。 @@ -7678,12 +7722,12 @@ '{4}' cannot be converted to '{5}' because '{0}' is not derived from '{1}', as required for the 'In' generic parameter '{2}' in '{3}'. - '“{4}”不能转换为“{5}”,因为根据“{3}”中“In”泛型形参“{2}”的需要,“{0}”不是从“{1}”派生的。 + “{4}”不能转换为“{5}”,因为根据“{3}”中“In”泛型形参“{2}”的需要,“{0}”不是从“{1}”派生的。 '{4}' cannot be converted to '{5}' because '{0}' is not derived from '{1}', as required for the 'Out' generic parameter '{2}' in '{3}'. - '“{4}”不能转换为“{5}”,因为根据“{3}”中“Out”泛型形参“{2}”的需要,“{0}”不是从“{1}”派生的。 + “{4}”不能转换为“{5}”,因为根据“{3}”中“Out”泛型形参“{2}”的需要,“{0}”不是从“{1}”派生的。 @@ -7708,17 +7752,17 @@ '{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an In type parameter, 'In {2}'. - '“{0}”不能转换为“{1}”。考虑在“{3}”的定义中将“{2}”改为 In 类型参数“In {2}”。 + “{0}”不能转换为“{1}”。考虑在“{3}”的定义中将“{2}”改为 In 类型参数“In {2}”。 '{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an Out type parameter, 'Out {2}'. - '“{0}”不能转换为“{1}”。考虑在“{3}”的定义中将“{2}”改为 Out 类型参数“Out {2}”。 + “{0}”不能转换为“{1}”。考虑在“{3}”的定义中将“{2}”改为 Out 类型参数“Out {2}”。 '{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an In type parameter, 'In {2}'. - '“{0}”不能转换为“{1}”。考虑在“{3}”的定义中将“{2}”改为 In 类型参数“In {2}”。 + “{0}”不能转换为“{1}”。考虑在“{3}”的定义中将“{2}”改为 In 类型参数“In {2}”。 @@ -7728,7 +7772,7 @@ '{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an Out type parameter, 'Out {2}'. - '“{0}”不能转换为“{1}”。考虑在“{3}”的定义中将“{2}”改为 Out 类型参数“Out {2}”。 + “{0}”不能转换为“{1}”。考虑在“{3}”的定义中将“{2}”改为 Out 类型参数“Out {2}”。 @@ -7998,7 +8042,7 @@ '{0}' does not implement '{1}'. - '“{0}”未实现“{1}”。 + “{0}”未实现“{1}”。 @@ -8038,7 +8082,7 @@ '{0}' does not return a Task and cannot be awaited. Consider changing it to an Async Function. - '“{0}”不返回 Task 且无法等待。请考虑将它更改为 Async Function。 + “{0}”不返回 Task 且无法等待。请考虑将它更改为 Async Function。 @@ -8093,7 +8137,7 @@ '{0}' cannot be used as a parameter type for an Iterator or Async method. - '“{0}”不能用作 Iterator 或 Async 方法的参数类型。 + “{0}”不能用作 Iterator 或 Async 方法的参数类型。 @@ -8103,7 +8147,7 @@ '{0}' cannot be declared 'Partial' because it has the 'Async' modifier. - '“{0}”不能声明为“Partial”,因为它具有“Async”修饰符。 + “{0}”不能声明为“Partial”,因为它具有“Async”修饰符。 @@ -8223,7 +8267,7 @@ '{0}.{1}' is already implemented by the base class '{2}'. Re-implementation of Windows Runtime Interface '{3}' is not allowed - '“{0}.{1}”已由基类“{2}”实现。不允许重新实现 Windows Runtime 接口“{3}” + “{0}.{1}”已由基类“{2}”实现。不允许重新实现 Windows Runtime 接口“{3}” @@ -8448,12 +8492,12 @@ '{0}' is an unsupported .NET module. - '“{0}”是不受支持的 .NET 模块。 + “{0}”是不受支持的 .NET 模块。 '{0}' is an unsupported event. - '“{0}”是不受支持的事件。 + “{0}”是不受支持的事件。 @@ -8718,7 +8762,7 @@ '{0}' is not a valid format specifier - '“{0}”不是有效的格式说明符 + “{0}”不是有效的格式说明符 @@ -8733,7 +8777,7 @@ '{0}' cannot be made nullable. - '“{0}”不可以为 Null。 + “{0}”不可以为 Null。 @@ -9103,7 +9147,7 @@ '{0}' is for evaluation purposes only and is subject to change or removal in future updates. - '“{0}”仅用于评估,在将来的更新中可能会被更改或删除。 + “{0}”仅用于评估,在将来的更新中可能会被更改或删除。 @@ -9133,7 +9177,7 @@ Predefined type '{0}' is declared in multiple referenced assemblies: '{1}' and '{2}' - 已在多个引用的程序集(“{1}”和“{2}”)中声明了预定义类型“{0}”。 + 已在多个引用的程序集(“{1}”和“{2}”)中声明了预定义类型“{0}” diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.zh-Hant.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.zh-Hant.xlf index c1a98587d7daa..be4692c2afe57 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.zh-Hant.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Command-line syntax error: '{0}' is not a valid value for the '{1}' option. The value must be of the form '{2}'. @@ -212,169 +212,169 @@ -vbruntime:<file> Compile with the alternate Visual Basic runtime in <file>. - Visual Basic Compiler Options + Visual Basic 編譯器選項 - - OUTPUT FILE - --out:<file> Specifies the output file name. --target:exe Create a console application (default). - (Short form: -t) --target:winexe Create a Windows application. --target:library Create a library assembly. --target:module Create a module that can be added to an - assembly. --target:appcontainerexe Create a Windows application that runs in - AppContainer. --target:winmdobj Create a Windows Metadata intermediate file --doc[+|-] Generates XML documentation file. --doc:<file> Generates XML documentation file to <file>. --refout:<file> Reference assembly output to generate + - 輸出檔案 - +-out:<file> 指定輸出檔名稱。 +-target:exe 建立主控台應用程式 (預設)。 + (簡短形式: -t) +-target:winexe 建立 Windows 應用程式。 +-target:library 建立程式庫組件。 +-target:module 建立可以新增至組件的 + 模組。 +-target:appcontainerexe 建立可在 AppContainer 中執行的 + Windows 應用程式。 +-target:winmdobj 建立 Windows Metadata 中繼檔案 +-doc[+|-] 產生 XML 文件檔。 +-doc:<file> 產生 XML 文件檔至 <file>。 +-refout:<file> 要產生的參考組件輸出 - - INPUT FILES - --addmodule:<file_list> Reference metadata from the specified modules --link:<file_list> Embed metadata from the specified interop - assembly. (Short form: -l) --recurse:<wildcard> Include all files in the current directory - and subdirectories according to the - wildcard specifications. --reference:<file_list> Reference metadata from the specified - assembly. (Short form: -r) --analyzer:<file_list> Run the analyzers from this assembly - (Short form: -a) --additionalfile:<file list> Additional files that don't directly affect code - generation but may be used by analyzers for producing - errors or warnings. + - 輸入檔 - +-addmodule:<file_list> 從指定的模組來參考中繼資料 +-link:<file_list> 從指定的 Interop 組件內嵌 + 中繼資料。(簡短形式: -l) +-recurse:<wildcard> 根據萬用字元規格 + 來加入目前目錄和子目錄中的 + 所有檔案。 +-reference:<file_list> 從指定的組件參考 + 中繼資料。(簡短形式: -r) +-analyzer:<file_list> 從此組件執行分析器 + (簡短形式: -a) +-additionalfile:<file list> 不直接影響程式碼產生, + 但分析器可能用於產生錯誤或警告的 + 其他檔案。 - - RESOURCES - --linkresource:<resinfo> Links the specified file as an external - assembly resource. + - 資源 - +-linkresource:<resinfo> 連結指定的檔案作為外部 + 組件資源。 resinfo:<file>[,<name>[,public|private]] - (Short form: -linkres) --nowin32manifest The default manifest should not be embedded - in the manifest section of the output PE. --resource:<resinfo> Adds the specified file as an embedded - assembly resource. + (簡短形式: -linkres) +-nowin32manifest 預設資訊清單不應內嵌於 + 輸出 PE 的資訊清單區段中。 +-resource:<resinfo> 將指定的檔案新增為內嵌的 + 組件資源。 resinfo:<file>[,<name>[,public|private]] - (Short form: -res) --win32icon:<file> Specifies a Win32 icon file (.ico) for the - default Win32 resources. --win32manifest:<file> The provided file is embedded in the manifest - section of the output PE. --win32resource:<file> Specifies a Win32 resource file (.res). + (簡短形式: -res) +-win32icon:<file> 指定某一個 Win32 圖示檔 (.ico) 給 + 預設的 Win32 資源。 +-win32manifest:<file> 提供的檔案內嵌於輸出 PE 的 + 資訊清單區段中。 +-win32resource:<file> 指定 Win32 資源檔 (.res)。 - - CODE GENERATION - --optimize[+|-] Enable optimizations. --removeintchecks[+|-] Remove integer checks. Default off. --debug[+|-] Emit debugging information. --debug:full Emit full debugging information (default). --debug:pdbonly Emit full debugging information. --debug:portable Emit cross-platform debugging information. --debug:embedded Emit cross-platform debugging information into - the target .dll or .exe. --deterministic Produce a deterministic assembly - (including module version GUID and timestamp) --refonly Produce a reference assembly in place of the main output --instrument:TestCoverage Produce an assembly instrumented to collect - coverage information --sourcelink:<file> Source link info to embed into PDB. + - 程式碼產生 - +-optimize[+|-] 啟用最佳化。 +-removeintchecks[+|-] 不檢查整數。預設為關閉。 +-debug[+|-] 發出偵錯資訊。 +-debug:full 發出完整偵錯資訊 (預設)。 +-debug:pdbonly 發出完整偵錯資訊。 +-debug:portable 發出跨平台的偵錯資訊。 +-debug:embedded 對目標 .dll 或 .exe 發出 + 跨平台偵錯資訊。 +-deterministic 產生確定性組件 + (含模組版本 GUID 與時間戳記) +-refonly 產生取代主要輸出的參考組件 +-instrument:TestCoverage 產生經檢測的組件,以收集 + 涵蓋範圍資訊 +-sourcelink:<file> 要內嵌至 PDB 的來源連結資訊。 - - ERRORS AND WARNINGS - --nowarn Disable all warnings. --nowarn:<number_list> Disable a list of individual warnings. --warnaserror[+|-] Treat all warnings as errors. --warnaserror[+|-]:<number_list> Treat a list of warnings as errors. --ruleset:<file> Specify a ruleset file that disables specific - diagnostics. + - 錯誤與警告 - +-nowarn 停用所有警告。 +-nowarn:<number_list> 停用個別警告清單。 +-warnaserror[+|-] 將所有警告視為錯誤。 +-warnaserror[+|-]:<number_list> 將警告清單視為錯誤。 +-ruleset:<file> 指定規則集檔案,以停用特定的 + 診斷。 -errorlog:<file>[,version=<sarif_version>] - Specify a file to log all compiler and analyzer - diagnostics in SARIF format. - sarif_version:{1|2|2.1} Default is 1. 2 and 2.1 - both mean SARIF version 2.1.0. --reportanalyzer Report additional analyzer information, such as - execution time. --skipanalyzers[+|-] Skip execution of diagnostic analyzers. + 指定檔案,以 SARIF 的格式記錄所有編譯器 + 與分析器診斷。 + sarif_version:{1|2|2.1} 預設為 1、2 與 2.1 + 兩者皆表示 SARIF 2.1.0 版。 +-reportanalyzer 回報其他分析器資訊,例如 + 執行時間。 +-skipanalyzers[+|-] 略過診斷分析器的執行。 - - LANGUAGE - --define:<symbol_list> Declare global conditional compilation - symbol(s). symbol_list:name=value,... - (Short form: -d) --imports:<import_list> Declare global Imports for namespaces in - referenced metadata files. + - 語言 - +-define:<symbol_list> 宣告全域條件式編譯的 + 符號。symbol_list:name=value,... + (簡短形式: -d) +-imports:<import_list> 在參考的中繼資料檔案中宣告命名空間的 + 全域匯入。 import_list:namespace,... --langversion:? Display the allowed values for language version --langversion:<string> Specify language version such as - `default` (latest major version), or - `latest` (latest version, including minor versions), - or specific versions like `14` or `15.3` --optionexplicit[+|-] Require explicit declaration of variables. --optioninfer[+|-] Allow type inference of variables. --rootnamespace:<string> Specifies the root Namespace for all type - declarations. --optionstrict[+|-] Enforce strict language semantics. --optionstrict:custom Warn when strict language semantics are not - respected. --optioncompare:binary Specifies binary-style string comparisons. - This is the default. --optioncompare:text Specifies text-style string comparisons. +-langversion:? 顯示允許的語言版本值 +-langversion:<string> 指定語言版本,例如 + `default` (最新的主要版本) 或 + `latest` (最新版本,包括次要版本) + 或特定的版本,例如 `14` 或 `15.3` +-optionexplicit[+|-] 變數必須明確宣告。 +-optioninfer[+|-] 允許變數的類型推斷。 +-rootnamespace:<string> 指定所有類型宣告的 + 根命名空間。 +-optionstrict[+|-] 強制採用嚴格的語意。 +-optionstrict:custom 未遵守嚴格的語意時 + 發出警告。 +-optioncompare:binary 採用二進位樣式來比較字串。 + 這是預設值。 +-optioncompare:text 採用文字樣式來比較字串。 - - MISCELLANEOUS - --help Display this usage message. (Short form: -?) --noconfig Do not auto-include VBC.RSP file. --nologo Do not display compiler copyright banner. --quiet Quiet output mode. --verbose Display verbose messages. --parallel[+|-] Concurrent build. --version Display the compiler version number and exit. + - 其他 - +-help 顯示此使用方式訊息。(簡短形式: -?) +-noconfig 不要自動納入 VBC.RSP 檔。 +-nologo 不要顯示編譯器著作權橫幅。 +-quiet 無對話輸出模式。 +-verbose 顯示詳細訊息。 +-parallel[+|-] 並行組建。 +-version 顯示編譯器版本編號然後結束。 - - ADVANCED - --baseaddress:<number> The base address for a library or module - (hex). --checksumalgorithm:<alg> Specify algorithm for calculating source file - checksum stored in PDB. Supported values are: - SHA1 or SHA256 (default). --codepage:<number> Specifies the codepage to use when opening - source files. --delaysign[+|-] Delay-sign the assembly using only the public - portion of the strong name key. --publicsign[+|-] Public-sign the assembly using only the public - portion of the strong name key. --errorreport:<string> Specifies how to handle internal compiler - errors; must be prompt, send, none, or queue - (default). --filealign:<number> Specify the alignment used for output file - sections. --highentropyva[+|-] Enable high-entropy ASLR. --keycontainer:<string> Specifies a strong name key container. --keyfile:<file> Specifies a strong name key file. --libpath:<path_list> List of directories to search for metadata - references. (Semi-colon delimited.) --main:<class> Specifies the Class or Module that contains - Sub Main. It can also be a Class that - inherits from System.Windows.Forms.Form. - (Short form: -m) --moduleassemblyname:<string> Name of the assembly which this module will - be a part of. --netcf Target the .NET Compact Framework. --nostdlib Do not reference standard libraries - (system.dll and VBC.RSP file). + - 進階 - +-baseaddress:<number> 程式庫或模組的基底位置 + (十六進位)。 +-checksumalgorithm:<alg> 指定演算法,以計算儲存於 PDB 的 + 來源檔案總和檢查碼。支援的值有: + SHA1 或 SHA256 (預設)。 +-codepage:<number> 指定開啟原始程式檔時所要使用的 + 字碼頁。 +-delaysign[+|-] 僅使用強式名稱金鑰的公開 + 部分延遲簽署組件。 +-publicsign[+|-] 僅使用強式名稱金鑰的公開 + 部分公開簽署組件。 +-errorreport:<string> 指定如何處理內部編譯器 + 錯誤;必須是 prompt、send、none 或 queue + (預設)。 +-filealign:<number> 指定用於輸出檔案區段的對齊 + 方式。 +-highentropyva[+|-] 啟用高熵 ASLR。 +-keycontainer:<string> 指定強式名稱金鑰容器。 +-keyfile:<file> 指定強式名稱金鑰檔。 +-libpath:<path_list> 搜尋中繼資料參考的 + 目錄清單 (以分號分隔)。 +-main:<class> 指定包含 Sub Main 的 + Class 或 Module。也可以是繼承自 + System.Windows.Forms.Form 的 Class。 + (簡短形式: -m) +-moduleassemblyname:<string> 這個模組將成為其一部分的 + 組件名稱。 +-netcf 以 .NET Compact Framework 為目標。 +-nostdlib 不要參考標準程式庫 + (system.dll 與 VBC.RSP 檔)。 -pathmap:<K1>=<V1>,<K2>=<V2>,... - Specify a mapping for source path names output by - the compiler. --platform:<string> Limit which platforms this code can run on; - must be x86, x64, Itanium, arm, arm64 - AnyCPU32BitPreferred or anycpu (default). --preferreduilang Specify the preferred output language name. --nosdkpath Disable searching the default SDK path for standard library assemblies. --sdkpath:<path> Location of the .NET Framework SDK directory - (mscorlib.dll). --subsystemversion:<version> Specify subsystem version of the output PE. - version:<number>[.<number>] --utf8output[+|-] Emit compiler output in UTF8 character - encoding. -@<file> Insert command-line settings from a text file --vbruntime[+|-|*] Compile with/without the default Visual Basic - runtime. --vbruntime:<file> Compile with the alternate Visual Basic - runtime in <file>. + 指定由編譯器輸出的來源路徑名稱對應 + 對應。 +-platform:<string> 限制這個程式碼可以在哪些平台執行; + 必須是 x86、x64、Itanium、arm、arm64 + AnyCPU32BitPreferred 或 anycpu (預設)。 +-preferreduilang 指定慣用的輸出語言名稱。 +-nosdkpath 禁止搜尋預設 SDK 路徑的標準程式庫組件。 +-sdkpath:<path> .NET Framework SDK 目錄 + (mscorlib.dll) 的位置。 +-subsystemversion:<version> 指定輸出 PE 的子系統版本。 + 版本:<number>[.<number>] +-utf8output[+|-] 以 UTF8 字元編碼發出編譯器 + 輸出。 +@<file> 從文字檔插入命令列設定 +-vbruntime[+|-|*] 使用 (或不使用) 預設 Visual Basic + 執行階段編譯。 +-vbruntime:<file> 使用 <file> 中的其他 Visual Basic + 執行階段編譯。 @@ -463,6 +463,50 @@ 類型引數不可為 Nothing + + The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + 包含類型 '{1}' 的組件 '{0}' 參考了 .NET Framework,此情形不受支援。 + {1} is the type that was loaded, {0} is the containing assembly. + + + The loaded assembly references .NET Framework, which is not supported. + 載入的組件參考了 .NET Framework,此情形不受支援。 + + + + Generator '{0}' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + 產生器 '{0}' 無法產生來源。其不會提供給輸出,並可能導致編譯錯誤。例外狀況的類型為 '{1}',訊息為 '{2}' + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + 產生器擲回了下列例外狀況: +'{0}'。 + {0} is the string representation of the exception that was thrown. + + + Generator failed to generate source. + 產生器無法產生來源。 + + + + Generator '{0}' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}' + 產生器 '{0}' 無法初始化。其不會提供給輸出,並可能導致編譯錯誤。例外狀況的類型為 '{1}',訊息為 '{2}' + {0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception + + + Generator threw the following exception: +'{0}'. + 產生器擲回了下列例外狀況: +'{0}'。 + {0} is the string representation of the exception that was thrown. + + + Generator failed to initialize. + 產生器無法初始化。 + + Wrong number of type arguments 類型引數的數目錯誤 @@ -585,12 +629,12 @@ ignoring /noconfig option because it was specified in a response file - 忽略 /noconfig 選項,因為在回應檔中已指定。 + 忽略 /noconfig 選項,因為在回應檔中已指定 Ignoring /noconfig option because it was specified in a response file - 因為在回應檔中已指定 /noconfig 選項,所以將會忽略該選項。 + 因為在回應檔中已指定 /noconfig 選項,所以將會忽略該選項 @@ -605,7 +649,7 @@ cannot infer an output file name from resource only input files; provide the '/out' option - 無法從只有輸入檔的資源推斷輸出檔名,請提供 '/out' 選項。 + 無法從只有輸入檔的資源推斷輸出檔名,請提供 '/out' 選項 @@ -725,7 +769,7 @@ Statement is not valid inside '{0}' block. - {0}' 區塊內的陳述式無效。 + '{0}' 區塊內的陳述式無效。 @@ -860,7 +904,7 @@ Too many arguments to '{0}'. - {0}' 的引數太多。 + '{0}' 的引數太多。 @@ -1514,7 +1558,7 @@ Parameter '{0}' of '{1}' already has a matching argument. - {1}' 的參數 '{0}' 已有相符的引數。 + '{1}' 的參數 '{0}' 已有相符的引數。 @@ -2225,7 +2269,7 @@ Default member of '{0}' is not a property. - {0}' 的預設成員並非屬性。 + '{0}' 的預設成員並非屬性。 @@ -2667,7 +2711,7 @@ Attribute '{0}' in '{1}' cannot be applied multiple times. - {1}' 中的屬性 '{0}' 不可多次套用。 + '{1}' 中的屬性 '{0}' 不可多次套用。 @@ -3248,7 +3292,7 @@ Multiple initializations of '{0}'. Fields and properties can be initialized only once in an object initializer expression. - {0}' 的多個初始設定。欄位和屬性只能在一個物件初始設定式運算式中初始化一次。 + '{0}' 的多個初始設定。欄位和屬性只能在一個物件初始設定式運算式中初始化一次。 @@ -4478,7 +4522,7 @@ Parameter '{0}' in '{1}' already has a matching omitted argument. - {1}' 中的參數 '{0}' 已有相符的省略引數。 + '{1}' 中的參數 '{0}' 已有相符的省略引數。 @@ -4543,7 +4587,7 @@ The '{0}' keyword is used to overload inherited members; do not use the '{0}' keyword when overloading 'Sub New'. - {0}' 關鍵字是用以多載繼承的成員; 當多載 'Sub New' 時,請勿使用 '{0}' 關鍵字。 + '{0}' 關鍵字是用以多載繼承的成員; 當多載 'Sub New' 時,請勿使用 '{0}' 關鍵字。 @@ -4553,12 +4597,12 @@ Too few type arguments to '{0}'. - {0}' 的類型引數太少。 + '{0}' 的類型引數太少。 Too many type arguments to '{0}'. - {0}' 的類型引數太多。 + '{0}' 的類型引數太多。 @@ -5175,12 +5219,12 @@ Matching '{0}' operator is required for '{1}'. - {1}' 必須要有對稱的 '{0}' 運算子。 + '{1}' 必須要有對稱的 '{0}' 運算子。 Return and parameter types of '{0}' must be '{1}' to be used in a '{2}' expression. - {0}' 的傳回類型與參數類型必須是 '{1}',才可用在 '{2}' 運算式中。 + '{0}' 的傳回類型與參數類型必須是 '{1}',才可用在 '{2}' 運算式中。 @@ -5200,12 +5244,12 @@ Return and parameter types of '{0}' must be '{1}' to be used in a 'For' statement. - {0}' 的傳回類型與參數類型必須是 '{1}',才可用在 'For' 陳述式中。 + '{0}' 的傳回類型與參數類型必須是 '{1}',才可用在 'For' 陳述式中。 Parameter types of '{0}' must be '{1}' to be used in a 'For' statement. - {0}' 的參數類型必須是 '{1}',才可用在 'For' 陳述式中。 + '{0}' 的參數類型必須是 '{1}',才可用在 'For' 陳述式中。 @@ -5554,12 +5598,12 @@ Parameter '{0}' in extension method '{1}' defined in '{2}' already has a matching omitted argument. - {2}' 中定義之擴充方法 '{1}' 內的參數 '{0}',已有相符的省略引數。 + '{2}' 中定義之擴充方法 '{1}' 內的參數 '{0}',已有相符的省略引數。 Parameter '{0}' of extension method '{1}' defined in '{2}' already has a matching argument. - {2}' 中定義之擴充方法 '{1}' 的參數 '{0}',已有相符的引數。 + '{2}' 中定義之擴充方法 '{1}' 的參數 '{0}',已有相符的引數。 @@ -5919,7 +5963,7 @@ Extension Method '{0}' defined in '{2}' does not have a signature compatible with delegate '{1}'. - {2}' 中定義的擴充方法 '{0}',沒有與委派 '{1}' 相容的簽章。 + '{2}' 中定義的擴充方法 '{0}',沒有與委派 '{1}' 相容的簽章。 @@ -6966,7 +7010,7 @@ XML comment tag '{0}' is not permitted on a '{1}' language element. - {1}' 語言元素上不可使用 XML 註解標記 '{0}'。 + '{1}' 語言元素上不可使用 XML 註解標記 '{0}'。 @@ -7428,12 +7472,12 @@ Friend access was granted by '{0}', but the public key of the output assembly does not match that specified by the attribute in the granting assembly. - {0}' 已授與 Friend 存取權限,但輸出組件的公開金鑰不符合授與之組件中屬性所指定的公開金鑰。 + '{0}' 已授與 Friend 存取權限,但輸出組件的公開金鑰不符合授與之組件中屬性所指定的公開金鑰。 Friend access was granted by '{0}', but the strong name signing state of the output assembly does not match that of the granting assembly. - {0}' 已授與 Friend 存取權限,但輸出組件的強式名稱簽署狀態不符合授與組件的強式名稱簽署狀態。 + '{0}' 已授與 Friend 存取權限,但輸出組件的強式名稱簽署狀態不符合授與組件的強式名稱簽署狀態。 @@ -7463,7 +7507,7 @@ Delay signing was specified and requires a public key, but no public key was specified - 指定了延遲簽署且需要公開金鑰,但未指定任何公開金鑰。 + 指定了延遲簽署且需要公開金鑰,但未指定任何公開金鑰 @@ -7498,7 +7542,7 @@ Executables cannot be satellite assemblies; culture should always be empty - 可執行檔不可為附屬組件; 文化特性需保留為空白。 + 可執行檔不可為附屬組件; 文化特性需保留為空白 @@ -7538,7 +7582,7 @@ The assembly name '{0}' is reserved and cannot be used as a reference in an interactive session - 組件名稱 '{0}' 已保留,不可用做為互動工作階段中的參考。 + 組件名稱 '{0}' 已保留,不可用做為互動工作階段中的參考 @@ -9153,7 +9197,7 @@ File name '{0}' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long - 檔案名稱 '{0}' 是空的、包含了無效字元、指定了磁碟機但不是絕對路徑,或太長了。 + 檔案名稱 '{0}' 是空的、包含了無效字元、指定了磁碟機但不是絕對路徑,或太長了 diff --git a/src/Compilers/VisualBasic/Test/CommandLine/CommandLineTests.vb b/src/Compilers/VisualBasic/Test/CommandLine/CommandLineTests.vb index 890fba65ecc91..ec9610a4e91fc 100644 --- a/src/Compilers/VisualBasic/Test/CommandLine/CommandLineTests.vb +++ b/src/Compilers/VisualBasic/Test/CommandLine/CommandLineTests.vb @@ -10058,6 +10058,59 @@ End Class") End If End Sub + + + + + + + + + + + Public Sub TestWarnAsErrorMinusDoesNotNullifyEditorConfig(warnAsErrorMinus As Boolean, + defaultSeverity As DiagnosticSeverity, + severityInConfigFile As DiagnosticSeverity?, + expectedEffectiveSeverity As DiagnosticSeverity) + Dim analyzer = New NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault:=True, defaultSeverity, throwOnAllNamedTypes:=False) + Dim diagnosticId = analyzer.Descriptor.Id + + Dim dir = Temp.CreateDirectory() + Dim src = dir.CreateFile("test.vb").WriteAllText(" +Class C +End Class") + Dim additionalFlags = {"/warnaserror+"} + + If severityInConfigFile.HasValue Then + Dim severityString = DiagnosticDescriptor.MapSeverityToReport(severityInConfigFile.Value).ToAnalyzerConfigString() + Dim analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($" +[*.vb] +dotnet_diagnostic.{diagnosticId}.severity = {severityString}") + + additionalFlags = additionalFlags.Append($"/analyzerconfig:{analyzerConfig.Path}").ToArray() + End If + + If warnAsErrorMinus Then + additionalFlags = additionalFlags.Append($"/warnaserror-:{diagnosticId}").ToArray() + End If + + Dim expectedWarningCount As Integer = 0, expectedErrorCount As Integer = 0 + Select Case expectedEffectiveSeverity + Case DiagnosticSeverity.Warning + expectedWarningCount = 1 + Case DiagnosticSeverity.[Error] + expectedErrorCount = 1 + Case Else + Throw ExceptionUtilities.UnexpectedValue(expectedEffectiveSeverity) + End Select + + VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference:=False, + expectedWarningCount:=expectedWarningCount, + expectedErrorCount:=expectedErrorCount, + additionalFlags:=additionalFlags, + analyzers:=ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) + End Sub + Public Sub GlobalAnalyzerConfigDiagnosticOptionsCanBeOverridenByCommandLine() @@ -10257,6 +10310,67 @@ dotnet_diagnostic.{diagnosticId}.severity = {analyzerConfigSeverity}") Assert.DoesNotContain(diagnosticId, output) End If End Sub + + + Public Sub TestGeneratorsCantTargetNetFramework() + Dim directory = Temp.CreateDirectory() + Dim src = directory.CreateFile("test.vb").WriteAllText(" +Class C +End Class") + + 'Core + Dim coreGenerator = EmitGenerator(".NETCoreApp,Version=v5.0") + VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/analyzer:" & coreGenerator}) + + 'NetStandard + Dim nsGenerator = EmitGenerator(".NETStandard,Version=v2.0") + VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/analyzer:" & nsGenerator}) + + 'NoTarget + Dim ntGenerator = EmitGenerator(targetFramework:=Nothing) + VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/analyzer:" & ntGenerator}) + + 'Framework + Dim frameworkGenerator = EmitGenerator(".NETFramework,Version=v4.7.2") + Dim output = VerifyOutput(directory, src, expectedWarningCount:=2, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/analyzer:" & frameworkGenerator}) + Assert.Contains("CS8850", output) + Assert.Contains("CS8033", output) + + 'Framework, suppressed + output = VerifyOutput(directory, src, expectedWarningCount:=1, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/nowarn:CS8850", "/analyzer:" & frameworkGenerator}) + Assert.Contains("CS8033", output) + VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/nowarn:CS8850,CS8033", "/analyzer:" & frameworkGenerator}) + End Sub + + Private Function EmitGenerator(ByVal targetFramework As String) As String + Dim targetFrameworkAttributeText As String = If(TypeOf targetFramework Is Object, $"", String.Empty) + Dim generatorSource As String = $" +Imports Microsoft.CodeAnalysis + +{targetFrameworkAttributeText} + + +Public Class Generator + Inherits ISourceGenerator + + Public Sub Execute(ByVal context As GeneratorExecutionContext) + End Sub + + Public Sub Initialize(ByVal context As GeneratorInitializationContext) + End Sub +End Class +" + Dim directory = Temp.CreateDirectory() + Dim generatorPath = Path.Combine(directory.Path, "generator.dll") + Dim compilation = VisualBasicCompilation.Create($"generator_{targetFramework}", + {VisualBasicSyntaxTree.ParseText(generatorSource)}, + TargetFrameworkUtil.GetReferences(Roslyn.Test.Utilities.TargetFramework.Standard, {MetadataReference.CreateFromAssemblyInternal(GetType(ISourceGenerator).Assembly)}), + New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) + compilation.VerifyDiagnostics() + Dim result = compilation.Emit(generatorPath) + Assert.[True](result.Success) + Return generatorPath + End Function End Class diff --git a/src/Compilers/VisualBasic/Test/Semantic/SourceGeneration/GeneratorDriverTests.vb b/src/Compilers/VisualBasic/Test/Semantic/SourceGeneration/GeneratorDriverTests.vb new file mode 100644 index 0000000000000..b35d948b9a092 --- /dev/null +++ b/src/Compilers/VisualBasic/Test/Semantic/SourceGeneration/GeneratorDriverTests.vb @@ -0,0 +1,213 @@ +' Licensed to the .NET Foundation under one or more agreements. +' The .NET Foundation licenses this file to you under the MIT license. +' See the LICENSE file in the project root for more information. + +Imports System.Collections.Immutable +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax +Imports Roslyn.Test.Utilities.TestGenerators + +Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests + + Public Class GeneratorDriverTests + Inherits BasicTestBase + + + Public Sub Single_File_Is_Added() + + Dim generatorSource = " +Public Class GeneratedClass + +End Class +" + Dim parseOptions = TestOptions.Regular + Dim compilation = GetCompilation(parseOptions) + Dim testGenerator As SingleFileTestGenerator = New SingleFileTestGenerator(generatorSource) + Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions) + + Dim outputCompilation As Compilation = Nothing + Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing + driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) + outputDiagnostics.Verify() + + Assert.Equal(2, outputCompilation.SyntaxTrees.Count()) + Assert.NotEqual(compilation, outputCompilation) + End Sub + + + Public Sub Can_Access_Additional_Files() + + Dim additionalText = New InMemoryAdditionalText("a\\file1.cs", "Hello World") + + Dim parseOptions = TestOptions.Regular + Dim compilation As Compilation = GetCompilation(parseOptions) + Dim testGenerator As CallbackGenerator = New CallbackGenerator(Sub(i) + End Sub, + Sub(e) Assert.Equal("Hello World", e.AdditionalFiles.First().GetText().ToString())) + + Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), + additionalTexts:=ImmutableArray.Create(Of AdditionalText)(additionalText), + parseOptions:=parseOptions) + + Dim outputCompilation As Compilation = Nothing + Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing + driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) + outputDiagnostics.Verify() + End Sub + + + Public Sub Generator_Can_Be_Written_In_Visual_Basic() + + Dim parseOptions = TestOptions.Regular + Dim compilation As Compilation = GetCompilation(parseOptions) + Dim testGenerator As VBGenerator = New VBGenerator() + Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions) + + Dim outputCompilation As Compilation = Nothing + Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing + driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) + outputDiagnostics.Verify() + + Assert.Equal(2, outputCompilation.SyntaxTrees.Count()) + Assert.NotEqual(compilation, outputCompilation) + End Sub + + + Public Sub Generator_Can_See_Syntax() + + Dim source = " +Imports System +Namespace ANamespace + Public Class AClass + Public Sub AMethod(p as String) + Throw New InvalidOperationException() + End Sub + End Class +End Namespace +" + + Dim parseOptions = TestOptions.Regular + Dim compilation As Compilation = GetCompilation(parseOptions, source) + Dim testGenerator As VBGenerator = New VBGenerator() + Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions) + + Dim outputCompilation As Compilation = Nothing + Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing + driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) + outputDiagnostics.Verify() + + Assert.Equal(23, testGenerator._receiver._nodes.Count) + Assert.IsType(GetType(CompilationUnitSyntax), testGenerator._receiver._nodes(0)) + Assert.IsType(GetType(ClassStatementSyntax), testGenerator._receiver._nodes(8)) + Assert.IsType(GetType(ThrowStatementSyntax), testGenerator._receiver._nodes(16)) + Assert.IsType(GetType(EndBlockStatementSyntax), testGenerator._receiver._nodes(22)) + + End Sub + + + Public Sub Exception_During_Init() + Dim parseOptions = TestOptions.Regular + Dim compilation As Compilation = GetCompilation(parseOptions) + Dim testGenerator As CallbackGenerator = New CallbackGenerator(Sub(i) Throw New Exception("Init Exception"), + Sub(e) + End Sub) + + Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions) + + Dim outputCompilation As Compilation = Nothing + Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing + driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) + outputDiagnostics.Verify( + Diagnostic("BC42501").WithArguments("CallbackGenerator", "Exception", "Init Exception").WithLocation(1, 1) + ) + End Sub + + + Public Sub Exception_During_Execute() + Dim parseOptions = TestOptions.Regular + Dim compilation As Compilation = GetCompilation(parseOptions) + Dim testGenerator As CallbackGenerator = New CallbackGenerator(Sub(i) + End Sub, + Sub(e) Throw New Exception("Generate Exception")) + + Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions) + + Dim outputCompilation As Compilation = Nothing + Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing + driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) + outputDiagnostics.Verify( + Diagnostic("BC42502").WithArguments("CallbackGenerator", "Exception", "Generate Exception").WithLocation(1, 1) + ) + + End Sub + + + Public Sub Exception_During_SyntaxWalk() + Dim parseOptions = TestOptions.Regular + Dim compilation As Compilation = GetCompilation(parseOptions) + Dim testGenerator As VBGenerator = New VBGenerator() + testGenerator._receiver._throw = True + + Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions) + + Dim outputCompilation As Compilation = Nothing + Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing + driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) + outputDiagnostics.Verify( + Diagnostic("BC42502").WithArguments("VBGenerator", "Exception", "Syntax Walk").WithLocation(1, 1) + ) + End Sub + + Shared Function GetCompilation(parseOptions As VisualBasicParseOptions, Optional source As String = "") As Compilation + If (String.IsNullOrWhiteSpace(source)) Then + source = " +Public Class C +End Class +" + End If + + Dim compilation As Compilation = CreateCompilation(source, options:=TestOptions.DebugDll, parseOptions:=parseOptions) + compilation.VerifyDiagnostics() + Assert.Single(compilation.SyntaxTrees) + + Return compilation + End Function + + End Class + + + + Friend Class VBGenerator + Implements ISourceGenerator + + Public _receiver As Receiver = New Receiver() + + Public Sub Initialize(context As GeneratorInitializationContext) Implements ISourceGenerator.Initialize + context.RegisterForSyntaxNotifications(Function() _receiver) + End Sub + + Public Sub Execute(context As GeneratorExecutionContext) Implements ISourceGenerator.Execute + context.AddSource("source.vb", " +Public Class D +End Class +") + End Sub + + Class Receiver + Implements ISyntaxReceiver + + Public _throw As Boolean + + Public _nodes As List(Of SyntaxNode) = New List(Of SyntaxNode)() + + Public Sub OnVisitSyntaxNode(syntaxNode As SyntaxNode) Implements ISyntaxReceiver.OnVisitSyntaxNode + If (_throw) Then + Throw New Exception("Syntax Walk") + End If + _nodes.Add(syntaxNode) + End Sub + End Class + + End Class + + +End Namespace diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AnonymousTypes/AnonymousTypesEmittedSymbolsTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AnonymousTypes/AnonymousTypesEmittedSymbolsTests.vb index c290423597138..4b5a31722f9d7 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AnonymousTypes/AnonymousTypesEmittedSymbolsTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AnonymousTypes/AnonymousTypesEmittedSymbolsTests.vb @@ -306,30 +306,31 @@ End Module End Sub + Public Sub CheckPropertyFieldAndAccessorsNamesTest() Dim compilationDef = Module ModuleB Sub Test1(x As Integer) - Dim v1 As Object = New With { .aa = 1 }.aa - Dim v2 As Object = New With { Key .AA = "a" }.aa + Dim v1 As Object = New With { .aab = 1 }.aab + Dim v2 As Object = New With { Key .AAB = "a" }.aab End Sub End Module Module ModuleA Sub Test1(x As Integer) - Dim v1 As Object = New With { .Aa = 1 }.aa - Dim v2 As Object = New With { Key .aA = "A" }.aa + Dim v1 As Object = New With { .Aab = 1 }.aab + Dim v2 As Object = New With { Key .aAB = "A" }.aab End Sub End Module Module ModuleC Sub Test1(x As Integer) - Dim v1 As Object = New With { .AA = 1 }.aa - Dim v2 As Object = New With { Key .aa = "A" }.aa + Dim v1 As Object = New With { .AAb = 1 }.aab + Dim v2 As Object = New With { Key .aaB = "A" }.aab End Sub End Module @@ -339,14 +340,15 @@ End Module For i = 0 To 50 CompileAndVerify(compilationDef, references:={SystemCoreRef}, + options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`1") Assert.NotNull(type) - CheckPropertyAccessorsAndField(m, type, "aa", type.TypeParameters(0), False) + CheckPropertyAccessorsAndField(m, type, "aab", type.TypeParameters(0), False) type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_1`1") Assert.NotNull(type) - CheckPropertyAccessorsAndField(m, type, "AA", type.TypeParameters(0), True) + CheckPropertyAccessorsAndField(m, type, "AAB", type.TypeParameters(0), True) End Sub) Next End Sub @@ -647,8 +649,7 @@ End Module #Region "Utils" Private Shared Sub CheckPropertyAccessorsAndField(m As ModuleSymbol, type As NamedTypeSymbol, propName As String, propType As TypeSymbol, isKey As Boolean) - Dim prop = DirectCast(type.GetMember(propName), PropertySymbol) - Assert.NotNull(prop) + Dim prop = type.GetMembers().OfType(Of PropertySymbol)().Single() Assert.Equal(propType, prop.Type) Assert.Equal(propName, prop.Name) Assert.Equal(propName, prop.MetadataName) @@ -682,7 +683,16 @@ End Module Assert.Null(prop.SetMethod) End If - Assert.Equal(0, type.GetMembers("$" & propName).Length) + Dim field = type.GetMembers().OfType(Of FieldSymbol)().Single() + Assert.Equal(propType, field.Type) + Assert.Equal("$" & propName, field.Name) + Assert.Equal("$" & propName, field.MetadataName) + Assert.Equal(Accessibility.Private, field.DeclaredAccessibility) + + Dim parameter = type.Constructors.Single().Parameters(0) + Assert.Equal(propType, parameter.Type) + Assert.Equal(propName, parameter.Name) + Assert.Equal(propName, parameter.MetadataName) End Sub Private Shared Sub CheckMethod(m As ModuleSymbol, method As MethodSymbol, @@ -697,6 +707,7 @@ End Module Assert.NotNull(method) Assert.Equal(name, method.Name) + Assert.Equal(name, method.MetadataName) Assert.Equal(paramCount, method.ParameterCount) If isSub Then diff --git a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParserRegressionTests.vb b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParserRegressionTests.vb index 0ce46fbf1763e..e10774ec82a94 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParserRegressionTests.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParserRegressionTests.vb @@ -934,4 +934,38 @@ End Enum Assert.Equal(Syntax.InternalSyntax.Scanner.BadTokenCountLimit, tree.GetDiagnostics().Where(Function(d) d.Code = ERRID.ERR_IllegalChar).Count()) End Sub + + Public Sub ParseTrailingTextAfterPropertyWithParentheses() + Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( + + +Class C + Public ReadOnly Property NumberOfResult1() String Integer JohnDoe WwwIIWww Wow + Public ReadOnly Property NumberOfResult2() Some unexpected tokens As Integer + Public ReadOnly Property NumberOfResult3() UnexpectedToken ' With comment. + Public ReadOnly Property NumberOfResult4() UnexpectedToken _ + As Integer ' with line continuation and comment. + + Public ReadOnly Property NumberOfResult5() ' With comment - no errors. + Public ReadOnly Property NumberOfResult6() _ + As Integer ' No error with line continuation. +End Class + +) + CompilationUtils.AssertTheseDiagnostics(compilation, + +BC30205: End of statement expected. + Public ReadOnly Property NumberOfResult1() String Integer JohnDoe WwwIIWww Wow + ~~~~~~ +BC30205: End of statement expected. + Public ReadOnly Property NumberOfResult2() Some unexpected tokens As Integer + ~~~~ +BC30205: End of statement expected. + Public ReadOnly Property NumberOfResult3() UnexpectedToken ' With comment. + ~~~~~~~~~~~~~~~ +BC30205: End of statement expected. + Public ReadOnly Property NumberOfResult4() UnexpectedToken _ + ~~~~~~~~~~~~~~~ +) + End Sub End Class diff --git a/src/Compilers/VisualBasic/vbc/Program.cs b/src/Compilers/VisualBasic/vbc/Program.cs index 7bc690808791a..3e1a32b7c113a 100644 --- a/src/Compilers/VisualBasic/vbc/Program.cs +++ b/src/Compilers/VisualBasic/vbc/Program.cs @@ -33,7 +33,8 @@ private static int MainCore(string[] args) ExitingTraceListener.Install(); #endif - return BuildClient.Run(args, RequestLanguage.VisualBasicCompile, Vbc.Run); + using var logger = new CompilerServerLogger(); + return BuildClient.Run(args, RequestLanguage.VisualBasicCompile, Vbc.Run, logger); } public static int Run(string[] args, string clientDir, string workingDir, string sdkDir, string tempDir, TextWriter textWriter, IAnalyzerAssemblyLoader analyzerLoader) diff --git a/src/EditorFeatures/CSharp/AddImports/CSharpAddImportsPasteCommandHandler.cs b/src/EditorFeatures/CSharp/AddImports/CSharpAddImportsPasteCommandHandler.cs new file mode 100644 index 0000000000000..ede93d30ce629 --- /dev/null +++ b/src/EditorFeatures/CSharp/AddImports/CSharpAddImportsPasteCommandHandler.cs @@ -0,0 +1,38 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.ComponentModel.Composition; +using Microsoft.CodeAnalysis.Editor.Implementation.AddImports; +using Microsoft.CodeAnalysis.Editor.Shared.Utilities; +using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.VisualStudio.Commanding; +using Microsoft.VisualStudio.Utilities; + +namespace Microsoft.CodeAnalysis.Editor.CSharp.AddImports +{ + [Export] + [Export(typeof(ICommandHandler))] + [ContentType(ContentTypeNames.CSharpContentType)] + [Name(PredefinedCommandHandlerNames.AddImportsPaste)] + // Order is important here, this command needs to execute before PasteTracking + // since it may modify the pasted span. Paste tracking dismisses if + // the span is modified. It doesn't need to be before FormatDocument, but + // this helps the order of execution be more constant in case there + // are problems that arise. This command will always execute the next + // command before doing operations. + [Order(After = PredefinedCommandHandlerNames.PasteTrackingPaste)] + [Order(Before = PredefinedCommandHandlerNames.FormatDocument)] + internal class CSharpAddImportsPasteCommandHandler : AbstractAddImportsPasteCommandHandler + { + [ImportingConstructor] + [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + public CSharpAddImportsPasteCommandHandler(IThreadingContext threadingContext) : base(threadingContext) + { + } + + public override string DisplayName => CSharpEditorResources.Add_Missing_Usings_on_Paste; + protected override string DialogText => CSharpEditorResources.Adding_missing_usings; + } +} diff --git a/src/EditorFeatures/CSharp/CSharpEditorResources.resx b/src/EditorFeatures/CSharp/CSharpEditorResources.resx index 082ec8d8c1746..dc934ab12dff9 100644 --- a/src/EditorFeatures/CSharp/CSharpEditorResources.resx +++ b/src/EditorFeatures/CSharp/CSharpEditorResources.resx @@ -171,4 +171,15 @@ '{0}' items in cache + + Generate Event Subscription + + + Adding missing usings... + Shown in a thread await dialog. "usings" is a language specific term and should not be localized + + + Add Missing Usings on Paste + "usings" is a language specific term and should not be localized + \ No newline at end of file diff --git a/src/VisualStudio/CSharp/Impl/EventHookup/EventHookupCommandHandler.cs b/src/EditorFeatures/CSharp/EventHookup/EventHookupCommandHandler.cs similarity index 100% rename from src/VisualStudio/CSharp/Impl/EventHookup/EventHookupCommandHandler.cs rename to src/EditorFeatures/CSharp/EventHookup/EventHookupCommandHandler.cs diff --git a/src/VisualStudio/CSharp/Impl/EventHookup/EventHookupCommandHandler_SessionCancellingCommands.cs b/src/EditorFeatures/CSharp/EventHookup/EventHookupCommandHandler_SessionCancellingCommands.cs similarity index 87% rename from src/VisualStudio/CSharp/Impl/EventHookup/EventHookupCommandHandler_SessionCancellingCommands.cs rename to src/EditorFeatures/CSharp/EventHookup/EventHookupCommandHandler_SessionCancellingCommands.cs index b3047725248b8..278e2c562220e 100644 --- a/src/VisualStudio/CSharp/Impl/EventHookup/EventHookupCommandHandler_SessionCancellingCommands.cs +++ b/src/EditorFeatures/CSharp/EventHookup/EventHookupCommandHandler_SessionCancellingCommands.cs @@ -5,7 +5,6 @@ #nullable disable using Microsoft.VisualStudio.Commanding; -using Microsoft.VisualStudio.LanguageServices.CSharp; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; namespace Microsoft.CodeAnalysis.Editor.CSharp.EventHookup @@ -13,7 +12,7 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.EventHookup internal partial class EventHookupCommandHandler : ICommandHandler { - public string DisplayName => CSharpVSResources.Generate_Event_Subscription; + public string DisplayName => CSharpEditorResources.Generate_Event_Subscription; public bool ExecuteCommand(EscapeKeyCommandArgs args, CommandExecutionContext context) { diff --git a/src/VisualStudio/CSharp/Impl/EventHookup/EventHookupCommandHandler_TabKeyCommand.cs b/src/EditorFeatures/CSharp/EventHookup/EventHookupCommandHandler_TabKeyCommand.cs similarity index 98% rename from src/VisualStudio/CSharp/Impl/EventHookup/EventHookupCommandHandler_TabKeyCommand.cs rename to src/EditorFeatures/CSharp/EventHookup/EventHookupCommandHandler_TabKeyCommand.cs index cefbfdef70064..ba13894250062 100644 --- a/src/VisualStudio/CSharp/Impl/EventHookup/EventHookupCommandHandler_TabKeyCommand.cs +++ b/src/EditorFeatures/CSharp/EventHookup/EventHookupCommandHandler_TabKeyCommand.cs @@ -175,7 +175,7 @@ private Solution CreateSolutionWithEventHandler( formattedDocument.Id, formattedDocument.GetTextSynchronously(cancellationToken)); } - private Document AddMethodNameAndAnnotationsToSolution( + private static Document AddMethodNameAndAnnotationsToSolution( Document document, string eventHandlerMethodName, int position, @@ -213,7 +213,7 @@ private Document AddMethodNameAndAnnotationsToSolution( return documentWithNameAdded.WithSyntaxRoot(rootWithUpdatedEventHookupExpression); } - private SyntaxNode AddGeneratedHandlerMethodToSolution( + private static SyntaxNode AddGeneratedHandlerMethodToSolution( SemanticDocument document, string eventHandlerMethodName, SyntaxAnnotation plusEqualsTokenAnnotation, @@ -236,7 +236,7 @@ private SyntaxNode AddGeneratedHandlerMethodToSolution( return root.ReplaceNode(typeDecl, typeDeclWithMethodAdded); } - private IMethodSymbol GetMethodSymbol( + private static IMethodSymbol GetMethodSymbol( SemanticDocument semanticDocument, string eventHandlerMethodName, AssignmentExpressionSyntax eventHookupExpression, diff --git a/src/VisualStudio/CSharp/Impl/EventHookup/EventHookupCommandHandler_TypeCharCommand.cs b/src/EditorFeatures/CSharp/EventHookup/EventHookupCommandHandler_TypeCharCommand.cs similarity index 100% rename from src/VisualStudio/CSharp/Impl/EventHookup/EventHookupCommandHandler_TypeCharCommand.cs rename to src/EditorFeatures/CSharp/EventHookup/EventHookupCommandHandler_TypeCharCommand.cs diff --git a/src/VisualStudio/CSharp/Impl/EventHookup/EventHookupSessionManager.cs b/src/EditorFeatures/CSharp/EventHookup/EventHookupSessionManager.cs similarity index 100% rename from src/VisualStudio/CSharp/Impl/EventHookup/EventHookupSessionManager.cs rename to src/EditorFeatures/CSharp/EventHookup/EventHookupSessionManager.cs diff --git a/src/VisualStudio/CSharp/Impl/EventHookup/EventHookupSessionManager_EventHookupSession.cs b/src/EditorFeatures/CSharp/EventHookup/EventHookupSessionManager_EventHookupSession.cs similarity index 100% rename from src/VisualStudio/CSharp/Impl/EventHookup/EventHookupSessionManager_EventHookupSession.cs rename to src/EditorFeatures/CSharp/EventHookup/EventHookupSessionManager_EventHookupSession.cs diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.cs.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.cs.xlf index f50d195b89fff..020765ccfadd0 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.cs.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.cs.xlf @@ -2,6 +2,16 @@ + + Add Missing Usings on Paste + Add Missing Usings on Paste + "usings" is a language specific term and should not be localized + + + Adding missing usings... + Adding missing usings... + Shown in a thread await dialog. "usings" is a language specific term and should not be localized + Chosen version: '{0}' Zvolená verze: {0} @@ -47,6 +57,11 @@ Našlo se jedno sestavení: {0} + + Generate Event Subscription + Generovat odběr událostí + + Load from: '{0}' Načíst z {0} diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.de.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.de.xlf index 48368ebb1821e..9ff72bf90ebbd 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.de.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.de.xlf @@ -2,6 +2,16 @@ + + Add Missing Usings on Paste + Add Missing Usings on Paste + "usings" is a language specific term and should not be localized + + + Adding missing usings... + Adding missing usings... + Shown in a thread await dialog. "usings" is a language specific term and should not be localized + Chosen version: '{0}' Ausgewählte Version: {0} @@ -47,6 +57,11 @@ Einzelne Assembly gefunden: {0} + + Generate Event Subscription + Ereignisabonnement generieren + + Load from: '{0}' Laden von: {0} diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.es.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.es.xlf index b86915f58c9fe..5e943d2232747 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.es.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.es.xlf @@ -2,6 +2,16 @@ + + Add Missing Usings on Paste + Add Missing Usings on Paste + "usings" is a language specific term and should not be localized + + + Adding missing usings... + Adding missing usings... + Shown in a thread await dialog. "usings" is a language specific term and should not be localized + Chosen version: '{0}' Versión elegida: "{0}" @@ -47,6 +57,11 @@ Se encontró un solo ensamblado: "{0}" + + Generate Event Subscription + Generar suscripción de eventos + + Load from: '{0}' Cargar desde: "{0}" diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.fr.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.fr.xlf index 965e7f016ea60..b92559e5cf792 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.fr.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.fr.xlf @@ -2,6 +2,16 @@ + + Add Missing Usings on Paste + Add Missing Usings on Paste + "usings" is a language specific term and should not be localized + + + Adding missing usings... + Adding missing usings... + Shown in a thread await dialog. "usings" is a language specific term and should not be localized + Chosen version: '{0}' Version choisie : '{0}' @@ -47,6 +57,11 @@ Un seul assembly trouvé : '{0}' + + Generate Event Subscription + Générer un abonnement à des événements + + Load from: '{0}' Charger à partir de : '{0}' diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.it.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.it.xlf index 65afc982fc5d6..2a8f93d2ce3c7 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.it.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.it.xlf @@ -2,6 +2,16 @@ + + Add Missing Usings on Paste + Add Missing Usings on Paste + "usings" is a language specific term and should not be localized + + + Adding missing usings... + Adding missing usings... + Shown in a thread await dialog. "usings" is a language specific term and should not be localized + Chosen version: '{0}' Versione selezionata: '{0}' @@ -47,6 +57,11 @@ È stato trovato un solo assembly: '{0}' + + Generate Event Subscription + Genera sottoscrizione di eventi + + Load from: '{0}' Carica da: '{0}' diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ja.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ja.xlf index 4bebabadfda62..27d570ec818c7 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ja.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ja.xlf @@ -2,6 +2,16 @@ + + Add Missing Usings on Paste + Add Missing Usings on Paste + "usings" is a language specific term and should not be localized + + + Adding missing usings... + Adding missing usings... + Shown in a thread await dialog. "usings" is a language specific term and should not be localized + Chosen version: '{0}' 選択されたバージョン: '{0}' @@ -29,7 +39,7 @@ Found '{0}' assemblies for '{1}': - '{1}' の '{0}' 個のアセンブリが見つかりました。 + '{1}' の '{0}' 個のアセンブリが見つかりました: @@ -47,6 +57,11 @@ 1 つのアセンブリが見つかりました: '{0}' + + Generate Event Subscription + イベント サブスクリプションの生成 + + Load from: '{0}' 読み込み元: '{0}' @@ -54,7 +69,7 @@ Module not found! - モジュールが見つかりません。 + モジュールが見つかりません diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ko.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ko.xlf index 293fc33a3dd2a..a09b9f60b3323 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ko.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ko.xlf @@ -2,6 +2,16 @@ + + Add Missing Usings on Paste + Add Missing Usings on Paste + "usings" is a language specific term and should not be localized + + + Adding missing usings... + Adding missing usings... + Shown in a thread await dialog. "usings" is a language specific term and should not be localized + Chosen version: '{0}' 선택한 버전: '{0}' @@ -47,6 +57,11 @@ 단일 어셈블리를 찾았습니다. '{0}' + + Generate Event Subscription + 이벤트 구독 생성 + + Load from: '{0}' 로드 위치: '{0}' diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.pl.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.pl.xlf index 84414c423b55b..5c49dd993f0c5 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.pl.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.pl.xlf @@ -2,6 +2,16 @@ + + Add Missing Usings on Paste + Add Missing Usings on Paste + "usings" is a language specific term and should not be localized + + + Adding missing usings... + Adding missing usings... + Shown in a thread await dialog. "usings" is a language specific term and should not be localized + Chosen version: '{0}' Wybrana wersja: „{0}” @@ -47,6 +57,11 @@ Znaleziono pojedynczy zestaw: „{0}” + + Generate Event Subscription + Generuj subskrypcję zdarzenia + + Load from: '{0}' Załaduj z: „{0}” diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.pt-BR.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.pt-BR.xlf index e1024a85946ec..cd53520fc18f1 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.pt-BR.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.pt-BR.xlf @@ -2,6 +2,16 @@ + + Add Missing Usings on Paste + Add Missing Usings on Paste + "usings" is a language specific term and should not be localized + + + Adding missing usings... + Adding missing usings... + Shown in a thread await dialog. "usings" is a language specific term and should not be localized + Chosen version: '{0}' Versão escolhida: '{0}' @@ -47,6 +57,11 @@ Foi encontrado um assembly: '{0}' + + Generate Event Subscription + Gerar Assinatura de Evento + + Load from: '{0}' Carregar de: '{0}' diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ru.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ru.xlf index 6a274d0ad2597..a15a3ea561b2a 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ru.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ru.xlf @@ -2,6 +2,16 @@ + + Add Missing Usings on Paste + Add Missing Usings on Paste + "usings" is a language specific term and should not be localized + + + Adding missing usings... + Adding missing usings... + Shown in a thread await dialog. "usings" is a language specific term and should not be localized + Chosen version: '{0}' Выбранная версия: "{0}" @@ -47,6 +57,11 @@ Найдена одна сборка: "{0}" + + Generate Event Subscription + Создать подписку на события + + Load from: '{0}' Загрузить из: "{0}" diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.tr.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.tr.xlf index 698cbca8e70da..3609af5a22b88 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.tr.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.tr.xlf @@ -2,6 +2,16 @@ + + Add Missing Usings on Paste + Add Missing Usings on Paste + "usings" is a language specific term and should not be localized + + + Adding missing usings... + Adding missing usings... + Shown in a thread await dialog. "usings" is a language specific term and should not be localized + Chosen version: '{0}' Seçilen sürüm: '{0}' @@ -47,6 +57,11 @@ Tek bütünleştirilmiş kod bulundu: '{0}' + + Generate Event Subscription + Olay Aboneliği Oluştur + + Load from: '{0}' Şuradan yükle: '{0}' diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.zh-Hans.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.zh-Hans.xlf index e9ecfd978c26b..3e41462e2fa0e 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.zh-Hans.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.zh-Hans.xlf @@ -1,7 +1,17 @@  - + + + Add Missing Usings on Paste + Add Missing Usings on Paste + "usings" is a language specific term and should not be localized + + + Adding missing usings... + Adding missing usings... + Shown in a thread await dialog. "usings" is a language specific term and should not be localized + Chosen version: '{0}' 所选版本: "{0}" @@ -47,6 +57,11 @@ 找到单个程序集: "{0}" + + Generate Event Subscription + 生成事件订阅 + + Load from: '{0}' 从以下位置加载: "{0}" diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.zh-Hant.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.zh-Hant.xlf index 4456f4117a91f..601b7c9bf3655 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.zh-Hant.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.zh-Hant.xlf @@ -1,7 +1,17 @@  - + + + Add Missing Usings on Paste + Add Missing Usings on Paste + "usings" is a language specific term and should not be localized + + + Adding missing usings... + Adding missing usings... + Shown in a thread await dialog. "usings" is a language specific term and should not be localized + Chosen version: '{0}' 選擇的版本: '{0}' @@ -47,6 +57,11 @@ 找到單一組件: '{0}' + + Generate Event Subscription + 產生事件訂閱 + + Load from: '{0}' 載入來源: '{0}' diff --git a/src/EditorFeatures/CSharpTest/CodeActions/ConvertLocalFunctionToMethod/ConvertLocalFunctionToMethodTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/ConvertLocalFunctionToMethod/ConvertLocalFunctionToMethodTests.cs index 86ca5bec30ba8..11700e987a376 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/ConvertLocalFunctionToMethod/ConvertLocalFunctionToMethodTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/ConvertLocalFunctionToMethod/ConvertLocalFunctionToMethodTests.cs @@ -821,6 +821,102 @@ C LocalFunction(C c) return null; } } +}"); + } + + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertLocalFunctionToMethod)] + [WorkItem(32976, "https://github.com/dotnet/roslyn/issues/32976")] + public async Task TestUnsafeLocalFunction() + { + await TestInRegularAndScriptAsync( +@"class C +{ + public unsafe void UnsafeFunction() + { + byte b = 1; + [|unsafe byte* GetPtr(byte* bytePt) + { + return bytePt; + }|] + var aReference = GetPtr(&b); + } +}", +@"class C +{ + public unsafe void UnsafeFunction() + { + byte b = 1; + var aReference = GetPtr(&b); + } + + private static unsafe byte* GetPtr(byte* bytePt) + { + return bytePt; + } +}"); + } + + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertLocalFunctionToMethod)] + [WorkItem(32976, "https://github.com/dotnet/roslyn/issues/32976")] + public async Task TestUnsafeLocalFunctionInUnsafeMethod() + { + await TestInRegularAndScriptAsync( +@"class C +{ + public unsafe void UnsafeFunction() + { + byte b = 1; + [|byte* GetPtr(byte* bytePt) + { + return bytePt; + }|] + var aReference = GetPtr(&b); + } +}", +@"class C +{ + public unsafe void UnsafeFunction() + { + byte b = 1; + var aReference = GetPtr(&b); + } + + private static unsafe byte* GetPtr(byte* bytePt) + { + return bytePt; + } +}"); + } + + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertLocalFunctionToMethod)] + [WorkItem(32976, "https://github.com/dotnet/roslyn/issues/32976")] + public async Task TestLocalFunctionInUnsafeMethod() + { + await TestInRegularAndScriptAsync( +@"class C +{ + public unsafe void UnsafeFunction() + { + byte b = 1; + [|byte GetPtr(byte bytePt) + { + return bytePt; + }|] + var aReference = GetPtr(b); + } +}", +@"class C +{ + public unsafe void UnsafeFunction() + { + byte b = 1; + var aReference = GetPtr(b); + } + + private static byte GetPtr(byte bytePt) + { + return bytePt; + } }"); } } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/ReplaceMethodWithProperty/ReplaceMethodWithPropertyTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/ReplaceMethodWithProperty/ReplaceMethodWithPropertyTests.cs index 05b357bc4e284..8aff66360e4c0 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/ReplaceMethodWithProperty/ReplaceMethodWithPropertyTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/ReplaceMethodWithProperty/ReplaceMethodWithPropertyTests.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable - using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeStyle; @@ -2415,7 +2413,7 @@ int Goo private async Task TestWithAllCodeStyleOff( string initialMarkup, string expectedMarkup, - ParseOptions parseOptions = null, int index = 0) + ParseOptions? parseOptions = null, int index = 0) { await TestAsync( initialMarkup, expectedMarkup, parseOptions, diff --git a/src/EditorFeatures/CSharpTest/CodeActions/ReplacePropertyWithMethods/ReplacePropertyWithMethodsTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/ReplacePropertyWithMethods/ReplacePropertyWithMethodsTests.cs index e7867fdcd6ebf..38a90857c12f4 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/ReplacePropertyWithMethods/ReplacePropertyWithMethodsTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/ReplacePropertyWithMethods/ReplacePropertyWithMethodsTests.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable - using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeStyle; @@ -1889,6 +1887,94 @@ void Main() }"); } + [WorkItem(45171, "https://github.com/dotnet/roslyn/issues/45171")] + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] + public async Task TestReferenceInImplicitObjectInitializer() + { + await TestInRegularAndScriptAsync( +@"public class Tweet +{ + public string [||]Tweet { get; } +} + +class C +{ + void Main() + { + var t = new Tweet(); + Tweet t1 = new() + { + Tweet = t.Tweet + }; + } +}", +@"public class Tweet +{ + private readonly string tweet; + + public string GetTweet() + { + return tweet; + } +} + +class C +{ + void Main() + { + var t = new Tweet(); + Tweet t1 = new() + { + {|Conflict:Tweet|} = t.GetTweet() + }; + } +}"); + } + + [WorkItem(45171, "https://github.com/dotnet/roslyn/issues/45171")] + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] + public async Task TestReferenceInWithInitializer() + { + await TestInRegularAndScriptAsync( +@"public class Tweet +{ + public string [||]Tweet { get; } +} + +class C +{ + void Main() + { + var t = new Tweet(); + var t1 = t with + { + Tweet = t.Tweet + }; + } +}", +@"public class Tweet +{ + private readonly string tweet; + + public string GetTweet() + { + return tweet; + } +} + +class C +{ + void Main() + { + var t = new Tweet(); + var t1 = t with + { + {|Conflict:Tweet|} = t.GetTweet() + }; + } +}"); + } + private OptionsCollection PreferExpressionBodiedMethods => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement } }; } diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ExtensionMethodImportCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ExtensionMethodImportCompletionProviderTests.cs index 527c8e8308225..9c1d6bf8f0177 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ExtensionMethodImportCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ExtensionMethodImportCompletionProviderTests.cs @@ -1888,6 +1888,120 @@ await VerifyImportItemIsAbsentAsync( } } + [Fact, Trait(Traits.Feature, Traits.Features.Completion)] + public async Task TestCommitWithSemicolonForMethod() + { + var markup = @" +public class C +{ +} +namespace AA +{ + public static class Ext + { + public static int ToInt(this C c) + => 1; + } +} + +namespace BB +{ + public class B + { + public void M() + { + var c = new C(); + c.$$ + } + } +}"; + + var expected = @" +using AA; + +public class C +{ +} +namespace AA +{ + public static class Ext + { + public static int ToInt(this C c) + => 1; + } +} + +namespace BB +{ + public class B + { + public void M() + { + var c = new C(); + c.ToInt(); + } + } +}"; + await VerifyProviderCommitAsync(markup, "ToInt", expected, commitChar: ';', sourceCodeKind: SourceCodeKind.Regular); + } + + [Fact, Trait(Traits.Feature, Traits.Features.Completion)] + public async Task TestCommitWithSemicolonForMethodForDelegateContext() + { + var markup = @" +public class C +{ +} +namespace AA +{ + public static class Ext + { + public static int ToInt(this C c) + => 1; + } +} + +namespace BB +{ + public class B + { + public void M() + { + var c = new C(); + c.$$ + } + } +}"; + + var expected = @" +using AA; + +public class C +{ +} +namespace AA +{ + public static class Ext + { + public static int ToInt(this C c) + => 1; + } +} + +namespace BB +{ + public class B + { + public void M() + { + var c = new C(); + c.ToInt(); + } + } +}"; + await VerifyProviderCommitAsync(markup, "ToInt", expected, commitChar: ';', sourceCodeKind: SourceCodeKind.Regular); + } + [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestTimeBox() { diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ObjectCreationCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ObjectCreationCompletionProviderTests.cs index 67e81c56be320..3c224495cb7ca 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ObjectCreationCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ObjectCreationCompletionProviderTests.cs @@ -677,5 +677,113 @@ void M() "; await VerifyItemExistsAsync(markup, "List"); } + + [Fact, Trait(Traits.Feature, Traits.Features.Completion)] + public async Task CreateObjectAndCommitWithSemicolon() + { + var markup = @" +class Program +{ + void Bar() + { + object o = new $$ + } +}"; + var expectedMark = @" +class Program +{ + void Bar() + { + object o = new object(); + } +}"; + await VerifyProviderCommitAsync(markup, "object", expectedMark, commitChar: ';'); + } + + [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] + public async Task CreateNullableObjectAndCommitWithSemicolon() + { + var markup = @" +class Program +{ + void Bar() + { + object? o = new $$ + } +}"; + var expectedMark = @" +class Program +{ + void Bar() + { + object? o = new object(); + } +}"; + await VerifyProviderCommitAsync(markup, "object", expectedMark, commitChar: ';'); + } + + [Fact, Trait(Traits.Feature, Traits.Features.Completion)] + public async Task CreateStringAsLocalAndCommitWithSemicolon() + { + var markup = @" +class Program +{ + void Bar() + { + string o = new $$ + } +}"; + var expectedMark = @" +class Program +{ + void Bar() + { + string o = new string(); + } +}"; + await VerifyProviderCommitAsync(markup, "string", expectedMark, commitChar: ';'); + } + + [Fact, Trait(Traits.Feature, Traits.Features.Completion)] + public async Task CreateGenericListAsLocalAndCommitWithSemicolon() + { + var markup = @" +using System.Collections.Generic; +class Program +{ + void Bar() + { + List o = new $$ + } +}"; + var expectedMark = @" +using System.Collections.Generic; +class Program +{ + void Bar() + { + List o = new List(); + } +}"; + await VerifyProviderCommitAsync(markup, "List", expectedMark, commitChar: ';'); + } + + [Fact, Trait(Traits.Feature, Traits.Features.Completion)] + public async Task CreateGenericListAsFieldAndCommitWithSemicolon() + { + var markup = @" +using System.Collections.Generic; +class Program +{ + private List o = new $$ +}"; + var expectedMark = @" +using System.Collections.Generic; +class Program +{ + private List o = new List(); +}"; + await VerifyProviderCommitAsync(markup, "List", expectedMark, commitChar: ';'); + } } } diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SymbolCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SymbolCompletionProviderTests.cs index 8fd26fea88722..d900c96828281 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SymbolCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SymbolCompletionProviderTests.cs @@ -10759,6 +10759,186 @@ await VerifyItemIsAbsentAsync( matchingFilters: new List { FilterSet.LocalAndParameterFilter }); } + [Fact, Trait(Traits.Feature, Traits.Features.Completion)] + public async Task CompletionWithSemicolonForMethod() + { + var markup = @" +class Program +{ + private void Bar() + { + F$$ + } + + private void Foo(int i) + { + } + + private void Foo(int i, int c) + { + } +}"; + var expected = @" +class Program +{ + private void Bar() + { + Foo(); + } + + private void Foo(int i) + { + } + + private void Foo(int i, int c) + { + } +}"; + await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: ';'); + } + + [Fact, Trait(Traits.Feature, Traits.Features.Completion)] + public async Task CompletionWithSemicolonInNestedMethod() + { + var markup = @" +class Program +{ + private void Bar() + { + Foo(F$$); + } + + private int Foo(int i) + { + return 1; + } +}"; + var expected = @" +class Program +{ + private void Bar() + { + Foo(Foo();); + } + + private int Foo(int i) + { + return 1; + } +}"; + await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: ';'); + } + + [Fact, Trait(Traits.Feature, Traits.Features.Completion)] + public async Task CompletionWithSemicolonForDelegateInferredType() + { + var markup = @" +using System; +class Program +{ + private void Bar() + { + Bar2(F$$); + } + + private void Foo() + { + } + + void Bar2(Action t) { } +}"; + var expected = @" +using System; +class Program +{ + private void Bar() + { + Bar2(Foo;); + } + + private void Foo() + { + } + + void Bar2(Action t) { } +}"; + await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: ';'); + } + + [Fact, Trait(Traits.Feature, Traits.Features.Completion)] + public async Task CompletionWithSemicolonForConstructor() + { + var markup = @" +class Program +{ + private static void Bar() + { + var o = new P$$ + } +}"; + var expected = @" +class Program +{ + private static void Bar() + { + var o = new Program(); + } +}"; + await VerifyProviderCommitAsync(markup, "Program", expected, commitChar: ';'); + } + + [Fact, Trait(Traits.Feature, Traits.Features.Completion)] + public async Task CompletionWithSemicolonForTypeUnderNonObjectCreationContext() + { + var markup = @" +class Program +{ + private static void Bar() + { + var o = P$$ + } +}"; + var expected = @" +class Program +{ + private static void Bar() + { + var o = Program; + } +}"; + await VerifyProviderCommitAsync(markup, "Program", expected, commitChar: ';'); + } + + [Fact, Trait(Traits.Feature, Traits.Features.Completion)] + public async Task CompletionWithSemicolonForAliasConstructor() + { + var markup = @" +using String2 = System.String; +namespace Bar1 +{ + class Program + { + private static void Bar() + { + var o = new S$$ + } + } +}"; + var expected = @" +using String2 = System.String; +namespace Bar1 +{ + class Program + { + private static void Bar() + { + var o = new String2(); + } + } +}"; + await VerifyProviderCommitAsync(markup, "String2", expected, commitChar: ';'); + } + [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterPatternMatch() diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/TypeImportCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/TypeImportCompletionProviderTests.cs index c964510fa0343..6fe02f582afe1 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/TypeImportCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/TypeImportCompletionProviderTests.cs @@ -1562,6 +1562,96 @@ await VerifyTypeImportItemIsAbsentAsync( } } + [Fact, Trait(Traits.Feature, Traits.Features.Completion)] + public async Task TestCommitWithSemicolonForParameterlessConstructor() + { + var markup = @" +namespace AA +{ + public class C + { + } +} + +namespace BB +{ + public class B + { + public void M() + { + var c = new $$ + } + } +}"; + + var expected = @" +using AA; + +namespace AA +{ + public class C + { + } +} + +namespace BB +{ + public class B + { + public void M() + { + var c = new C(); + } + } +}"; + await VerifyProviderCommitAsync(markup, "C", expected, commitChar: ';', sourceCodeKind: SourceCodeKind.Regular); + } + + [Fact, Trait(Traits.Feature, Traits.Features.Completion)] + public async Task TestCommitWithSemicolonUnderNonObjectCreationContext() + { + var markup = @" +namespace AA +{ + public class C + { + } +} + +namespace BB +{ + public class B + { + public void M() + { + $$ + } + } +}"; + + var expected = @" +using AA; + +namespace AA +{ + public class C + { + } +} + +namespace BB +{ + public class B + { + public void M() + { + C; + } + } +}"; + await VerifyProviderCommitAsync(markup, "C", expected, commitChar: ';', sourceCodeKind: SourceCodeKind.Regular); + } + private Task VerifyTypeImportItemExistsAsync(string markup, string expectedItem, int glyph, string inlineDescription, string displayTextSuffix = null, string expectedDescriptionOrNull = null, CompletionItemFlags? flags = null) => VerifyItemExistsAsync(markup, expectedItem, displayTextSuffix: displayTextSuffix, glyph: glyph, inlineDescription: inlineDescription, expectedDescriptionOrNull: expectedDescriptionOrNull, flags: flags); diff --git a/src/EditorFeatures/CSharpTest/EditAndContinue/CSharpEditAndContinueAnalyzerTests.cs b/src/EditorFeatures/CSharpTest/EditAndContinue/CSharpEditAndContinueAnalyzerTests.cs index d45049796eac7..d79c6319c0fd7 100644 --- a/src/EditorFeatures/CSharpTest/EditAndContinue/CSharpEditAndContinueAnalyzerTests.cs +++ b/src/EditorFeatures/CSharpTest/EditAndContinue/CSharpEditAndContinueAnalyzerTests.cs @@ -746,7 +746,9 @@ public async Task AnalyzeDocumentAsync_InternalError(bool outOfMemory) var expectedDiagnostic = outOfMemory ? $"ENC0089: {string.Format(FeaturesResources.Modifying_source_file_will_prevent_the_debug_session_from_continuing_because_the_file_is_too_big, "src.cs")}" : - $"ENC0080: {string.Format(FeaturesResources.Modifying_source_file_will_prevent_the_debug_session_from_continuing_due_to_internal_error, "src.cs", "System.NullReferenceException: NullRef!")}"; + // Because the error message that is formatted into this template string includes a stacktrace with newlines, we need to replicate that behavior + // here so that any trailing punctuation is removed from the translated template string. + $"ENC0080: {string.Format(FeaturesResources.Modifying_source_file_will_prevent_the_debug_session_from_continuing_due_to_internal_error, "src.cs", "System.NullReferenceException: NullRef!\n")}".Split('\n').First(); AssertEx.Equal(new[] { expectedDiagnostic }, result.RudeEditErrors.Select(d => d.ToDiagnostic(newSyntaxTree)) .Select(d => $"{d.Id}: {d.GetMessage().Split(new[] { Environment.NewLine }, StringSplitOptions.None).First()}")); diff --git a/src/VisualStudio/CSharp/Test/EventHookup/EventHookupCommandHandlerTests.cs b/src/EditorFeatures/CSharpTest/EventHookup/EventHookupCommandHandlerTests.cs similarity index 99% rename from src/VisualStudio/CSharp/Test/EventHookup/EventHookupCommandHandlerTests.cs rename to src/EditorFeatures/CSharpTest/EventHookup/EventHookupCommandHandlerTests.cs index 69e3765f74b2e..6fbb7e3cbe8fb 100644 --- a/src/VisualStudio/CSharp/Test/EventHookup/EventHookupCommandHandlerTests.cs +++ b/src/EditorFeatures/CSharpTest/EventHookup/EventHookupCommandHandlerTests.cs @@ -1024,7 +1024,7 @@ private void C_MyEvent() testState.AssertCodeIs(expectedCode); } - private OptionsCollection QualifyMethodAccessWithNotification(NotificationOption2 notification) + private static OptionsCollection QualifyMethodAccessWithNotification(NotificationOption2 notification) => new OptionsCollection(LanguageNames.CSharp) { { CodeStyleOptions2.QualifyMethodAccess, true, notification } }; } } diff --git a/src/VisualStudio/CSharp/Test/EventHookup/EventHookupTestState.cs b/src/EditorFeatures/CSharpTest/EventHookup/EventHookupTestState.cs similarity index 96% rename from src/VisualStudio/CSharp/Test/EventHookup/EventHookupTestState.cs rename to src/EditorFeatures/CSharpTest/EventHookup/EventHookupTestState.cs index e97c9449f4390..777d4295d248c 100644 --- a/src/VisualStudio/CSharp/Test/EventHookup/EventHookupTestState.cs +++ b/src/EditorFeatures/CSharpTest/EventHookup/EventHookupTestState.cs @@ -21,7 +21,6 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.EventHookup { internal sealed class EventHookupTestState : AbstractCommandHandlerTestState { - // TODO: It seems that we can move EventHookupSessionManager to EditorFeatures (https://github.com/dotnet/roslyn/issues/46280) private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeaturesWpf.AddParts( typeof(EventHookupCommandHandler), typeof(EventHookupSessionManager)); diff --git a/src/EditorFeatures/CSharpTest/Formatting/FormattingEngineTests.cs b/src/EditorFeatures/CSharpTest/Formatting/FormattingEngineTests.cs index 1b46437a32ceb..2a69b980f066a 100644 --- a/src/EditorFeatures/CSharpTest/Formatting/FormattingEngineTests.cs +++ b/src/EditorFeatures/CSharpTest/Formatting/FormattingEngineTests.cs @@ -2234,6 +2234,34 @@ public void SeparateGroups_GroupIfSorted_RecognizeSystemNotFirst() AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true)); } + [Fact, WorkItem(49492, "https://github.com/dotnet/roslyn/issues/49492")] + public void PreserveAnnotationsOnMultiLineTrivia() + { + var text = @" +namespace TestApp +{ + class Test + { + /* __marker__ */ + } +} +"; + + var position = text.IndexOf("/* __marker__ */"); + var syntaxTree = CSharpSyntaxTree.ParseText(text); + var root = syntaxTree.GetRoot(); + + var annotation = new SyntaxAnnotation("marker"); + var markerTrivia = root.FindTrivia(position, findInsideTrivia: true); + var annotatedMarkerTrivia = markerTrivia.WithAdditionalAnnotations(annotation); + root = root.ReplaceTrivia(markerTrivia, annotatedMarkerTrivia); + + var formattedRoot = Formatter.Format(root, new AdhocWorkspace()); + var annotatedTrivia = formattedRoot.GetAnnotatedTrivia("marker"); + + Assert.Single(annotatedTrivia); + } + private static void AssertFormatAfterTypeChar(string code, string expected, Dictionary changedOptionSet = null) { using var workspace = TestWorkspace.CreateCSharp(code); diff --git a/src/EditorFeatures/CSharpTest/GenerateVariable/GenerateVariableTests.cs b/src/EditorFeatures/CSharpTest/GenerateVariable/GenerateVariableTests.cs index 4a745489fd545..f5a0a5770ae48 100644 --- a/src/EditorFeatures/CSharpTest/GenerateVariable/GenerateVariableTests.cs +++ b/src/EditorFeatures/CSharpTest/GenerateVariable/GenerateVariableTests.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable - using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; @@ -38,7 +36,7 @@ public GenerateVariableTests(ITestOutputHelper logger) { } - internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) + internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpGenerateVariableCodeFixProvider()); private readonly CodeStyleOption2 onWithInfo = new CodeStyleOption2(true, NotificationOption2.Suggestion); @@ -3515,6 +3513,36 @@ void goo() }"); } + [WorkItem(49294, "https://github.com/dotnet/roslyn/issues/49294")] + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] + public async Task TestPropertyInWithInitializer() + { + await TestInRegularAndScriptAsync( +@"record Goo +{ +} + +class Bar +{ + void goo(Goo g) + { + var c = g with { [|Gibberish|] = 24 }; + } +}", +@"record Goo +{ + public int Gibberish { get; internal set; } +} + +class Bar +{ + void goo(Goo g) + { + var c = g with { Gibberish = 24 }; + } +}"); + } + [WorkItem(13166, "https://github.com/dotnet/roslyn/issues/13166")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyOnNestedObjectInitializer() diff --git a/src/EditorFeatures/CSharpTest/ImplementInterface/ImplementInterfaceTests.cs b/src/EditorFeatures/CSharpTest/ImplementInterface/ImplementInterfaceTests.cs index 8d415fdc7ddca..55566b6cc9e86 100644 --- a/src/EditorFeatures/CSharpTest/ImplementInterface/ImplementInterfaceTests.cs +++ b/src/EditorFeatures/CSharpTest/ImplementInterface/ImplementInterfaceTests.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable - using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; @@ -31,7 +29,7 @@ public ImplementInterfaceTests(ITestOutputHelper logger) { } - internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) + internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpImplementInterfaceCodeFixProvider()); private OptionsCollection AllOptionsOff @@ -118,7 +116,7 @@ internal sealed class DoesNotReturnIfAttribute : Attribute internal async Task TestWithAllCodeStyleOptionsOffAsync( string initialMarkup, string expectedMarkup, - int index = 0, ParseOptions parseOptions = null) + int index = 0, ParseOptions? parseOptions = null) { await TestAsync(initialMarkup, expectedMarkup, parseOptions, null, index, options: AllOptionsOff); @@ -126,7 +124,7 @@ await TestAsync(initialMarkup, expectedMarkup, parseOptions, null, internal async Task TestWithAllCodeStyleOptionsOnAsync( string initialMarkup, string expectedMarkup, - int index = 0, ParseOptions parseOptions = null) + int index = 0, ParseOptions? parseOptions = null) { await TestAsync(initialMarkup, expectedMarkup, parseOptions, null, index, options: AllOptionsOn); @@ -134,7 +132,7 @@ await TestAsync(initialMarkup, expectedMarkup, parseOptions, null, internal async Task TestWithAccessorCodeStyleOptionsOnAsync( string initialMarkup, string expectedMarkup, - int index = 0, ParseOptions parseOptions = null) + int index = 0, ParseOptions? parseOptions = null) { await TestAsync(initialMarkup, expectedMarkup, parseOptions, null, index, options: AccessorOptionsOn); @@ -8750,6 +8748,194 @@ public void M1() throw new System.NotImplementedException(); } } +"); + } + + [WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")] + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] + public async Task TestUnconstrainedGenericInstantiatedWithValueType() + { + await TestInRegularAndScriptAsync(@" +interface IGoo +{ + void Bar(T? x); +} + +class C : [|IGoo|] +{ +} +", +@" +interface IGoo +{ + void Bar(T? x); +} + +class C : IGoo +{ + public void Bar(int x) + { + throw new System.NotImplementedException(); + } +} +"); + } + + [WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")] + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] + public async Task TestConstrainedGenericInstantiatedWithValueType() + { + await TestInRegularAndScriptAsync(@" +interface IGoo where T : struct +{ + void Bar(T? x); +} + +class C : [|IGoo|] +{ +} +", +@" +interface IGoo where T : struct +{ + void Bar(T? x); +} + +class C : IGoo +{ + public void Bar(int? x) + { + throw new System.NotImplementedException(); + } +} +"); + } + + [WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")] + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] + public async Task TestUnconstrainedGenericInstantiatedWithReferenceType() + { + await TestInRegularAndScriptAsync(@" +interface IGoo +{ + void Bar(T? x); +} + +class C : [|IGoo|] +{ +} +", +@" +interface IGoo +{ + void Bar(T? x); +} + +class C : IGoo +{ + public void Bar(string x) + { + throw new System.NotImplementedException(); + } +} +"); + } + + [WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")] + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] + public async Task TestUnconstrainedGenericInstantiatedWithReferenceType_NullableEnable() + { + await TestInRegularAndScriptAsync(@" +#nullable enable + +interface IGoo +{ + void Bar(T? x); +} + +class C : [|IGoo|] +{ +} +", +@" +#nullable enable + +interface IGoo +{ + void Bar(T? x); +} + +class C : IGoo +{ + public void Bar(string? x) + { + throw new System.NotImplementedException(); + } +} +"); + } + + [WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")] + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] + public async Task TestConstrainedGenericInstantiatedWithReferenceType() + { + await TestInRegularAndScriptAsync(@" +interface IGoo where T : class +{ + void Bar(T? x); +} + +class C : [|IGoo|] +{ +} +", +@" +interface IGoo where T : class +{ + void Bar(T? x); +} + +class C : IGoo +{ + public void Bar(string x) + { + throw new System.NotImplementedException(); + } +} +"); + } + + [WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")] + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] + public async Task TestConstrainedGenericInstantiatedWithReferenceType_NullableEnable() + { + await TestInRegularAndScriptAsync(@" +#nullable enable + +interface IGoo where T : class +{ + void Bar(T? x); +} + +class C : [|IGoo|] +{ +} +", +@" +#nullable enable + +interface IGoo where T : class +{ + void Bar(T? x); +} + +class C : IGoo +{ + public void Bar(string? x) + { + throw new System.NotImplementedException(); + } +} "); } } diff --git a/src/EditorFeatures/CSharpTest/QuickInfo/DiagnosticAnalyzerQuickInfoSourceTests.cs b/src/EditorFeatures/CSharpTest/QuickInfo/DiagnosticAnalyzerQuickInfoSourceTests.cs index b729f3936a42a..b5b3c87c1e964 100644 --- a/src/EditorFeatures/CSharpTest/QuickInfo/DiagnosticAnalyzerQuickInfoSourceTests.cs +++ b/src/EditorFeatures/CSharpTest/QuickInfo/DiagnosticAnalyzerQuickInfoSourceTests.cs @@ -29,7 +29,7 @@ public class DiagnosticAnalyzerQuickInfoSourceTests { [WorkItem(46604, "https://github.com/dotnet/roslyn/issues/46604")] [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] - public async Task ErrorTileIsShownOnDisablePragma() + public async Task ErrorTitleIsShownOnDisablePragma() { await TestInMethodAsync( @" @@ -41,7 +41,7 @@ await TestInMethodAsync( [WorkItem(46604, "https://github.com/dotnet/roslyn/issues/46604")] [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] - public async Task ErrorTileIsShownOnRestorePragma() + public async Task ErrorTitleIsShownOnRestorePragma() { await TestInMethodAsync( @" @@ -61,6 +61,42 @@ await TestInMethodAsync( ", GetFormattedErrorTitle(ErrorCode.WRN_UnreferencedVarAssg)); } + [WorkItem(49102, "https://github.com/dotnet/roslyn/issues/49102")] + [WpfTheory, Trait(Traits.Feature, Traits.Features.QuickInfo)] + [InlineData("CS0219$$")] + [InlineData("219$$")] + [InlineData("0219$$")] + [InlineData("CS02$$19")] + [InlineData("2$$19")] + [InlineData("02$$19")] + public async Task PragmaWarningCompilerWarningSyntaxKinds(string warning) + { + // Reference: https://docs.microsoft.com/en-US/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-pragma-warning + // "A comma-separated list of warning numbers. The "CS" prefix is optional." + await TestInMethodAsync( +@$" +#pragma warning disable {warning} +", GetFormattedErrorTitle(ErrorCode.WRN_UnreferencedVarAssg)); + } + + [WorkItem(49102, "https://github.com/dotnet/roslyn/issues/49102")] + [WpfTheory, Trait(Traits.Feature, Traits.Features.QuickInfo)] + [InlineData("#pragma warning $$CS0219", null)] + [InlineData("#pragma warning disable$$", null)] + [InlineData("#pragma warning disable $$true", null)] + [InlineData("#pragma warning disable $$219.0", (int)ErrorCode.WRN_UnreferencedVarAssg)] + [InlineData("#pragma warning disable $$219.5", (int)ErrorCode.WRN_UnreferencedVarAssg)] + public async Task PragmaWarningDoesNotThrowInBrokenSyntax(string pragma, int? errorCode) + { + var expectedDescription = errorCode is int errorCodeValue + ? GetFormattedErrorTitle((ErrorCode)errorCodeValue) + : ""; + await TestInMethodAsync( +@$" +{pragma} +", expectedDescription); + } + [WorkItem(46604, "https://github.com/dotnet/roslyn/issues/46604")] [WpfTheory, Trait(Traits.Feature, Traits.Features.QuickInfo)] [InlineData("#pragma warning disable $$CS0162", (int)ErrorCode.WRN_UnreachableCode)] diff --git a/src/EditorFeatures/CSharpTest/ReplaceDocCommentTextWithTag/ReplaceDocCommentTextWithTagTests.cs b/src/EditorFeatures/CSharpTest/ReplaceDocCommentTextWithTag/ReplaceDocCommentTextWithTagTests.cs index 91e6b12f0582d..db92ab57c37bf 100644 --- a/src/EditorFeatures/CSharpTest/ReplaceDocCommentTextWithTag/ReplaceDocCommentTextWithTagTests.cs +++ b/src/EditorFeatures/CSharpTest/ReplaceDocCommentTextWithTag/ReplaceDocCommentTextWithTagTests.cs @@ -448,6 +448,42 @@ await TestMissingAsync( class C { void WriteLine(TKey value) { } +}"); + } + + [WorkItem(38370, "https://github.com/dotnet/roslyn/issues/38370")] + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)] + public async Task TestBaseKeyword() + { + await TestInRegularAndScriptAsync( +@" +/// Testing keyword [||]base. +class C +{ +}", + +@" +/// Testing keyword . +class C +{ +}"); + } + + [WorkItem(38370, "https://github.com/dotnet/roslyn/issues/38370")] + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)] + public async Task TestThisKeyword() + { + await TestInRegularAndScriptAsync( +@" +/// Testing keyword [||]this. +class C +{ +}", + +@" +/// Testing keyword . +class C +{ }"); } } diff --git a/src/EditorFeatures/Core.Cocoa/EventHookup/EventHookupCommandHandler.cs b/src/EditorFeatures/Core.Cocoa/EventHookup/EventHookupCommandHandler.cs deleted file mode 100644 index bf466ddd85c4f..0000000000000 --- a/src/EditorFeatures/Core.Cocoa/EventHookup/EventHookupCommandHandler.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. - -#nullable disable - -using System; -using System.ComponentModel.Composition; -using System.Threading; -using Microsoft.CodeAnalysis.Editor.Shared.Utilities; -using Microsoft.CodeAnalysis.Host.Mef; -using Microsoft.CodeAnalysis.Shared.TestHooks; -using Microsoft.VisualStudio.Utilities; -using VSCommanding = Microsoft.VisualStudio.Commanding; - -namespace Microsoft.CodeAnalysis.Editor.CSharp.EventHookup -{ - /// - /// Ignores commands until '=' is pressed, at which point we determine if the '=' is part of a - /// "+=" that is used to attach an event handler to an event. Once we determine that it is a - /// "+=" attaching an event handler to an event, we show a UI that tells the user they can hit - /// tab to generate a handler method. - /// - /// Once we receive the '=' we watch all actions within the buffer. Anything (including use of - /// directional arrows) other than a typed space removes the UI or cancels any background - /// computation. - /// - /// The determination of whether the "+=" is being used to attach an event handler to an event - /// can be costly, so it operates on a background thread. After the '=' of a "+=" is typed, - /// only a tab will cause the UI thread to block while it determines whether we should - /// intercept the tab and generate an event handler or just let the tab through to other - /// handlers. - /// - /// Because we are explicitly asking the user to tab, so we should handle the tab command before - /// Automatic Completion. - /// - [Export(typeof(VSCommanding.ICommandHandler))] - [ContentType(ContentTypeNames.CSharpContentType)] - [Name(PredefinedCommandHandlerNames.EventHookup)] - [Order(Before = PredefinedCommandHandlerNames.AutomaticCompletion)] - internal partial class EventHookupCommandHandler : ForegroundThreadAffinitizedObject - { - private readonly IInlineRenameService _inlineRenameService; - private readonly IAsynchronousOperationListener _asyncListener; - - internal readonly EventHookupSessionManager EventHookupSessionManager; - - // For testing purposes only! Will always be null except in certain tests. - internal Mutex TESTSessionHookupMutex = null; - - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public EventHookupCommandHandler( - IThreadingContext threadingContext, - IInlineRenameService inlineRenameService, - IAsynchronousOperationListenerProvider listenerProvider, - EventHookupSessionManager eventHookupSessionManager) - : base(threadingContext) - { - _inlineRenameService = inlineRenameService; - _asyncListener = listenerProvider.GetListener(FeatureAttribute.EventHookup); - - this.EventHookupSessionManager = eventHookupSessionManager; - } - } -} diff --git a/src/EditorFeatures/Core.Cocoa/EventHookup/EventHookupCommandHandler_SessionCancellingCommands.cs b/src/EditorFeatures/Core.Cocoa/EventHookup/EventHookupCommandHandler_SessionCancellingCommands.cs deleted file mode 100644 index b41731ce5f26a..0000000000000 --- a/src/EditorFeatures/Core.Cocoa/EventHookup/EventHookupCommandHandler_SessionCancellingCommands.cs +++ /dev/null @@ -1,30 +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.VisualStudio.Commanding; -using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; -using Microsoft.VisualStudio.UI; -using VSCommanding = Microsoft.VisualStudio.Commanding; - -namespace Microsoft.CodeAnalysis.Editor.CSharp.EventHookup -{ - internal partial class EventHookupCommandHandler : - VSCommanding.ICommandHandler - { - public string DisplayName => GettextCatalog.GetString("Generate Event Subscription"); - - public bool ExecuteCommand(EscapeKeyCommandArgs args, CommandExecutionContext context) - { - AssertIsForeground(); - EventHookupSessionManager.CancelAndDismissExistingSessions(); - return false; - } - - public VSCommanding.CommandState GetCommandState(EscapeKeyCommandArgs args) - { - AssertIsForeground(); - return VSCommanding.CommandState.Unspecified; - } - } -} diff --git a/src/EditorFeatures/Core.Cocoa/EventHookup/EventHookupCommandHandler_TabKeyCommand.cs b/src/EditorFeatures/Core.Cocoa/EventHookup/EventHookupCommandHandler_TabKeyCommand.cs deleted file mode 100644 index e05bd86d814c9..0000000000000 --- a/src/EditorFeatures/Core.Cocoa/EventHookup/EventHookupCommandHandler_TabKeyCommand.cs +++ /dev/null @@ -1,409 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -#nullable disable - -using System; -using System.Collections.Immutable; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis.CodeGeneration; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Editing; -using Microsoft.CodeAnalysis.Editor.Shared.Extensions; -using Microsoft.CodeAnalysis.Editor.Shared.Options; -using Microsoft.CodeAnalysis.Formatting; -using Microsoft.CodeAnalysis.Internal.Log; -using Microsoft.CodeAnalysis.LanguageServices; -using Microsoft.CodeAnalysis.Shared.Extensions; -using Microsoft.CodeAnalysis.Simplification; -using Microsoft.CodeAnalysis.Text; -using Microsoft.CodeAnalysis.Text.Shared.Extensions; -using Microsoft.VisualStudio.Commanding; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Editor; -using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; -using Roslyn.Utilities; -using VSCommanding = Microsoft.VisualStudio.Commanding; - -namespace Microsoft.CodeAnalysis.Editor.CSharp.EventHookup -{ - internal partial class EventHookupCommandHandler : IChainedCommandHandler - { - public void ExecuteCommand(TabKeyCommandArgs args, Action nextHandler, CommandExecutionContext cotext) - { - AssertIsForeground(); - if (!args.SubjectBuffer.GetFeatureOnOffOption(InternalFeatureOnOffOptions.EventHookup)) - { - nextHandler(); - return; - } - - if (EventHookupSessionManager.CurrentSession == null) - { - nextHandler(); - return; - } - - // Handling tab is currently uncancellable. - HandleTabWorker(args.TextView, args.SubjectBuffer, nextHandler, CancellationToken.None); - } - - public VSCommanding.CommandState GetCommandState(TabKeyCommandArgs args, Func nextHandler) - { - AssertIsForeground(); - if (EventHookupSessionManager.CurrentSession != null) - { - return VSCommanding.CommandState.Available; - } - else - { - return nextHandler(); - } - } - - private void HandleTabWorker(ITextView textView, ITextBuffer subjectBuffer, Action nextHandler, CancellationToken cancellationToken) - { - AssertIsForeground(); - - // For test purposes only! - if (EventHookupSessionManager.CurrentSession.TESTSessionHookupMutex != null) - { - try - { - EventHookupSessionManager.CurrentSession.TESTSessionHookupMutex.ReleaseMutex(); - } - catch (ApplicationException) - { - } - } - - // Blocking wait (if necessary) to determine whether to consume the tab and - // generate the event handler. - EventHookupSessionManager.CurrentSession.GetEventNameTask.Wait(cancellationToken); - - string eventHandlerMethodName = null; - if (EventHookupSessionManager.CurrentSession.GetEventNameTask.Status == TaskStatus.RanToCompletion) - { - eventHandlerMethodName = EventHookupSessionManager.CurrentSession.GetEventNameTask.WaitAndGetResult(cancellationToken); - } - - if (eventHandlerMethodName == null || - EventHookupSessionManager.CurrentSession.TextView != textView) - { - nextHandler(); - EventHookupSessionManager.CancelAndDismissExistingSessions(); - return; - } - - // This tab means we should generate the event handler method. Begin the code - // generation process. - GenerateAndAddEventHandler(textView, subjectBuffer, eventHandlerMethodName, nextHandler, cancellationToken); - } - - private void GenerateAndAddEventHandler(ITextView textView, ITextBuffer subjectBuffer, string eventHandlerMethodName, Action nextHandler, CancellationToken cancellationToken) - { - AssertIsForeground(); - - using (Logger.LogBlock(FunctionId.EventHookup_Generate_Handler, cancellationToken)) - { - EventHookupSessionManager.CancelAndDismissExistingSessions(); - - var workspace = textView.TextSnapshot.TextBuffer.GetWorkspace(); - if (workspace == null) - { - nextHandler(); - EventHookupSessionManager.CancelAndDismissExistingSessions(); - return; - } - - var document = textView.TextSnapshot.GetOpenDocumentInCurrentContextWithChanges(); - if (document == null) - { - Contract.Fail("Event Hookup could not find the document for the IBufferView."); - } - - var position = textView.GetCaretPoint(subjectBuffer).Value.Position; - var solutionWithEventHandler = CreateSolutionWithEventHandler( - document, - eventHandlerMethodName, - position, - out var plusEqualTokenEndPosition, - cancellationToken); - - if (solutionWithEventHandler == null) - { - Contract.Fail("Event Hookup could not create solution with event handler."); - } - - // The new solution is created, so start user observable changes - - if (!workspace.TryApplyChanges(solutionWithEventHandler)) - { - Contract.Fail("Event Hookup could not update the solution."); - } - - // The += token will not move during this process, so it is safe to use that - // position as a location from which to find the identifier we're renaming. - BeginInlineRename(workspace, textView, subjectBuffer, plusEqualTokenEndPosition, cancellationToken); - } - } - - private Solution CreateSolutionWithEventHandler( - Document document, - string eventHandlerMethodName, - int position, - out int plusEqualTokenEndPosition, - CancellationToken cancellationToken) - { - AssertIsForeground(); - - // Mark the += token with an annotation so we can find it after formatting - var plusEqualsTokenAnnotation = new SyntaxAnnotation(); - - var documentWithNameAndAnnotationsAdded = AddMethodNameAndAnnotationsToSolution(document, eventHandlerMethodName, position, plusEqualsTokenAnnotation, cancellationToken); - var semanticDocument = SemanticDocument.CreateAsync(documentWithNameAndAnnotationsAdded, cancellationToken).WaitAndGetResult(cancellationToken); - var updatedRoot = AddGeneratedHandlerMethodToSolution(semanticDocument, eventHandlerMethodName, plusEqualsTokenAnnotation, cancellationToken); - - if (updatedRoot == null) - { - plusEqualTokenEndPosition = 0; - return null; - } - - var simplifiedDocument = Simplifier.ReduceAsync(documentWithNameAndAnnotationsAdded.WithSyntaxRoot(updatedRoot), Simplifier.Annotation, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken); - var formattedDocument = Formatter.FormatAsync(simplifiedDocument, Formatter.Annotation, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken); - - var newRoot = formattedDocument.GetSyntaxRootSynchronously(cancellationToken); - plusEqualTokenEndPosition = newRoot.GetAnnotatedNodesAndTokens(plusEqualsTokenAnnotation) - .Single().Span.End; - - return document.Project.Solution.WithDocumentText( - formattedDocument.Id, formattedDocument.GetTextSynchronously(cancellationToken)); - } - - private static Document AddMethodNameAndAnnotationsToSolution( - Document document, - string eventHandlerMethodName, - int position, - SyntaxAnnotation plusEqualsTokenAnnotation, - CancellationToken cancellationToken) - { - // First find the event hookup to determine if we are in a static context. - var root = document.GetSyntaxRootSynchronously(cancellationToken); - var plusEqualsToken = root.FindTokenOnLeftOfPosition(position); - var eventHookupExpression = plusEqualsToken.GetAncestor(); - - var textToInsert = eventHandlerMethodName + ";"; - if (!eventHookupExpression.IsInStaticContext()) - { - // This will be simplified later if it's not needed. - textToInsert = "this." + textToInsert; - } - - // Next, perform a textual insertion of the event handler method name. - var textChange = new TextChange(new TextSpan(position, 0), textToInsert); - var newText = document.GetTextSynchronously(cancellationToken).WithChanges(textChange); - var documentWithNameAdded = document.WithText(newText); - - // Now find the event hookup again to add the appropriate annotations. - root = documentWithNameAdded.GetSyntaxRootSynchronously(cancellationToken); - plusEqualsToken = root.FindTokenOnLeftOfPosition(position); - eventHookupExpression = plusEqualsToken.GetAncestor(); - - var updatedEventHookupExpression = eventHookupExpression - .ReplaceToken(plusEqualsToken, plusEqualsToken.WithAdditionalAnnotations(plusEqualsTokenAnnotation)) - .WithRight(eventHookupExpression.Right.WithAdditionalAnnotations(Simplifier.Annotation)) - .WithAdditionalAnnotations(Formatter.Annotation); - - var rootWithUpdatedEventHookupExpression = root.ReplaceNode(eventHookupExpression, updatedEventHookupExpression); - return documentWithNameAdded.WithSyntaxRoot(rootWithUpdatedEventHookupExpression); - } - - private static SyntaxNode AddGeneratedHandlerMethodToSolution( - SemanticDocument document, - string eventHandlerMethodName, - SyntaxAnnotation plusEqualsTokenAnnotation, - CancellationToken cancellationToken) - { - var root = document.Root as SyntaxNode; - var eventHookupExpression = root.GetAnnotatedNodesAndTokens(plusEqualsTokenAnnotation).Single().AsToken().GetAncestor(); - - var generatedMethodSymbol = GetMethodSymbol(document, eventHandlerMethodName, eventHookupExpression, cancellationToken); - - if (generatedMethodSymbol == null) - { - return null; - } - - var typeDecl = eventHookupExpression.GetAncestor(); - - var typeDeclWithMethodAdded = CodeGenerator.AddMethodDeclaration(typeDecl, generatedMethodSymbol, document.Project.Solution.Workspace, new CodeGenerationOptions(afterThisLocation: eventHookupExpression.GetLocation())); - - return root.ReplaceNode(typeDecl, typeDeclWithMethodAdded); - } - - private static IMethodSymbol GetMethodSymbol( - SemanticDocument semanticDocument, - string eventHandlerMethodName, - AssignmentExpressionSyntax eventHookupExpression, - CancellationToken cancellationToken) - { - var semanticModel = semanticDocument.SemanticModel as SemanticModel; - var symbolInfo = semanticModel.GetSymbolInfo(eventHookupExpression.Left, cancellationToken); - - var symbol = symbolInfo.Symbol; - if (symbol == null || symbol.Kind != SymbolKind.Event) - { - return null; - } - - var typeInference = semanticDocument.Document.GetLanguageService(); - var delegateType = typeInference.InferDelegateType(semanticModel, eventHookupExpression.Right, cancellationToken); - if (delegateType == null || delegateType.DelegateInvokeMethod == null) - { - return null; - } - - var syntaxFactory = semanticDocument.Document.GetLanguageService(); - var delegateInvokeMethod = delegateType.DelegateInvokeMethod.RemoveInaccessibleAttributesAndAttributesOfTypes(semanticDocument.SemanticModel.Compilation.Assembly); - - return CodeGenerationSymbolFactory.CreateMethodSymbol( - attributes: default, - accessibility: Accessibility.Private, - modifiers: new DeclarationModifiers(isStatic: eventHookupExpression.IsInStaticContext()), - returnType: delegateInvokeMethod.ReturnType, - refKind: delegateInvokeMethod.RefKind, - explicitInterfaceImplementations: default, - name: eventHandlerMethodName, - typeParameters: default, - parameters: delegateInvokeMethod.Parameters, - statements: ImmutableArray.Create( - CodeGenerationHelpers.GenerateThrowStatement(syntaxFactory, semanticDocument, "System.NotImplementedException"))); - } - -#pragma warning disable IDE0060 // Remove unused parameter - private void BeginInlineRename(Workspace workspace, ITextView textView, ITextBuffer subjectBuffer, int plusEqualTokenEndPosition, CancellationToken cancellationToken) -#pragma warning restore IDE0060 // Remove unused parameter - { - AssertIsForeground(); - - if (_inlineRenameService.ActiveSession == null) - { - var document = textView.TextSnapshot.GetOpenDocumentInCurrentContextWithChanges(); - if (document != null) - { - // In the middle of a user action, cannot cancel. - var root = document.GetSyntaxRootSynchronously(cancellationToken); - var token = root.FindTokenOnRightOfPosition(plusEqualTokenEndPosition); - var editSpan = token.Span; - var memberAccessExpression = token.GetAncestor(); - if (memberAccessExpression != null) - { - // the event hookup might look like `MyEvent += this.GeneratedHandlerName;` - editSpan = memberAccessExpression.Name.Span; - } - - _inlineRenameService.StartInlineSession(document, editSpan, cancellationToken); - textView.SetSelection(editSpan.ToSnapshotSpan(textView.TextSnapshot)); - } - } - } - } - - internal static class ExtensionMethods - { - public static bool IsInStaticContext(this SyntaxNode node) - { - // this/base calls are always static. - if (node.FirstAncestorOrSelf() != null) - { - return true; - } - - var memberDeclaration = node.FirstAncestorOrSelf(); - if (memberDeclaration == null) - { - return false; - } - - switch (memberDeclaration.Kind()) - { - case SyntaxKind.MethodDeclaration: - case SyntaxKind.ConstructorDeclaration: - case SyntaxKind.EventDeclaration: - case SyntaxKind.IndexerDeclaration: - return memberDeclaration.GetModifiers().Any(SyntaxKind.StaticKeyword); - - case SyntaxKind.PropertyDeclaration: - return memberDeclaration.GetModifiers().Any(SyntaxKind.StaticKeyword) || - node.IsFoundUnder((PropertyDeclarationSyntax p) => p.Initializer); - - case SyntaxKind.FieldDeclaration: - case SyntaxKind.EventFieldDeclaration: - // Inside a field one can only access static members of a type (unless it's top-level). - return !memberDeclaration.Parent.IsKind(SyntaxKind.CompilationUnit); - - case SyntaxKind.DestructorDeclaration: - return false; - } - - // Global statements are not a static context. - if (node.FirstAncestorOrSelf() != null) - { - return false; - } - - // any other location is considered static - return true; - } - - public static SyntaxTokenList GetModifiers(this SyntaxNode member) - { - if (member != null) - { - switch (member.Kind()) - { - case SyntaxKind.EnumDeclaration: - return ((EnumDeclarationSyntax)member).Modifiers; - case SyntaxKind.ClassDeclaration: - case SyntaxKind.InterfaceDeclaration: - case SyntaxKind.StructDeclaration: - return ((TypeDeclarationSyntax)member).Modifiers; - case SyntaxKind.DelegateDeclaration: - return ((DelegateDeclarationSyntax)member).Modifiers; - case SyntaxKind.FieldDeclaration: - return ((FieldDeclarationSyntax)member).Modifiers; - case SyntaxKind.EventFieldDeclaration: - return ((EventFieldDeclarationSyntax)member).Modifiers; - case SyntaxKind.ConstructorDeclaration: - return ((ConstructorDeclarationSyntax)member).Modifiers; - case SyntaxKind.DestructorDeclaration: - return ((DestructorDeclarationSyntax)member).Modifiers; - case SyntaxKind.PropertyDeclaration: - return ((PropertyDeclarationSyntax)member).Modifiers; - case SyntaxKind.EventDeclaration: - return ((EventDeclarationSyntax)member).Modifiers; - case SyntaxKind.IndexerDeclaration: - return ((IndexerDeclarationSyntax)member).Modifiers; - case SyntaxKind.OperatorDeclaration: - return ((OperatorDeclarationSyntax)member).Modifiers; - case SyntaxKind.ConversionOperatorDeclaration: - return ((ConversionOperatorDeclarationSyntax)member).Modifiers; - case SyntaxKind.MethodDeclaration: - return ((MethodDeclarationSyntax)member).Modifiers; - case SyntaxKind.GetAccessorDeclaration: - case SyntaxKind.SetAccessorDeclaration: - case SyntaxKind.AddAccessorDeclaration: - case SyntaxKind.RemoveAccessorDeclaration: - return ((AccessorDeclarationSyntax)member).Modifiers; - } - } - - return default; - } - } -} diff --git a/src/EditorFeatures/Core.Cocoa/EventHookup/EventHookupCommandHandler_TypeCharCommand.cs b/src/EditorFeatures/Core.Cocoa/EventHookup/EventHookupCommandHandler_TypeCharCommand.cs deleted file mode 100644 index 7f6d3eb1796b4..0000000000000 --- a/src/EditorFeatures/Core.Cocoa/EventHookup/EventHookupCommandHandler_TypeCharCommand.cs +++ /dev/null @@ -1,78 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Threading; -using Microsoft.CodeAnalysis.Editor.Shared.Extensions; -using Microsoft.CodeAnalysis.Editor.Shared.Options; -using Microsoft.CodeAnalysis.Internal.Log; -using Microsoft.VisualStudio.Commanding; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Editor; -using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; -using VSCommanding = Microsoft.VisualStudio.Commanding; - -namespace Microsoft.CodeAnalysis.Editor.CSharp.EventHookup -{ - internal partial class EventHookupCommandHandler : IChainedCommandHandler - { - public void ExecuteCommand(TypeCharCommandArgs args, Action nextHandler, CommandExecutionContext context) - { - AssertIsForeground(); - nextHandler(); - - if (!args.SubjectBuffer.GetFeatureOnOffOption(InternalFeatureOnOffOptions.EventHookup)) - { - EventHookupSessionManager.CancelAndDismissExistingSessions(); - return; - } - - // Event hookup is current uncancellable. - var cancellationToken = CancellationToken.None; - using (Logger.LogBlock(FunctionId.EventHookup_Type_Char, cancellationToken)) - { - if (args.TypedChar == '=') - { - // They've typed an equals. Cancel existing sessions and potentially start a - // new session. - - EventHookupSessionManager.CancelAndDismissExistingSessions(); - - if (IsTextualPlusEquals(args.TextView, args.SubjectBuffer)) - { - EventHookupSessionManager.BeginSession(this, args.TextView, args.SubjectBuffer, _asyncListener, TESTSessionHookupMutex); - } - } - else - { - // Spaces are the only non-'=' character that allow the session to continue - if (args.TypedChar != ' ') - { - EventHookupSessionManager.CancelAndDismissExistingSessions(); - } - } - } - } - - private bool IsTextualPlusEquals(ITextView textView, ITextBuffer subjectBuffer) - { - AssertIsForeground(); - - var caretPoint = textView.GetCaretPoint(subjectBuffer); - if (!caretPoint.HasValue) - { - return false; - } - - var position = caretPoint.Value.Position; - return position - 2 >= 0 && subjectBuffer.CurrentSnapshot.GetText(position - 2, 2) == "+="; - } - - public VSCommanding.CommandState GetCommandState(TypeCharCommandArgs args, Func nextHandler) - { - AssertIsForeground(); - return nextHandler(); - } - } -} diff --git a/src/EditorFeatures/Core.Cocoa/EventHookup/EventHookupSessionManager.cs b/src/EditorFeatures/Core.Cocoa/EventHookup/EventHookupSessionManager.cs deleted file mode 100644 index da7ed633c40f4..0000000000000 --- a/src/EditorFeatures/Core.Cocoa/EventHookup/EventHookupSessionManager.cs +++ /dev/null @@ -1,160 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -#nullable disable - -using System; -using System.ComponentModel.Composition; -using System.Linq; -using System.Threading; -using Microsoft.CodeAnalysis.Classification; -using Microsoft.CodeAnalysis.Editor.Shared.Extensions; -using Microsoft.CodeAnalysis.Editor.Shared.Utilities; -using Microsoft.CodeAnalysis.Host.Mef; -using Microsoft.CodeAnalysis.Shared.TestHooks; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Adornments; -using Microsoft.VisualStudio.Text.Editor; -using Microsoft.VisualStudio.UI; - -namespace Microsoft.CodeAnalysis.Editor.CSharp.EventHookup -{ - [Export] - internal sealed partial class EventHookupSessionManager : ForegroundThreadAffinitizedObject - { - private readonly IToolTipService _toolTipService; - private IToolTipPresenter _toolTipPresenter; - - internal EventHookupSession CurrentSession { get; set; } - - // For test purposes only! - internal ClassifiedTextElement[] TEST_MostRecentToolTipContent { get; set; } - - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public EventHookupSessionManager(IThreadingContext threadingContext, IToolTipService toolTipService) - : base(threadingContext) - { - _toolTipService = toolTipService; - } - - internal void EventHookupFoundInSession(EventHookupSession analyzedSession) - { - AssertIsForeground(); - - var caretPoint = analyzedSession.TextView.GetCaretPoint(analyzedSession.SubjectBuffer); - - // only generate tooltip if it is not already shown (_toolTipPresenter == null) - // Ensure the analyzed session matches the current session and that the caret is still - // in the session's tracking span. - if (_toolTipPresenter == null && - CurrentSession == analyzedSession && - caretPoint.HasValue && - analyzedSession.TrackingSpan.GetSpan(CurrentSession.TextView.TextSnapshot).Contains(caretPoint.Value)) - { - // Create a tooltip presenter that stays alive, even when the user types, without tracking the mouse. - _toolTipPresenter = this._toolTipService.CreatePresenter(analyzedSession.TextView, - new ToolTipParameters(trackMouse: false, ignoreBufferChange: true)); - - // tooltips text is: Program_MyEvents; (Press TAB to insert) - // GetEventNameTask() gets back the event name, only needs to add a semicolon after it. - var eventText = analyzedSession.GetEventNameTask.Result + ";"; - var texts = new[] { eventText, GettextCatalog.GetString(" (Press TAB to insert)") }; - var textRuns = texts.Select(s => new ClassifiedTextRun(ClassificationTypeNames.Text, s)); - var content = new[] { new ClassifiedTextElement(textRuns) }; - - _toolTipPresenter.StartOrUpdate(analyzedSession.TrackingSpan, content); - - // For test purposes only! - TEST_MostRecentToolTipContent = content; - - // Watch all text buffer changes & caret moves while this event hookup session is active - analyzedSession.TextView.TextSnapshot.TextBuffer.Changed += TextBuffer_Changed; - CurrentSession.Dismissed += () => { analyzedSession.TextView.TextSnapshot.TextBuffer.Changed -= TextBuffer_Changed; }; - - analyzedSession.TextView.Caret.PositionChanged += Caret_PositionChanged; - CurrentSession.Dismissed += () => { analyzedSession.TextView.Caret.PositionChanged -= Caret_PositionChanged; }; - } - } - - internal void BeginSession( - EventHookupCommandHandler eventHookupCommandHandler, - ITextView textView, - ITextBuffer subjectBuffer, - IAsynchronousOperationListener asyncListener, - Mutex testSessionHookupMutex) - { - CurrentSession = new EventHookupSession(this, eventHookupCommandHandler, textView, subjectBuffer, asyncListener, testSessionHookupMutex); - } - - internal void CancelAndDismissExistingSessions() - { - AssertIsForeground(); - - if (CurrentSession != null) - { - CurrentSession.Cancel(); - CurrentSession = null; - } - - if (_toolTipPresenter != null) - { - _toolTipPresenter.Dismiss(); - _toolTipPresenter = null; - } - - // For test purposes only! - TEST_MostRecentToolTipContent = null; - } - - /// - /// If any text is deleted or any non-space text is entered, cancel the session. - /// - private void TextBuffer_Changed(object sender, TextContentChangedEventArgs e) - { - AssertIsForeground(); - - foreach (var change in e.Changes) - { - if (change.OldText.Length > 0 || change.NewText.Any(c => c != ' ')) - { - CancelAndDismissExistingSessions(); - return; - } - } - } - - /// - /// If the caret moves outside the session's tracking span, cancel the session. - /// - private void Caret_PositionChanged(object sender, EventArgs e) - { - AssertIsForeground(); - - if (CurrentSession == null) - { - CancelAndDismissExistingSessions(); - return; - } - - var caretPoint = CurrentSession.TextView.GetCaretPoint(CurrentSession.SubjectBuffer); - - if (!caretPoint.HasValue) - { - CancelAndDismissExistingSessions(); - } - - var snapshotSpan = CurrentSession.TrackingSpan.GetSpan(CurrentSession.TextView.TextSnapshot); - if (snapshotSpan.Snapshot != caretPoint.Value.Snapshot || !snapshotSpan.Contains(caretPoint.Value)) - { - CancelAndDismissExistingSessions(); - } - } - - internal bool IsTrackingSession() - { - return CurrentSession != null; - } - } -} diff --git a/src/EditorFeatures/Core.Cocoa/EventHookup/EventHookupSessionManager_EventHookupSession.cs b/src/EditorFeatures/Core.Cocoa/EventHookup/EventHookupSessionManager_EventHookupSession.cs deleted file mode 100644 index 6cef3265b964a..0000000000000 --- a/src/EditorFeatures/Core.Cocoa/EventHookup/EventHookupSessionManager_EventHookupSession.cs +++ /dev/null @@ -1,273 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -#nullable disable - -using System; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Editor.Shared.Extensions; -using Microsoft.CodeAnalysis.Editor.Shared.Utilities; -using Microsoft.CodeAnalysis.Internal.Log; -using Microsoft.CodeAnalysis.LanguageServices; -using Microsoft.CodeAnalysis.Shared.Extensions; -using Microsoft.CodeAnalysis.Shared.TestHooks; -using Microsoft.CodeAnalysis.Shared.Utilities; -using Microsoft.CodeAnalysis.Text; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Editor; -using Roslyn.Utilities; - -namespace Microsoft.CodeAnalysis.Editor.CSharp.EventHookup -{ - internal sealed partial class EventHookupSessionManager - { - /// - /// A session begins when an '=' is typed after a '+' and requires determining whether the - /// += is being used to add an event handler to an event. If it is, then we also determine - /// a candidate name for the event handler. - /// - internal class EventHookupSession : ForegroundThreadAffinitizedObject - { - public readonly Task GetEventNameTask; - private readonly CancellationTokenSource _cancellationTokenSource; - private readonly ITrackingPoint _trackingPoint; - private readonly ITrackingSpan _trackingSpan; - private readonly ITextView _textView; - private readonly ITextBuffer _subjectBuffer; - - public event Action Dismissed = () => { }; - - // For testing purposes only! Should always be null except in tests. - internal Mutex TESTSessionHookupMutex = null; - - public ITrackingPoint TrackingPoint - { - get - { - AssertIsForeground(); - return _trackingPoint; - } - } - - public ITrackingSpan TrackingSpan - { - get - { - AssertIsForeground(); - return _trackingSpan; - } - } - - public ITextView TextView - { - get - { - AssertIsForeground(); - return _textView; - } - } - - public ITextBuffer SubjectBuffer - { - get - { - AssertIsForeground(); - return _subjectBuffer; - } - } - - public void Cancel() - { - AssertIsForeground(); - _cancellationTokenSource.Cancel(); - } - - public EventHookupSession( - EventHookupSessionManager eventHookupSessionManager, - EventHookupCommandHandler commandHandler, - ITextView textView, - ITextBuffer subjectBuffer, - IAsynchronousOperationListener asyncListener, - Mutex testSessionHookupMutex) - : base(eventHookupSessionManager.ThreadingContext) - { - AssertIsForeground(); - _cancellationTokenSource = new CancellationTokenSource(); - _textView = textView; - _subjectBuffer = subjectBuffer; - this.TESTSessionHookupMutex = testSessionHookupMutex; - - var document = textView.TextSnapshot.GetOpenDocumentInCurrentContextWithChanges(); - if (document != null && document.Project.Solution.Workspace.CanApplyChange(ApplyChangesKind.ChangeDocument)) - { - var position = textView.GetCaretPoint(subjectBuffer).Value.Position; - _trackingPoint = textView.TextSnapshot.CreateTrackingPoint(position, PointTrackingMode.Negative); - _trackingSpan = textView.TextSnapshot.CreateTrackingSpan(new Span(position, 1), SpanTrackingMode.EdgeInclusive); - - var asyncToken = asyncListener.BeginAsyncOperation(GetType().Name + ".Start"); - - this.GetEventNameTask = Task.Factory.SafeStartNewFromAsync( - () => DetermineIfEventHookupAndGetHandlerNameAsync(document, position, _cancellationTokenSource.Token), - _cancellationTokenSource.Token, - TaskScheduler.Default); - - var continuedTask = this.GetEventNameTask.SafeContinueWithFromAsync( - async t => - { - await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, _cancellationTokenSource.Token); - _cancellationTokenSource.Token.ThrowIfCancellationRequested(); - -#pragma warning disable VSTHRD103 // Call async methods when in an async method - if (t.Result != null) -#pragma warning restore VSTHRD103 // Call async methods when in an async method - { - commandHandler.EventHookupSessionManager.EventHookupFoundInSession(this); - } - }, - _cancellationTokenSource.Token, - TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously, - TaskScheduler.Default); - - continuedTask.CompletesAsyncOperation(asyncToken); - } - else - { - _trackingPoint = textView.TextSnapshot.CreateTrackingPoint(0, PointTrackingMode.Negative); - _trackingSpan = textView.TextSnapshot.CreateTrackingSpan(new Span(), SpanTrackingMode.EdgeInclusive); - this.GetEventNameTask = SpecializedTasks.Null(); - eventHookupSessionManager.CancelAndDismissExistingSessions(); - } - } - - private async Task DetermineIfEventHookupAndGetHandlerNameAsync(Document document, int position, CancellationToken cancellationToken) - { - AssertIsBackground(); - - // For test purposes only! - if (TESTSessionHookupMutex != null) - { - TESTSessionHookupMutex.WaitOne(); - TESTSessionHookupMutex.ReleaseMutex(); - } - - using (Logger.LogBlock(FunctionId.EventHookup_Determine_If_Event_Hookup, cancellationToken)) - { - var plusEqualsToken = await GetPlusEqualsTokenInsideAddAssignExpressionAsync(document, position, cancellationToken).ConfigureAwait(false); - if (plusEqualsToken == null) - { - return null; - } - - var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); - - var eventSymbol = GetEventSymbol(semanticModel, plusEqualsToken.Value, cancellationToken); - if (eventSymbol == null) - { - return null; - } - - return GetEventHandlerName(eventSymbol, plusEqualsToken.Value, semanticModel, document.GetLanguageService()); - } - } - - private async Task GetPlusEqualsTokenInsideAddAssignExpressionAsync(Document document, int position, CancellationToken cancellationToken) - { - AssertIsBackground(); - var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); - var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); - - if (token.Kind() != SyntaxKind.PlusEqualsToken) - { - return null; - } - - if (!token.Parent.IsKind(SyntaxKind.AddAssignmentExpression)) - { - return null; - } - - return token; - } - - private IEventSymbol GetEventSymbol(SemanticModel semanticModel, SyntaxToken plusEqualsToken, CancellationToken cancellationToken) - { - AssertIsBackground(); - var parentToken = plusEqualsToken.Parent as AssignmentExpressionSyntax; - if (parentToken == null) - { - return null; - } - - var symbol = semanticModel.GetSymbolInfo(parentToken.Left, cancellationToken).Symbol; - if (symbol == null) - { - return null; - } - - return symbol as IEventSymbol; - } - - private string GetEventHandlerName(IEventSymbol eventSymbol, SyntaxToken plusEqualsToken, SemanticModel semanticModel, ISyntaxFactsService syntaxFactsService) - { - AssertIsBackground(); - var basename = string.Format("{0}_{1}", GetNameObjectPart(eventSymbol, plusEqualsToken, semanticModel, syntaxFactsService), eventSymbol.Name); - basename = basename.ToPascalCase(trimLeadingTypePrefix: false); - - var reservedNames = semanticModel.LookupSymbols(plusEqualsToken.SpanStart).Select(m => m.Name); - - return NameGenerator.EnsureUniqueness(basename, reservedNames); - } - - /// - /// Take another look at the LHS of the += node -- we need to figure out a default name - /// for the event handler, and that's usually based on the object (which is usually a - /// field of 'this', but not always) to which the event belongs. So, if the event is - /// something like 'button1.Click' or 'this.listBox1.Select', we want the names - /// 'button1' and 'listBox1' respectively. If the field belongs to 'this', then we use - /// the name of this class, as we do if we can't make any sense out of the parse tree. - /// - private string GetNameObjectPart(IEventSymbol eventSymbol, SyntaxToken plusEqualsToken, SemanticModel semanticModel, ISyntaxFactsService syntaxFactsService) - { - AssertIsBackground(); - var parentToken = plusEqualsToken.Parent as AssignmentExpressionSyntax; - - if (parentToken.Left is MemberAccessExpressionSyntax memberAccessExpression) - { - // This is expected -- it means the last thing is(probably) the event name. We - // already have that in eventSymbol. What we need is the LHS of that dot. - - var lhs = memberAccessExpression.Expression; - - if (lhs is MemberAccessExpressionSyntax lhsMemberAccessExpression) - { - // Okay, cool. The name we're after is in the RHS of this dot. - return lhsMemberAccessExpression.Name.ToString(); - } - - if (lhs is NameSyntax lhsNameSyntax) - { - // Even easier -- the LHS of the dot is the name itself - return lhsNameSyntax.ToString(); - } - } - - // If we didn't find an object name above, then the object name is the name of this class. - // Note: For generic, it's ok(it's even a good idea) to exclude type variables, - // because the name is only used as a prefix for the method name. - - var typeDeclaration = syntaxFactsService.GetContainingTypeDeclaration( - semanticModel.SyntaxTree.GetRoot(), - plusEqualsToken.SpanStart) as BaseTypeDeclarationSyntax; - - return typeDeclaration != null - ? typeDeclaration.Identifier.Text - : eventSymbol.ContainingType.Name; - } - } - } -} diff --git a/src/EditorFeatures/Core.Cocoa/PreviewPane/PreviewPane.cs b/src/EditorFeatures/Core.Cocoa/PreviewPane/PreviewPane.cs index aaf5ddbb23c95..72c36131e1869 100644 --- a/src/EditorFeatures/Core.Cocoa/PreviewPane/PreviewPane.cs +++ b/src/EditorFeatures/Core.Cocoa/PreviewPane/PreviewPane.cs @@ -6,51 +6,147 @@ using System; using System.Collections.Generic; +using System.Text; using AppKit; +using CoreGraphics; +using Foundation; using Microsoft.CodeAnalysis.Editor.Implementation.Preview; +using Microsoft.CodeAnalysis.Editor.Shared.Extensions; +using Microsoft.VisualStudio.Text.Editor; -#pragma warning disable IDE0052 // Remove unread private members +#pragma warning disable IDE0060 //Remove unused parameter namespace Microsoft.VisualStudio.LanguageServices.Implementation.PreviewPane { internal class PreviewPane : NSView { - private readonly NSImage severityIcon; - private readonly string id; - private readonly string title; - private readonly string description; - private readonly Uri helpLink; - private readonly string helpLinkToolTipText; - private readonly IReadOnlyList previewContent; - private readonly bool logIdVerbatimInTelemetry; - private Guid? optionPageGuid; private DifferenceViewerPreview _differenceViewerPreview; + private readonly NSTextField titleField; public PreviewPane(NSImage severityIcon, string id, string title, string description, Uri helpLink, string helpLinkToolTipText, IReadOnlyList previewContent, bool logIdVerbatimInTelemetry, Guid? optionPageGuid = null) { - this.severityIcon = severityIcon; - this.id = id; - this.title = title; - this.description = description; - this.helpLink = helpLink; - this.helpLinkToolTipText = helpLinkToolTipText; - this.previewContent = previewContent; - this.logIdVerbatimInTelemetry = logIdVerbatimInTelemetry; - this.optionPageGuid = optionPageGuid; _differenceViewerPreview = (DifferenceViewerPreview)previewContent[0]; var view = _differenceViewerPreview.Viewer.VisualElement; - SetFrameSize(view.Frame.Size); + + var originalSize = view.Frame.Size; + + this.TranslatesAutoresizingMaskIntoConstraints = false; + + // === Title === + // Title is in a stack view to help with padding + var titlePlaceholder = new NSStackView() + { + Orientation = NSUserInterfaceLayoutOrientation.Vertical, + EdgeInsets = new NSEdgeInsets(5, 0, 5, 0), + Alignment = NSLayoutAttribute.Leading, + TranslatesAutoresizingMaskIntoConstraints = false + }; + + // TODO: missing icon + this.titleField = new NSTextField() + { + Editable = false, + Bordered = false, + BackgroundColor = NSColor.ControlBackground, + DrawsBackground = false, + }; + + titlePlaceholder.AddArrangedSubview(titleField); + AddSubview(titlePlaceholder); + + // === Preview View === + // This is the actual view, that shows the diff + view.TranslatesAutoresizingMaskIntoConstraints = false; + NSLayoutConstraint.Create(view, NSLayoutAttribute.Width, NSLayoutRelation.GreaterThanOrEqual, 1, originalSize.Width).Active = true; + NSLayoutConstraint.Create(view, NSLayoutAttribute.Height, NSLayoutRelation.GreaterThanOrEqual, 1, originalSize.Height).Active = true; + view.Subviews[0].TranslatesAutoresizingMaskIntoConstraints = false; + view.WantsLayer = true; + AddSubview(view); - // HACK: This is here for a11y compliance and should be removed as - // we find a better alternative - this.AccessibilityHelp = _differenceViewerPreview?.Viewer?.DifferenceBuffer?.InlineBuffer?.CurrentSnapshot.GetText(); + // === Constraints === + var constraints = new NSLayoutConstraint[] + { + // Title + NSLayoutConstraint.Create(titlePlaceholder, NSLayoutAttribute.Top, NSLayoutRelation.Equal, this, NSLayoutAttribute.Top, 1, 0), + NSLayoutConstraint.Create(titlePlaceholder, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, this, NSLayoutAttribute.Leading, 1, 0), + NSLayoutConstraint.Create(titlePlaceholder, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, this, NSLayoutAttribute.Trailing, 1, 0), + + // Preview View + NSLayoutConstraint.Create(view, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, this, NSLayoutAttribute.Bottom, 1, 0), + NSLayoutConstraint.Create(view, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, this, NSLayoutAttribute.Leading, 1, 0), + NSLayoutConstraint.Create(view, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, this, NSLayoutAttribute.Trailing, 1, 0), + + // subviews + NSLayoutConstraint.Create(view.Subviews[0], NSLayoutAttribute.Top, NSLayoutRelation.Equal, view, NSLayoutAttribute.Top, 1, 0), + NSLayoutConstraint.Create(view.Subviews[0], NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, view, NSLayoutAttribute.Bottom, 1, 0), + NSLayoutConstraint.Create(view.Subviews[0], NSLayoutAttribute.Left, NSLayoutRelation.Equal, view, NSLayoutAttribute.Left, 1, 0), + NSLayoutConstraint.Create(view.Subviews[0], NSLayoutAttribute.Right, NSLayoutRelation.Equal, view, NSLayoutAttribute.Right, 1, 0), + }; + + if (GenerateAttributeString(id, title, helpLink, helpLinkToolTipText) is NSAttributedString attributedStringTitle) + { + this.titleField.AttributedStringValue = attributedStringTitle; + // We do this separately, because the title sometimes isn't there (i.e. no diagnostics ID) + // and we want the preview to stretch to the top + NSLayoutConstraint.Create(view, NSLayoutAttribute.Top, NSLayoutRelation.Equal, titlePlaceholder, NSLayoutAttribute.Bottom, 1, 0).Active = true; + } + else + { + NSLayoutConstraint.Create(view, NSLayoutAttribute.Top, NSLayoutRelation.Equal, this, NSLayoutAttribute.Top, 1, 0).Active = true; + } + + NSLayoutConstraint.ActivateConstraints(constraints); + + _differenceViewerPreview.Viewer.InlineView.TryMoveCaretToAndEnsureVisible( + new Text.SnapshotPoint(_differenceViewerPreview.Viewer.InlineView.TextSnapshot, 0)); + } + + public PreviewPane(IntPtr ptr) + : base(ptr) + { + } + + private static NSAttributedString GenerateAttributeString(string id, string title, Uri link, string linkTooltip) + { + if (string.IsNullOrEmpty(title)) + return null; + + var attributedBuffer = new NSMutableAttributedString(); + + attributedBuffer.BeginEditing(); + + var normalText = new NSStringAttributes + { + ForegroundColor = NSColor.ControlText + }; + + if (!string.IsNullOrEmpty(id)) + { + var linkAttributes = new NSStringAttributes + { + LinkUrl = link, + ToolTip = linkTooltip + }; + + attributedBuffer.Append(new NSAttributedString(id, linkAttributes)); + attributedBuffer.Append(new NSAttributedString(": ", normalText)); + } + + attributedBuffer.Append(new NSAttributedString(title, normalText)); + attributedBuffer.EndEditing(); + + return attributedBuffer; } protected override void Dispose(bool disposing) { - _differenceViewerPreview?.Dispose(); - _differenceViewerPreview = null; + if (disposing) + { + _differenceViewerPreview?.Dispose(); + _differenceViewerPreview = null; + } + base.Dispose(disposing); } } -} +} \ No newline at end of file diff --git a/src/EditorFeatures/Core.Cocoa/Suggestions/FixAll/FixAllGetFixesService.cs b/src/EditorFeatures/Core.Cocoa/Suggestions/FixAll/FixAllGetFixesService.cs index 399fc25f59bec..a61b4f10636de 100644 --- a/src/EditorFeatures/Core.Cocoa/Suggestions/FixAll/FixAllGetFixesService.cs +++ b/src/EditorFeatures/Core.Cocoa/Suggestions/FixAll/FixAllGetFixesService.cs @@ -165,6 +165,10 @@ internal static Solution PreviewChanges( ? Glyph.CSharpProject : Glyph.BasicProject; + // Until IPreviewDialogService is implemented, just execute all changes without user ability to pick and choose + if (previewService == null) + return newSolution; + var changedSolution = previewService.PreviewChanges( string.Format(EditorFeaturesResources.Preview_Changes_0, fixAllPreviewChangesTitle), "vs.codefix.fixall", diff --git a/src/EditorFeatures/Core.Wpf/InlineHints/InlineHintsTaggerProvider.cs b/src/EditorFeatures/Core.Wpf/InlineHints/InlineHintsTaggerProvider.cs index ac7b467242502..48b8fa3ed6147 100644 --- a/src/EditorFeatures/Core.Wpf/InlineHints/InlineHintsTaggerProvider.cs +++ b/src/EditorFeatures/Core.Wpf/InlineHints/InlineHintsTaggerProvider.cs @@ -5,6 +5,7 @@ using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Host; +using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text; @@ -56,9 +57,7 @@ public InlineHintsTaggerProvider( public ITagger? CreateTagger(ITextView textView, ITextBuffer buffer) where T : ITag { - // Determining of the textView's buffer does not match the buffer in order to skip showing the hints for - // the interactive window - if (buffer != textView.TextBuffer) + if (textView.IsNotSurfaceBufferOfTextView(buffer)) { return null; } diff --git a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.cs.xlf b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.cs.xlf index 422ad8daadbe0..9a1c854ac6e35 100644 --- a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.cs.xlf +++ b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.cs.xlf @@ -9,17 +9,17 @@ Copying selection to Interactive Window. - Výběr se kopíruje do interaktivního okna. + Výběr se kopíruje do okna Interactive. Executing selection in Interactive Window. - Výběr se spouští v interaktivním okně. + Výběr se spouští v okně Interactive. Interactive host process platform - Interactive host process platform + Interaktivní platforma procesů hostitelů @@ -29,7 +29,7 @@ The references command is not supported in this Interactive Window implementation. - Příkaz references není v této implementaci interaktivního okna podporovaný. + Příkaz references není v této implementaci okna Interactive podporovaný. diff --git a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.de.xlf b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.de.xlf index 4ecf141117aaa..e7ae53f59e6d9 100644 --- a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.de.xlf +++ b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.de.xlf @@ -9,17 +9,17 @@ Copying selection to Interactive Window. - Die Auswahl wird in Interactive Window kopiert. + Die Auswahl wird in Interactive-Fenster kopiert. Executing selection in Interactive Window. - Die Auswahl wird in Interactive Window ausgeführt. + Die Auswahl wird im Interactive-Fenster ausgeführt. Interactive host process platform - Interactive host process platform + Interaktive Hostprozessplattform @@ -29,7 +29,7 @@ The references command is not supported in this Interactive Window implementation. - Der Befehl "references" wird in dieser Interactive Window-Implementierung nicht unterstützt. + Der Befehl "references" wird in dieser Implementierung von Interactive-Fenster nicht unterstützt. diff --git a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.es.xlf b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.es.xlf index 1adad1910031d..f9b37c8fbafbf 100644 --- a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.es.xlf +++ b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.es.xlf @@ -19,7 +19,7 @@ Interactive host process platform - Interactive host process platform + Plataforma de proceso de host interactiva diff --git a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.fr.xlf b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.fr.xlf index 447a98857bd9f..cfa326e3f7e9d 100644 --- a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.fr.xlf +++ b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.fr.xlf @@ -19,7 +19,7 @@ Interactive host process platform - Interactive host process platform + Plateforme de processus hôte interactive diff --git a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.it.xlf b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.it.xlf index b0a6159f5b39f..0d454c9d77824 100644 --- a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.it.xlf +++ b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.it.xlf @@ -19,7 +19,7 @@ Interactive host process platform - Interactive host process platform + Piattaforma interattiva per processi host diff --git a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.ja.xlf b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.ja.xlf index d8ad83908caab..52c9bc7c4d170 100644 --- a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.ja.xlf +++ b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.ja.xlf @@ -14,12 +14,12 @@ Executing selection in Interactive Window. - 対話型ウィンドウで選択を実行します。 + インタラクティブ ウィンドウで選択を実行します。 Interactive host process platform - Interactive host process platform + 対話型ホスト プロセス プラットフォーム @@ -29,7 +29,7 @@ The references command is not supported in this Interactive Window implementation. - この対話型ウィンドウの実装で、参照コマンドはサポートされていません。 + このインタラクティブ ウィンドウの実装で、参照コマンドはサポートされていません。 diff --git a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.ko.xlf b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.ko.xlf index 7f8e47459d525..6b4ce0a2bef0b 100644 --- a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.ko.xlf +++ b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.ko.xlf @@ -19,7 +19,7 @@ Interactive host process platform - Interactive host process platform + 대화형 호스트 프로세스 플랫폼 diff --git a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.pl.xlf b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.pl.xlf index 553b7c74a0d31..831d3a1e3541c 100644 --- a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.pl.xlf +++ b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.pl.xlf @@ -9,17 +9,17 @@ Copying selection to Interactive Window. - Kopiowanie zaznaczenia do okna interaktywnego. + Kopiowanie zaznaczenia do okna Interactive. Executing selection in Interactive Window. - Wykonywanie zaznaczenia w oknie interaktywnym. + Wykonywanie zaznaczenia w oknie Interactive. Interactive host process platform - Interactive host process platform + Platforma procesu hosta interaktywnego @@ -29,7 +29,7 @@ The references command is not supported in this Interactive Window implementation. - Polecenie references nie jest obsługiwane w tej implementacji okna interaktywnego. + Polecenie references nie jest obsługiwane w tej implementacji okna Interactive. diff --git a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.pt-BR.xlf b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.pt-BR.xlf index b5b674169be98..8d473c7b134e0 100644 --- a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.pt-BR.xlf +++ b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.pt-BR.xlf @@ -19,7 +19,7 @@ Interactive host process platform - Interactive host process platform + Plataforma interativa de processo de host diff --git a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.ru.xlf b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.ru.xlf index c3d951dedefaa..a16c8bb9b8377 100644 --- a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.ru.xlf +++ b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.ru.xlf @@ -14,12 +14,12 @@ Executing selection in Interactive Window. - Выполнение выделенного фрагмента в интерактивном окне. + Выполнение выделенного фрагмента в Интерактивном окне. Interactive host process platform - Interactive host process platform + Интерактивная платформа хост-процесса @@ -29,7 +29,7 @@ The references command is not supported in this Interactive Window implementation. - Команда, на которую указывает ссылка, не поддерживается в этой интерактивной реализации Windows. + Команда, на которую указывает ссылка, не поддерживается в этой реализации Интерактивного окна. diff --git a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.tr.xlf b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.tr.xlf index 4d7f5a631eb45..5a97f7a67c34e 100644 --- a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.tr.xlf +++ b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.tr.xlf @@ -19,7 +19,7 @@ Interactive host process platform - Interactive host process platform + Etkileşimli ana işlem platformu diff --git a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.zh-Hans.xlf b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.zh-Hans.xlf index 5f136ff53162b..51e93ff05f4cf 100644 --- a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.zh-Hans.xlf +++ b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Building Project @@ -9,17 +9,17 @@ Copying selection to Interactive Window. - 将所选内容复制到交互式窗口。 + 将所选内容复制到交互窗口。 Executing selection in Interactive Window. - 在交互式窗口中执行所选内容。 + 在交互窗口中执行所选内容。 Interactive host process platform - Interactive host process platform + 交互式主机进程平台 diff --git a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.zh-Hant.xlf b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.zh-Hant.xlf index 553697aed5c91..01cec4fb3993e 100644 --- a/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.zh-Hant.xlf +++ b/src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Building Project @@ -9,17 +9,17 @@ Copying selection to Interactive Window. - 正在將選取範圍複製到互動式視窗。 + 正在將選取範圍複製到互動視窗。 Executing selection in Interactive Window. - 正在於互動式視窗中執行選取範圍。 + 正在於互動視窗中執行選取範圍。 Interactive host process platform - Interactive host process platform + 互動式主機處理序平台 diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.cs.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.cs.xlf index 79343a9b721f5..2122cedcf0d68 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.cs.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.cs.xlf @@ -4,7 +4,7 @@ Error performing rename: '{0}' - Error performing rename: '{0}' + Nepovedlo se provést přejmenování: {0} diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.de.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.de.xlf index be554684dd4e3..48ba913476158 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.de.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.de.xlf @@ -4,7 +4,7 @@ Error performing rename: '{0}' - Error performing rename: '{0}' + Fehler beim Umbenennen: "{0}" diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.es.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.es.xlf index 58cdaa1be4513..ac13e8377183f 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.es.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.es.xlf @@ -4,7 +4,7 @@ Error performing rename: '{0}' - Error performing rename: '{0}' + Error al realizar el cambio de nombre: "{0}" diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.fr.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.fr.xlf index 1c1e912ac1a62..7ef4dfab948be 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.fr.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.fr.xlf @@ -4,7 +4,7 @@ Error performing rename: '{0}' - Error performing rename: '{0}' + Erreur au moment du renommage : '{0}' diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.it.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.it.xlf index 825f7ee2780af..e7ae427e2bdef 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.it.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.it.xlf @@ -4,7 +4,7 @@ Error performing rename: '{0}' - Error performing rename: '{0}' + Si è verificato un errore durante la ridenominazione: '{0}' diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ja.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ja.xlf index f9a8544ed53fd..1c7d1cd8ecff1 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ja.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ja.xlf @@ -4,7 +4,7 @@ Error performing rename: '{0}' - Error performing rename: '{0}' + 名前変更の実行でエラーが発生しました: '{0}' diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ko.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ko.xlf index c9c7c45ed2c0b..5945717b3b52d 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ko.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ko.xlf @@ -4,7 +4,7 @@ Error performing rename: '{0}' - Error performing rename: '{0}' + 이름 바꾸기 수행 중 오류 발생: '{0}' diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.pl.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.pl.xlf index b6bf79dce119f..8166476a00797 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.pl.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.pl.xlf @@ -4,7 +4,7 @@ Error performing rename: '{0}' - Error performing rename: '{0}' + Błąd podczas wykonywania operacji zmiany nazwy: „{0}” diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.pt-BR.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.pt-BR.xlf index 1fe3975ecc7d4..ee988f2509faf 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.pt-BR.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.pt-BR.xlf @@ -4,7 +4,7 @@ Error performing rename: '{0}' - Error performing rename: '{0}' + Erro ao executar a renomeação: '{0}' diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ru.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ru.xlf index b96dfeb8578c7..86ca75e6f2a52 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ru.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ru.xlf @@ -4,7 +4,7 @@ Error performing rename: '{0}' - Error performing rename: '{0}' + Ошибка при выполнении переименования: "{0}" diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.tr.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.tr.xlf index 7053b1eb6a1bb..8eae379c18e00 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.tr.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.tr.xlf @@ -4,7 +4,7 @@ Error performing rename: '{0}' - Error performing rename: '{0}' + Yeniden adlandırma işlemi gerçekleştirilirken hata oluştu: '{0}' diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.zh-Hans.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.zh-Hans.xlf index af71aa6ae3355..4b0694101e09a 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.zh-Hans.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.zh-Hans.xlf @@ -1,10 +1,10 @@  - + Error performing rename: '{0}' - Error performing rename: '{0}' + 执行重命名时出错:“{0}” diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.zh-Hant.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.zh-Hant.xlf index 14ad9260c5704..e2a01e3543531 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.zh-Hant.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.zh-Hant.xlf @@ -1,10 +1,10 @@  - + Error performing rename: '{0}' - Error performing rename: '{0}' + 執行重新命名時發生錯誤: '{0}' diff --git a/src/EditorFeatures/Core/Extensibility/Commands/PredefinedCommandHandlerNames.cs b/src/EditorFeatures/Core/Extensibility/Commands/PredefinedCommandHandlerNames.cs index 58609dae3ffef..545e53524b7d7 100644 --- a/src/EditorFeatures/Core/Extensibility/Commands/PredefinedCommandHandlerNames.cs +++ b/src/EditorFeatures/Core/Extensibility/Commands/PredefinedCommandHandlerNames.cs @@ -169,6 +169,11 @@ internal static class PredefinedCommandHandlerNames /// public const string PasteTrackingPaste = "Paste Tracking Paste Command Handler"; + /// + /// Command handler name for Paste in Add Imports. + /// + public const string AddImportsPaste = "Add Imports Paste Command Handler"; + /// /// Command handler name for Edit and Continue file save handler. /// diff --git a/src/EditorFeatures/Core/FindUsages/FindUsagesHelpers.cs b/src/EditorFeatures/Core/FindUsages/FindUsagesHelpers.cs index ef5b30fe6095d..fb6da25c517b7 100644 --- a/src/EditorFeatures/Core/FindUsages/FindUsagesHelpers.cs +++ b/src/EditorFeatures/Core/FindUsages/FindUsagesHelpers.cs @@ -4,17 +4,12 @@ #nullable disable -using System.Collections.Generic; using System.Collections.Immutable; -using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Shared.Extensions; -using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SymbolMapping; -using Microsoft.VisualStudio.Utilities; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.FindUsages { diff --git a/src/EditorFeatures/Core/FindUsages/IDefinitionsAndReferencesFactory.cs b/src/EditorFeatures/Core/FindUsages/IDefinitionsAndReferencesFactory.cs index d6c8af7ce067e..044a2e1922696 100644 --- a/src/EditorFeatures/Core/FindUsages/IDefinitionsAndReferencesFactory.cs +++ b/src/EditorFeatures/Core/FindUsages/IDefinitionsAndReferencesFactory.cs @@ -149,22 +149,6 @@ private static async Task ToDefinitionItemAsync( sourceLocations.Add(documentLocation); } - else - { - // Was this a source generated tree? If so, we don't have a document representaion (yet) so - // we'll create a metadata symbol which will later be handled by the symbol navigation service - // that way. Once we represent generated source trees as propery documents, we'll update the code above - // to correctly make this item. - var project = solution.GetOriginatingProject(definition); - var generatorRunResult = await project.GetGeneratorDriverRunResultAsync(cancellationToken).ConfigureAwait(false); - - if (generatorRunResult.TryGetGeneratorAndHint(location.SourceTree, out _, out _)) - { - return DefinitionItem.CreateMetadataDefinition( - tags, displayParts, nameDisplayParts, solution, - definition, properties, displayIfNoReferences); - } - } } } } diff --git a/src/EditorFeatures/Core/Implementation/AddImports/AbstractAddImportsPasteCommandHandler.cs b/src/EditorFeatures/Core/Implementation/AddImports/AbstractAddImportsPasteCommandHandler.cs new file mode 100644 index 0000000000000..b0dd73c076392 --- /dev/null +++ b/src/EditorFeatures/Core/Implementation/AddImports/AbstractAddImportsPasteCommandHandler.cs @@ -0,0 +1,103 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using Microsoft.CodeAnalysis.AddMissingImports; +using Microsoft.CodeAnalysis.Editor.Shared.Extensions; +using Microsoft.CodeAnalysis.Editor.Shared.Options; +using Microsoft.CodeAnalysis.Editor.Shared.Utilities; +using Microsoft.CodeAnalysis.Shared.Extensions; +using Microsoft.CodeAnalysis.Text; +using Microsoft.VisualStudio.Commanding; +using Microsoft.VisualStudio.Text; +using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; + +namespace Microsoft.CodeAnalysis.Editor.Implementation.AddImports +{ + internal abstract class AbstractAddImportsPasteCommandHandler : IChainedCommandHandler + { + /// + /// The command handler display name + /// + public abstract string DisplayName { get; } + + /// + /// The thread await dialog text shown to the user if the operation takes a long time + /// + protected abstract string DialogText { get; } + + private readonly IThreadingContext _threadingContext; + + public AbstractAddImportsPasteCommandHandler(IThreadingContext threadingContext) + => _threadingContext = threadingContext; + + public CommandState GetCommandState(PasteCommandArgs args, Func nextCommandHandler) + => nextCommandHandler(); + + public void ExecuteCommand(PasteCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext) + { + // Check that the feature is enabled before doing any work + if (!args.SubjectBuffer.GetFeatureOnOffOption(FeatureOnOffOptions.AddImportsOnPaste)) + { + nextCommandHandler(); + return; + } + + // Capture the pre-paste caret position + var caretPosition = args.TextView.GetCaretPoint(args.SubjectBuffer); + if (!caretPosition.HasValue) + { + nextCommandHandler(); + return; + } + + // Create a tracking span from the pre-paste caret position that will grow as text is inserted. + var trackingSpan = caretPosition.Value.Snapshot.CreateTrackingSpan(caretPosition.Value.Position, 0, SpanTrackingMode.EdgeInclusive); + + // Perform the paste command before adding imports + nextCommandHandler(); + + if (!args.SubjectBuffer.CanApplyChangeDocumentToWorkspace()) + { + return; + } + + // Don't perform work if we're inside the interactive window + if (args.TextView.IsNotSurfaceBufferOfTextView(args.SubjectBuffer)) + { + return; + } + + // Applying the post-paste snapshot to the tracking span gives us the span of pasted text. + var snapshotSpan = trackingSpan.GetSpan(args.SubjectBuffer.CurrentSnapshot); + var textSpan = snapshotSpan.Span.ToTextSpan(); + + var sourceTextContainer = args.SubjectBuffer.AsTextContainer(); + if (!Workspace.TryGetWorkspace(sourceTextContainer, out var workspace)) + { + return; + } + + var document = sourceTextContainer.GetOpenDocumentInCurrentContext(); + if (document is null) + { + return; + } + + using var _ = executionContext.OperationContext.AddScope(allowCancellation: true, DialogText); + var cancellationToken = executionContext.OperationContext.UserCancellationToken; + + var addMissingImportsService = document.GetRequiredLanguageService(); +#pragma warning disable VSTHRD102 // Implement internal logic asynchronously + var updatedDocument = _threadingContext.JoinableTaskFactory.Run(() => addMissingImportsService.AddMissingImportsAsync(document, textSpan, cancellationToken)); +#pragma warning restore VSTHRD102 // Implement internal logic asynchronously + if (updatedDocument is null) + { + return; + } + + workspace.TryApplyChanges(updatedDocument.Project.Solution); + } + } +} diff --git a/src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/CompletionSource.cs b/src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/CompletionSource.cs index 36a635357373f..0ae8aea56a039 100644 --- a/src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/CompletionSource.cs +++ b/src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/CompletionSource.cs @@ -222,6 +222,9 @@ private bool TryInvokeSnippetCompletion( SnapshotSpan applicableToSpan, CancellationToken cancellationToken) { + if (session is null) + throw new ArgumentNullException(nameof(session)); + session.Properties[TriggerLocation] = triggerLocation; return GetCompletionContextWorkerAsync(session, trigger, triggerLocation, isExpanded: false, cancellationToken); } @@ -364,6 +367,11 @@ private bool TryInvokeSnippetCompletion( public async Task GetDescriptionAsync(IAsyncCompletionSession session, VSCompletionItem item, CancellationToken cancellationToken) { + if (session is null) + throw new ArgumentNullException(nameof(session)); + if (item is null) + throw new ArgumentNullException(nameof(item)); + if (!item.Properties.TryGetProperty(RoslynItem, out RoslynCompletionItem roslynItem) || !Helpers.TryGetInitialTriggerLocation(session, out var triggerLocation)) { diff --git a/src/EditorFeatures/Core/Implementation/PasteTracking/PasteTrackingPasteCommandHandlercs.cs b/src/EditorFeatures/Core/Implementation/PasteTracking/PasteTrackingPasteCommandHandler.cs similarity index 97% rename from src/EditorFeatures/Core/Implementation/PasteTracking/PasteTrackingPasteCommandHandlercs.cs rename to src/EditorFeatures/Core/Implementation/PasteTracking/PasteTrackingPasteCommandHandler.cs index 02b6021dccce2..b5e27805f48bf 100644 --- a/src/EditorFeatures/Core/Implementation/PasteTracking/PasteTrackingPasteCommandHandlercs.cs +++ b/src/EditorFeatures/Core/Implementation/PasteTracking/PasteTrackingPasteCommandHandler.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable - using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor; @@ -44,6 +42,10 @@ public void ExecuteCommand(PasteCommandArgs args, Action nextCommandHandler, Com { // Capture the pre-paste caret position var caretPosition = args.TextView.GetCaretPoint(args.SubjectBuffer); + if (!caretPosition.HasValue) + { + return; + } // Allow the pasted text to be inserted and formatted. nextCommandHandler(); diff --git a/src/EditorFeatures/Core/Implementation/SplitComment/SplitCommentCommandHandler.cs b/src/EditorFeatures/Core/Implementation/SplitComment/SplitCommentCommandHandler.cs index 811290dbbb908..7f399654c87d9 100644 --- a/src/EditorFeatures/Core/Implementation/SplitComment/SplitCommentCommandHandler.cs +++ b/src/EditorFeatures/Core/Implementation/SplitComment/SplitCommentCommandHandler.cs @@ -27,7 +27,7 @@ namespace Microsoft.CodeAnalysis.Editor.Implementation.SplitComment { [Export(typeof(ICommandHandler))] - [ContentType(ContentTypeNames.CSharpContentType)] + [ContentType(ContentTypeNames.RoslynContentType)] [Name(nameof(SplitCommentCommandHandler))] [Order(After = PredefinedCompletionNames.CompletionCommandHandler)] internal sealed class SplitCommentCommandHandler : ICommandHandler @@ -65,6 +65,10 @@ public bool ExecuteCommand(ReturnKeyCommandArgs args, CommandExecutionContext co if (document == null) return false; + var splitCommentService = document.GetLanguageService(); + if (splitCommentService == null) + return false; + // If there is a selection, ensure that it's all on one-line. It's not clear what sort of semantics we // would want if this spanned multiple lines. var selectionSpan = spans[0].Span; @@ -76,7 +80,6 @@ public bool ExecuteCommand(ReturnKeyCommandArgs args, CommandExecutionContext co // Quick check. If the line doesn't contain a comment in it before the caret, // then no point in doing any more expensive synchronous work. - var splitCommentService = document.GetRequiredLanguageService(); if (!LineProbablyContainsComment(splitCommentService, new SnapshotPoint(snapshot, position))) return false; diff --git a/src/EditorFeatures/Core/Shared/Extensions/ITextViewExtensions.cs b/src/EditorFeatures/Core/Shared/Extensions/ITextViewExtensions.cs index cf40d0aa5ad62..3d790bb96ad84 100644 --- a/src/EditorFeatures/Core/Shared/Extensions/ITextViewExtensions.cs +++ b/src/EditorFeatures/Core/Shared/Extensions/ITextViewExtensions.cs @@ -377,5 +377,11 @@ public static bool TryGetSurfaceBufferSpan( return span; } + + /// + /// Determines if the textbuffer passed in matches the buffer for the textview. + /// + public static bool IsNotSurfaceBufferOfTextView(this ITextView textView, ITextBuffer textBuffer) + => textBuffer != textView.TextBuffer; } } diff --git a/src/EditorFeatures/Core/Shared/Options/FeatureOnOffOptions.cs b/src/EditorFeatures/Core/Shared/Options/FeatureOnOffOptions.cs index 24e1f7faf53d4..82db496d92a15 100644 --- a/src/EditorFeatures/Core/Shared/Options/FeatureOnOffOptions.cs +++ b/src/EditorFeatures/Core/Shared/Options/FeatureOnOffOptions.cs @@ -83,6 +83,9 @@ internal static class FeatureOnOffOptions public static readonly Option2 UseEnhancedColors = new( nameof(FeatureOnOffOptions), nameof(UseEnhancedColors), defaultValue: 1, storageLocations: new RoamingProfileStorageLocation("WindowManagement.Options.UseEnhancedColorsForManagedLanguages")); + + public static readonly PerLanguageOption2 AddImportsOnPaste = new( + nameof(FeatureOnOffOptions), nameof(AddImportsOnPaste), defaultValue: false); } [ExportOptionProvider, Shared] @@ -112,6 +115,7 @@ public FeatureOnOffOptionsProvider() FeatureOnOffOptions.RefactoringVerification, FeatureOnOffOptions.StreamingGoToImplementation, FeatureOnOffOptions.NavigateToDecompiledSources, - FeatureOnOffOptions.UseEnhancedColors); + FeatureOnOffOptions.UseEnhancedColors, + FeatureOnOffOptions.AddImportsOnPaste); } } diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.cs.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.cs.xlf index aa2232eaf4c3a..acb37b784a996 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.cs.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.cs.xlf @@ -79,7 +79,7 @@ Inline Hints - Inline Hints + Vložené nápovědy @@ -144,7 +144,7 @@ Split comment - Split comment + Dělený komentář @@ -259,7 +259,7 @@ User Types - Records - User Types - Records + Typy uživatelů – Záznamy diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.de.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.de.xlf index b9e62eda3ac3f..91196135e6b7d 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.de.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.de.xlf @@ -39,12 +39,12 @@ Error creating instance of CodeFixProvider - Error creating instance of CodeFixProvider + Fehler beim Erstellen der CodeFixProvider-Instanz Error creating instance of CodeFixProvider '{0}' - Error creating instance of CodeFixProvider '{0}' + Fehler beim Erstellen der CodeFixProvider-Instanz "{0}". @@ -79,7 +79,7 @@ Inline Hints - Inline Hints + Inlinehinweise @@ -144,7 +144,7 @@ Split comment - Split comment + Kommentar teilen @@ -259,7 +259,7 @@ User Types - Records - User Types - Records + Benutzertypen – Datensätze @@ -434,7 +434,7 @@ {0} unresolvable conflict(s) - {0} nicht lösbare Konflikt(s) + {0} nicht lösbare(r) Konflikt(e) @@ -1286,17 +1286,17 @@ Möchten Sie fortfahren? '{0}' references - '"{0}"-Verweise + "{0}"-Verweise '{0}' implementations - '"{0}"-Implementierungen + "{0}"-Implementierungen '{0}' declarations - '"{0}"-Deklarationen + "{0}"-Deklarationen diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.es.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.es.xlf index 9e23a7f42aeb9..25f4a05ac96ac 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.es.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.es.xlf @@ -39,12 +39,12 @@ Error creating instance of CodeFixProvider - Error creating instance of CodeFixProvider + Error al crear la instancia de CodeFixProvider Error creating instance of CodeFixProvider '{0}' - Error creating instance of CodeFixProvider '{0}' + Error al crear la instancia de CodeFixProvider "{0}" @@ -79,7 +79,7 @@ Inline Hints - Inline Hints + Sugerencias insertadas @@ -144,7 +144,7 @@ Split comment - Split comment + Dividir comentario @@ -259,7 +259,7 @@ User Types - Records - User Types - Records + Tipos de usuario: registros diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.fr.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.fr.xlf index 5076aa2bc2b05..64d61696a80c0 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.fr.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.fr.xlf @@ -39,12 +39,12 @@ Error creating instance of CodeFixProvider - Error creating instance of CodeFixProvider + Erreur lors de la création de l'instance de CodeFixProvider Error creating instance of CodeFixProvider '{0}' - Error creating instance of CodeFixProvider '{0}' + Erreur lors de la création de l'instance de CodeFixProvider '{0}' @@ -79,7 +79,7 @@ Inline Hints - Inline Hints + Indicateurs inline @@ -144,7 +144,7 @@ Split comment - Split comment + Diviser le commentaire @@ -259,7 +259,7 @@ User Types - Records - User Types - Records + Types d'utilisateur - Enregistrements diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.it.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.it.xlf index 70c08772e60fc..93f5be573a44b 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.it.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.it.xlf @@ -39,12 +39,12 @@ Error creating instance of CodeFixProvider - Error creating instance of CodeFixProvider + Si è verificato un errore durante la creazione dell'istanza di CodeFixProvider Error creating instance of CodeFixProvider '{0}' - Error creating instance of CodeFixProvider '{0}' + Si è verificato un errore durante la creazione dell'istanza di CodeFixProvider '{0}' @@ -79,7 +79,7 @@ Inline Hints - Inline Hints + Suggerimenti inline @@ -144,7 +144,7 @@ Split comment - Split comment + Dividi commento @@ -259,7 +259,7 @@ User Types - Records - User Types - Records + Tipi utente - Record @@ -994,7 +994,7 @@ Not a source error, line/column unavailable - L'errore non dipende dall'origine. La riga o la colonna non è disponibile. + L'errore non dipende dall'origine. La riga o la colonna non è disponibile diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ja.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ja.xlf index e1f8bea00dcff..eb9a8adc7cf97 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ja.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ja.xlf @@ -39,12 +39,12 @@ Error creating instance of CodeFixProvider - Error creating instance of CodeFixProvider + CodeFixProvider のインスタンスの作成でエラーが発生しました Error creating instance of CodeFixProvider '{0}' - Error creating instance of CodeFixProvider '{0}' + CodeFixProvider '{0}' のインスタンスの作成でエラーが発生しました @@ -79,7 +79,7 @@ Inline Hints - Inline Hints + インラインのヒント @@ -144,7 +144,7 @@ Split comment - Split comment + コメントの分割 @@ -259,7 +259,7 @@ User Types - Records - User Types - Records + ユーザー タイプ - レコード @@ -644,7 +644,7 @@ Rename operation was cancelled or is not valid - 名前の変更操作は取り消されたか、または検証されていません。 + 名前の変更操作は取り消されたか、または検証されていません @@ -664,7 +664,7 @@ Rename '{0}' to '{1}' - {0}' を '{1}' に名前変更 + '{0}' を '{1}' に名前変更 @@ -1111,7 +1111,7 @@ Do you want to proceed? Rename '{0}' to '{1}': - {0}' の名前を '{1}' に変更します。 + '{0}' の名前を '{1}' に変更します: @@ -1126,7 +1126,7 @@ Do you want to proceed? Calls To '{0}' - {0}' への呼び出し + '{0}' への呼び出し @@ -1146,7 +1146,7 @@ Do you want to proceed? Implements '{0}' - {0}' を実装します + '{0}' を実装します @@ -1166,7 +1166,7 @@ Do you want to proceed? _Preview changes - プレビューの変更(_P) + 変更のプレビュー(_P) diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ko.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ko.xlf index 43de3b6d2d614..2dd71585c3b1d 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ko.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ko.xlf @@ -39,12 +39,12 @@ Error creating instance of CodeFixProvider - Error creating instance of CodeFixProvider + CodeFixProvider 인스턴스를 만드는 동안 오류가 발생했습니다. Error creating instance of CodeFixProvider '{0}' - Error creating instance of CodeFixProvider '{0}' + CodeFixProvider '{0}' 인스턴스를 만드는 동안 오류가 발생했습니다. @@ -79,7 +79,7 @@ Inline Hints - Inline Hints + 인라인 힌트 @@ -144,7 +144,7 @@ Split comment - Split comment + 주석 분할 @@ -259,7 +259,7 @@ User Types - Records - User Types - Records + 사용자 유형 - 레코드 @@ -449,37 +449,37 @@ Adding project '{0}' - {0}' 프로젝트 추가 중 + '{0}' 프로젝트 추가 중 Removing project '{0}' - {0}' 프로젝트를 제거하는 중 + '{0}' 프로젝트를 제거하는 중 Changing project references for '{0}' - {0}'에 대한 프로젝트 참조 변경 중 + '{0}'에 대한 프로젝트 참조 변경 중 Adding reference '{0}' to '{1}' - {1}'에 대한 '{0}' 참조 추가 중 + '{1}'에 대한 '{0}' 참조 추가 중 Removing reference '{0}' from '{1}' - {1}'에서 '{0}' 참조를 제거하는 중 + '{1}'에서 '{0}' 참조를 제거하는 중 Adding analyzer reference '{0}' to '{1}' - {1}'에 대한 '{0}' 분석기 참조 추가 중 + '{1}'에 대한 '{0}' 분석기 참조 추가 중 Removing analyzer reference '{0}' from '{1}' - {1}'에서 '{0}' 분석기 참조를 제거하는 중 + '{1}'에서 '{0}' 분석기 참조를 제거하는 중 @@ -664,7 +664,7 @@ Rename '{0}' to '{1}' - {1}'(으)로 '{0}' 이름 바꾸기 + '{1}'(으)로 '{0}' 이름 바꾸기 @@ -1126,17 +1126,17 @@ Do you want to proceed? Calls To '{0}' - {0}'에 대한 호출 + '{0}'에 대한 호출 Calls To Base Member '{0}' - {0}' 기본 멤버에 대한 호출 + '{0}' 기본 멤버에 대한 호출 Calls To Interface Implementation '{0}' - {0}' 인터페이스 구현에 대한 호출 + '{0}' 인터페이스 구현에 대한 호출 @@ -1146,7 +1146,7 @@ Do you want to proceed? Implements '{0}' - {0}' 구현 + '{0}' 구현 @@ -1156,7 +1156,7 @@ Do you want to proceed? References To Field '{0}' - {0}' 필드에 대한 참조 + '{0}' 필드에 대한 참조 diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.pl.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.pl.xlf index 665f0890d886c..6d272bf833bae 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.pl.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.pl.xlf @@ -39,12 +39,12 @@ Error creating instance of CodeFixProvider - Error creating instance of CodeFixProvider + Błąd podczas tworzenia wystąpienia elementu CodeFixProvider Error creating instance of CodeFixProvider '{0}' - Error creating instance of CodeFixProvider '{0}' + Błąd podczas tworzenia wystąpienia elementu CodeFixProvider „{0}” @@ -79,7 +79,7 @@ Inline Hints - Inline Hints + Wskazówki w tekście @@ -144,7 +144,7 @@ Split comment - Split comment + Podziel komentarz @@ -259,7 +259,7 @@ User Types - Records - User Types - Records + Typy użytkownika — rekordy diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.pt-BR.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.pt-BR.xlf index f00ce20f9b263..1e98d2c4e5cd1 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.pt-BR.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.pt-BR.xlf @@ -39,12 +39,12 @@ Error creating instance of CodeFixProvider - Error creating instance of CodeFixProvider + Erro ao criar a instância de CodeFixProvider Error creating instance of CodeFixProvider '{0}' - Error creating instance of CodeFixProvider '{0}' + Erro ao criar instância de CodeFixProvider '{0}' @@ -79,7 +79,7 @@ Inline Hints - Inline Hints + Dicas Embutidas @@ -144,7 +144,7 @@ Split comment - Split comment + Dividir o comentário @@ -259,7 +259,7 @@ User Types - Records - User Types - Records + Tipos de Usuário – Registros diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ru.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ru.xlf index 0c3c539d3ee86..31ebdfd306e68 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ru.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ru.xlf @@ -39,12 +39,12 @@ Error creating instance of CodeFixProvider - Error creating instance of CodeFixProvider + Ошибка при создании экземпляра CodeFixProvider. Error creating instance of CodeFixProvider '{0}' - Error creating instance of CodeFixProvider '{0}' + Ошибка при создании экземпляра CodeFixProvider "{0}". @@ -79,7 +79,7 @@ Inline Hints - Inline Hints + Встроенные подсказки @@ -144,7 +144,7 @@ Split comment - Split comment + Разделительный комментарий @@ -259,7 +259,7 @@ User Types - Records - User Types - Records + Пользовательские типы — записи @@ -1211,7 +1211,7 @@ Do you want to proceed? '{0}' does not support the '{1}' operation. However, it may contain nested '{2}'s (see '{2}.{3}') that support this operation. - '"{0}" не поддерживает операцию "{1}", но может содержать вложенные "{2}" (см. "{2}.{3}"), которые поддерживают эту операцию. + "{0}" не поддерживает операцию "{1}", но может содержать вложенные "{2}" (см. "{2}.{3}"), которые поддерживают эту операцию. diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.tr.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.tr.xlf index 326d4dd327927..80a50d63bddbe 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.tr.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.tr.xlf @@ -39,12 +39,12 @@ Error creating instance of CodeFixProvider - Error creating instance of CodeFixProvider + CodeFixProvider örneği oluşturulurken hata oluştu Error creating instance of CodeFixProvider '{0}' - Error creating instance of CodeFixProvider '{0}' + '{0}' CodeFixProvider örneği oluşturulurken hata oluştu @@ -79,7 +79,7 @@ Inline Hints - Inline Hints + Satır İçi İpuçları @@ -144,7 +144,7 @@ Split comment - Split comment + Açıklamayı böl @@ -259,7 +259,7 @@ User Types - Records - User Types - Records + Kullanıcı Türleri - Kayıtlar @@ -444,32 +444,32 @@ Adding '{0}' to '{1}' with content: - {0}' şu içerik ile '{1}' üzerine ekleniyor: + '{0}' şu içerik ile '{1}' üzerine ekleniyor: Adding project '{0}' - {0}' projesi ekleniyor + '{0}' projesi ekleniyor Removing project '{0}' - {0}' projesi kaldırılıyor + '{0}' projesi kaldırılıyor Changing project references for '{0}' - {0}' için proje başvuruları değiştiriliyor + '{0}' için proje başvuruları değiştiriliyor Adding reference '{0}' to '{1}' - {0}' başvurusu '{1}' üzerine ekleniyor + '{0}' başvurusu '{1}' üzerine ekleniyor Removing reference '{0}' from '{1}' - {0}' başvurusu '{1}' üzerinden kaldırılıyor + '{0}' başvurusu '{1}' üzerinden kaldırılıyor @@ -664,7 +664,7 @@ Rename '{0}' to '{1}' - {0}' öğesini '{1}' olarak yeniden adlandır + '{0}' öğesini '{1}' olarak yeniden adlandır @@ -1111,7 +1111,7 @@ Devam etmek istiyor musunuz? Rename '{0}' to '{1}': - {0}' öğesini '{1}' olarak yeniden adlandır: + '{0}' öğesini '{1}' olarak yeniden adlandır: @@ -1126,7 +1126,7 @@ Devam etmek istiyor musunuz? Calls To '{0}' - {0}' Öğesine Çağrılar + '{0}' Öğesine Çağrılar @@ -1136,7 +1136,7 @@ Devam etmek istiyor musunuz? Calls To Interface Implementation '{0}' - {0}' Arayüz Uygulama Çağrıları + '{0}' Arayüz Uygulama Çağrıları @@ -1146,7 +1146,7 @@ Devam etmek istiyor musunuz? Implements '{0}' - {0}' öğesini uygular + '{0}' öğesini uygular @@ -1156,7 +1156,7 @@ Devam etmek istiyor musunuz? References To Field '{0}' - {0}' Alanına Yapılan Başvurular + '{0}' Alanına Yapılan Başvurular @@ -1206,7 +1206,7 @@ Devam etmek istiyor musunuz? Removing '{0}' from '{1}' with content: - {0}' öğesi, içeriği şu olan '{1}' öğesinden kaldırılıyor: + '{0}' öğesi, içeriği şu olan '{1}' öğesinden kaldırılıyor: diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.zh-Hans.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.zh-Hans.xlf index f443d78eb5025..7efa8fb1d22c1 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.zh-Hans.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. @@ -79,7 +79,7 @@ Inline Hints - Inline Hints + 内联提示 @@ -144,7 +144,7 @@ Split comment - Split comment + 拆分注释 @@ -259,7 +259,7 @@ User Types - Records - User Types - Records + 用户类型 - 记录 @@ -1206,12 +1206,12 @@ Do you want to proceed? Removing '{0}' from '{1}' with content: - 将“{0}”连带内容从“{1}”删除。 + 将“{0}”连带内容从“{1}”删除: '{0}' does not support the '{1}' operation. However, it may contain nested '{2}'s (see '{2}.{3}') that support this operation. - '“{0}”不支持“{1}”操作。但是,它可能包含支持此操作的嵌套“{2}”(参见“{2}.{3}”)。 + “{0}”不支持“{1}”操作。但是,它可能包含支持此操作的嵌套“{2}”(参见“{2}.{3}”)。 @@ -1286,17 +1286,17 @@ Do you want to proceed? '{0}' references - '“{0}”引用 + “{0}”引用 '{0}' implementations - '“{0}”实现 + “{0}”实现 '{0}' declarations - '“{0}”声明 + “{0}”声明 diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.zh-Hant.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.zh-Hant.xlf index 17562cc418696..397f80f81207d 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.zh-Hant.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. @@ -39,12 +39,12 @@ Error creating instance of CodeFixProvider - Error creating instance of CodeFixProvider + 建立 CodeFixProvider 的執行個體時發生錯誤 Error creating instance of CodeFixProvider '{0}' - Error creating instance of CodeFixProvider '{0}' + 建立 CodeFixProvider '{0}' 的執行個體時發生錯誤 @@ -79,7 +79,7 @@ Inline Hints - Inline Hints + 內嵌提示 @@ -144,7 +144,7 @@ Split comment - Split comment + 分割註解 @@ -259,7 +259,7 @@ User Types - Records - User Types - Records + 使用者類型 - 記錄 @@ -994,7 +994,7 @@ Not a source error, line/column unavailable - 非來源錯誤,行/資料行無法使用。 + 非來源錯誤,行/資料行無法使用 diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.ConstructorSymbols.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.ConstructorSymbols.vb index 910ee7621b784..617336626710c 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.ConstructorSymbols.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.ConstructorSymbols.vb @@ -894,6 +894,34 @@ class C Await TestAPIAndFeature(input, kind, host) End Function + + + Public Async Function DoNotCountInstantiationTwiceWhenTargetTypedNewExists(kind As TestKind, host As TestHost) As Task + Dim input = + + + +class Bar +{ + public {|Definition:$$Bar|}() { } +} + + +public class Foo +{ + private readonly Bar bar1 = [|new|](); + private readonly Bar bar2; + public Foo(Bar bar) + { + this.bar2 = new [|Bar|](); + } +} + + + + Await TestAPIAndFeature(input, kind, host) + End Function + Public Async Function TestConstructorReferenceInGlobalSuppression(kind As TestKind, host As TestHost) As Task diff --git a/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests.vb b/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests.vb index 2a779f9155390..e80fed00ca754 100644 --- a/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests.vb +++ b/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests.vb @@ -7,6 +7,7 @@ Imports System.Composition Imports System.Globalization Imports System.Threading Imports Microsoft.CodeAnalysis.Completion +Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.CSharp Imports Microsoft.CodeAnalysis.Editor.CSharp.Formatting Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion @@ -7580,6 +7581,325 @@ class C End Using End Function + + + Public Sub TestCompleteMethodParenthesisForSymbolCompletionProvider(showCompletionInArgumentLists As Boolean) + Using state = TestStateFactory.CreateCSharpTestState( + + public class B + { + private void C11() + { + $$ + } + }, + showCompletionInArgumentLists:=showCompletionInArgumentLists) + + Dim expectedText = " + public class B + { + private void C11() + { + C11(); + } + }" + state.SendTypeChars("C") + Dim expectingItem = state.GetCompletionItems().First(Function(item) item.DisplayText.Equals("C11")) + Assert.True(SymbolCompletionItem.GetShouldProvideParenthesisCompletion(expectingItem)) + + state.SendSelectCompletionItem("C11") + state.SendTypeChars(";") + Assert.Equal(expectedText, state.GetDocumentText()) + End Using + End Sub + + + + Public Sub TestCompleteMethodParenthesisForSymbolCompletionProviderUnderDelegateContext(showCompletionInArgumentLists As Boolean) + Using state = TestStateFactory.CreateCSharpTestState( + + using System; + public class B + { + private void C11() + { + Action t = $$ + } + }, + showCompletionInArgumentLists:=showCompletionInArgumentLists) + + Dim expectedText = " + using System; + public class B + { + private void C11() + { + Action t = C11; + } + }" + state.SendTypeChars("C") + Dim expectingItem = state.GetCompletionItems().First(Function(item) item.DisplayText.Equals("C11")) + Assert.False(SymbolCompletionItem.GetShouldProvideParenthesisCompletion(expectingItem)) + + state.SendSelectCompletionItem("C11") + state.SendTypeChars(";") + Assert.Equal(expectedText, state.GetDocumentText()) + End Using + End Sub + + + + Public Sub TestCompleteObjectCreationParenthesisForSymbolCreationCompletionProvider(showCompletionInArgumentLists As Boolean) + Using state = TestStateFactory.CreateCSharpTestState( + + using Bar = System.String + public class AA + { + private static void CC() + { + var a = new $$ + } + }, + showCompletionInArgumentLists:=showCompletionInArgumentLists) + + Dim expectedText = " + using Bar = System.String + public class AA + { + private static void CC() + { + var a = new Bar(); + } + }" + state.SendTypeChars("B") + Dim expectingItem = state.GetCompletionItems().First(Function(item) item.DisplayText.Equals("AA")) + Assert.True(SymbolCompletionItem.GetShouldProvideParenthesisCompletion(expectingItem)) + + state.SendSelectCompletionItem("Bar") + state.SendTypeChars(";") + Assert.Equal(expectedText, state.GetDocumentText()) + End Using + End Sub + + + + Public Sub TestCompleteObjectCreationParenthesisForSymbolCreationCompletionProviderUnderNonObjectCreationContext(showCompletionInArgumentLists As Boolean) + Using state = TestStateFactory.CreateCSharpTestState( + + using Bar = System.String + public class AA + { + private static void CC() + { + $$ + } + }, + showCompletionInArgumentLists:=showCompletionInArgumentLists) + + Dim expectedText = " + using Bar = System.String + public class AA + { + private static void CC() + { + Bar; + } + }" + state.SendTypeChars("B") + Dim expectingItem = state.GetCompletionItems().First(Function(item) item.DisplayText.Equals("AA")) + Assert.False(SymbolCompletionItem.GetShouldProvideParenthesisCompletion(expectingItem)) + + state.SendSelectCompletionItem("Bar") + + state.SendTypeChars(";") + Assert.Equal(expectedText, state.GetDocumentText()) + End Using + End Sub + + + + Public Sub TestCompleteParenthesisForObjectCreationCompletionProvider(showCompletionInArgumentLists As Boolean) + Using state = TestStateFactory.CreateCSharpTestState( + + public class AA + { + private static void CC() + { + AA a = new $$ + } + }, + showCompletionInArgumentLists:=showCompletionInArgumentLists) + + Dim expectedText = " + public class AA + { + private static void CC() + { + AA a = new AA(); + } + }" + state.SendTypeChars("A") + state.SendSelectCompletionItem("AA") + state.SendTypeChars(";") + Assert.Equal(expectedText, state.GetDocumentText()) + End Using + End Sub + + + + Public Sub TestCompleteParenthesisForExtensionMethodImportCompletionProvider(showCompletionInArgumentLists As Boolean) + Using state = TestStateFactory.CreateCSharpTestState( + +namespace CC +{ + public static class DD + { + public static int ToInt(this AA a) => 1; + } +} +public class AA +{ + private static void CC() + { + AA a = new AA(); + var value = a.$$ + } +}, + showCompletionInArgumentLists:=showCompletionInArgumentLists) + state.Workspace.SetOptions( + state.Workspace.Options.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True)) + + Dim expectedText = " +using CC; + +namespace CC +{ + public static class DD + { + public static int ToInt(this AA a) => 1; + } +} +public class AA +{ + private static void CC() + { + AA a = new AA(); + var value = a.ToInt(); + } +}" + state.SendTypeChars("To") + state.SendSelectCompletionItem("ToInt") + state.SendTypeChars(";") + Assert.Equal(expectedText, state.GetDocumentText()) + End Using + End Sub + + + + Public Async Function TestCompleteParenthesisForTypeImportCompletionProvider(showCompletionInArgumentLists As Boolean) As Task + Using state = TestStateFactory.CreateCSharpTestState( + +namespace CC +{ + public class Bar + { + } +} +public class AA +{ + private static void CC() + { + var a = new $$ + } +}, + showCompletionInArgumentLists:=showCompletionInArgumentLists) + state.Workspace.SetOptions(state.Workspace.Options.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True)) + + state.SendInvokeCompletionList() + Await state.WaitForAsynchronousOperationsAsync() + Await state.WaitForUIRenderedAsync() + + ' Make sure expander is selected + state.SetCompletionItemExpanderState(isSelected:=True) + Await state.WaitForAsynchronousOperationsAsync() + Await state.WaitForUIRenderedAsync() + + Dim expectedText = " +using CC; + +namespace CC +{ + public class Bar + { + } +} +public class AA +{ + private static void CC() + { + var a = new Bar(); + } +}" + state.SendTypeChars("Ba") + state.SendSelectCompletionItem("Bar") + state.SendTypeChars(";") + Assert.Equal(expectedText, state.GetDocumentText()) + End Using + End Function + + + + Public Async Function TestCompleteParenthesisForTypeImportCompletionProviderUnderNonObjectCreationContext(showCompletionInArgumentLists As Boolean) As Task + Using state = TestStateFactory.CreateCSharpTestState( + +namespace CC +{ + public class Bar + { + } +} +public class AA +{ + private static void CC() + { + $$ + } +}, + showCompletionInArgumentLists:=showCompletionInArgumentLists) + state.Workspace.SetOptions(state.Workspace.Options.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True)) + + state.SendInvokeCompletionList() + Await state.WaitForAsynchronousOperationsAsync() + Await state.WaitForUIRenderedAsync() + + ' Make sure expander is selected + state.SetCompletionItemExpanderState(isSelected:=True) + Await state.WaitForAsynchronousOperationsAsync() + Await state.WaitForUIRenderedAsync() + + Dim expectedText = " +using CC; + +namespace CC +{ + public class Bar + { + } +} +public class AA +{ + private static void CC() + { + Bar; + } +}" + state.SendTypeChars("Ba") + state.SendSelectCompletionItem("Bar") + state.SendTypeChars(";") + Assert.Equal(expectedText, state.GetDocumentText()) + End Using + End Function + ' Simulates a situation where IntelliCode provides items not included into the Rolsyn original list. ' We want to ignore these items in CommitIfUnique. ' This situation should not happen. Tests with this provider were added to cover protective scenarios. diff --git a/src/EditorFeatures/TestUtilities/Completion/AbstractCompletionProviderTests.cs b/src/EditorFeatures/TestUtilities/Completion/AbstractCompletionProviderTests.cs index 5a174e0bcfbbe..aaf9bfb1680e6 100644 --- a/src/EditorFeatures/TestUtilities/Completion/AbstractCompletionProviderTests.cs +++ b/src/EditorFeatures/TestUtilities/Completion/AbstractCompletionProviderTests.cs @@ -553,6 +553,7 @@ private async Task VerifyProviderCommitWorkerAsync(string codeBeforeCommit, int private async Task VerifyProviderCommitCheckResultsAsync( Document document, int position, string itemToCommit, string expectedCodeAfterCommit, char? commitCharOpt) { + document = WithChangedOptions(document); var service = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(service, document, position, RoslynCompletion.CompletionTrigger.Invoke); var items = completionList.Items; @@ -628,7 +629,7 @@ protected static string CreateMarkupForProjectWithMetadataReference(string marku } protected Task VerifyItemWithAliasedMetadataReferencesAsync(string markup, string metadataAlias, string expectedItem, int expectedSymbols, - string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers) + string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers) { var xmlString = CreateMarkupForProjectWithAliasedMetadataReference(markup, metadataAlias, "", sourceLanguage, referencedLanguage); diff --git a/src/EditorFeatures/TestUtilities/Diagnostics/TestAnalyzerReferenceByLanguage.cs b/src/EditorFeatures/TestUtilities/Diagnostics/TestAnalyzerReferenceByLanguage.cs index 070fe33410042..7775cd555c514 100644 --- a/src/EditorFeatures/TestUtilities/Diagnostics/TestAnalyzerReferenceByLanguage.cs +++ b/src/EditorFeatures/TestUtilities/Diagnostics/TestAnalyzerReferenceByLanguage.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable - using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; @@ -14,10 +12,13 @@ internal class TestAnalyzerReferenceByLanguage : AnalyzerReference { private readonly IReadOnlyDictionary> _analyzersMap; - public TestAnalyzerReferenceByLanguage(IReadOnlyDictionary> analyzersMap) - => _analyzersMap = analyzersMap; + public TestAnalyzerReferenceByLanguage(IReadOnlyDictionary> analyzersMap, string? fullPath = null) + { + _analyzersMap = analyzersMap; + FullPath = fullPath; + } - public override string FullPath => null; + public override string? FullPath { get; } public override string Display => nameof(TestAnalyzerReferenceByLanguage); public override object Id => Display; diff --git a/src/EditorFeatures/TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs b/src/EditorFeatures/TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs index f78efa216961c..2e31bc243d9fb 100644 --- a/src/EditorFeatures/TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs +++ b/src/EditorFeatures/TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs @@ -47,7 +47,7 @@ public abstract class AbstractLanguageServerProtocolTests internal class TestLspSolutionProvider : ILspSolutionProvider { [DisallowNull] - private Solution? _currentSolution; + private TestWorkspace? _workspace; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] @@ -55,21 +55,20 @@ public TestLspSolutionProvider() { } - public void UpdateSolution(Solution solution) + public void SetTestWorkspace(TestWorkspace workspace) { - _currentSolution = solution; + _workspace = workspace; } public Solution GetCurrentSolutionForMainWorkspace() { - Contract.ThrowIfNull(_currentSolution); - return _currentSolution; + Contract.ThrowIfNull(_workspace); + return _workspace.CurrentSolution; } public ImmutableArray GetDocuments(Uri documentUri) { - Contract.ThrowIfNull(_currentSolution); - return _currentSolution.GetDocuments(documentUri); + return GetCurrentSolutionForMainWorkspace().GetDocuments(documentUri); } } @@ -102,13 +101,18 @@ public Task> MapSpansAsync(Document document, I ImmutableArray mappedResult = default; if (document.Name == GeneratedFileName) { - mappedResult = ImmutableArray.Create(new MappedSpanResult(s_mappedFilePath, s_mappedLinePosition, new TextSpan(0, 5))); + mappedResult = spans.Select(span => new MappedSpanResult(s_mappedFilePath, s_mappedLinePosition, new TextSpan(0, 5))).ToImmutableArray(); } return Task.FromResult(mappedResult); } } + protected class OrderLocations : Comparer + { + public override int Compare(LSP.Location x, LSP.Location y) => CompareLocations(x, y); + } + protected virtual TestComposition Composition => s_composition; /// @@ -117,7 +121,7 @@ public Task> MapSpansAsync(Document document, I /// the JSON object type. /// the expected object to be converted to JSON. /// the actual object to be converted to JSON. - protected static void AssertJsonEquals(T expected, T actual) + public static void AssertJsonEquals(T expected, T actual) { var expectedStr = JsonConvert.SerializeObject(expected); var actualStr = JsonConvert.SerializeObject(actual); @@ -141,13 +145,13 @@ protected static void AssertLocationsEqual(IEnumerable expectedLoc var orderedExpectedLocations = expectedLocations.OrderBy(CompareLocations); AssertJsonEquals(orderedExpectedLocations, orderedActualLocations); + } - static int CompareLocations(LSP.Location l1, LSP.Location l2) - { - var compareDocument = l1.Uri.OriginalString.CompareTo(l2.Uri.OriginalString); - var compareRange = CompareRange(l1.Range, l2.Range); - return compareDocument != 0 ? compareDocument : compareRange; - } + protected static int CompareLocations(LSP.Location l1, LSP.Location l2) + { + var compareDocument = l1.Uri.OriginalString.CompareTo(l2.Uri.OriginalString); + var compareRange = CompareRange(l1.Range, l2.Range); + return compareDocument != 0 ? compareDocument : compareRange; } protected static int CompareRange(LSP.Range r1, LSP.Range r2) @@ -296,6 +300,7 @@ private TestWorkspace CreateTestWorkspace(string[] markups, out Dictionary throw new ArgumentException($"language name {languageName} is not valid for a test workspace"), }; + SetSolutionProviderWorkspace(workspace); var solution = workspace.CurrentSolution; foreach (var document in workspace.Documents) @@ -307,15 +312,14 @@ private TestWorkspace CreateTestWorkspace(string[] markups, out Dictionary> locations) { var workspace = TestWorkspace.Create(xmlContent, composition: Composition); + SetSolutionProviderWorkspace(workspace); locations = GetAnnotatedLocations(workspace, workspace.CurrentSolution); - UpdateSolutionProvider(workspace, workspace.CurrentSolution); return workspace; } @@ -328,16 +332,15 @@ protected static void AddMappedDocument(Workspace workspace, string markup) SourceCodeKind.Regular, loader, $"C:\\{TestSpanMapper.GeneratedFileName}", isGenerated: true, designTimeOnly: false, new TestSpanMapperProvider()); var newSolution = workspace.CurrentSolution.AddDocument(generatedDocumentInfo); workspace.TryApplyChanges(newSolution); - UpdateSolutionProvider((TestWorkspace)workspace, newSolution); } - private protected static void UpdateSolutionProvider(TestWorkspace workspace, Solution solution) + private protected static void SetSolutionProviderWorkspace(TestWorkspace workspace) { var provider = (TestLspSolutionProvider)workspace.ExportProvider.GetExportedValue(); - provider.UpdateSolution(solution); + provider.SetTestWorkspace(workspace); } - private static Dictionary> GetAnnotatedLocations(TestWorkspace workspace, Solution solution) + public static Dictionary> GetAnnotatedLocations(TestWorkspace workspace, Solution solution) { var locations = new Dictionary>(); foreach (var testDocument in workspace.Documents) diff --git a/src/EditorFeatures/TestUtilities/Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj b/src/EditorFeatures/TestUtilities/Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj index b7823c8a0373d..74da299d6ea16 100644 --- a/src/EditorFeatures/TestUtilities/Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj +++ b/src/EditorFeatures/TestUtilities/Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj @@ -23,6 +23,7 @@ + diff --git a/src/EditorFeatures/TestUtilities/Structure/AbstractSyntaxNodeStructureProviderTests.cs b/src/EditorFeatures/TestUtilities/Structure/AbstractSyntaxNodeStructureProviderTests.cs index a2a4d04f879ac..0e10bece8851d 100644 --- a/src/EditorFeatures/TestUtilities/Structure/AbstractSyntaxNodeStructureProviderTests.cs +++ b/src/EditorFeatures/TestUtilities/Structure/AbstractSyntaxNodeStructureProviderTests.cs @@ -41,7 +41,10 @@ internal sealed override async Task> GetBlockSpansWork var outliner = CreateProvider(); var actualRegions = ArrayBuilder.GetInstance(); - outliner.CollectBlockSpans(document, node, actualRegions, CancellationToken.None); + var optionProvider = new BlockStructureOptionProvider( + document.Project.Solution.Options, + isMetadataAsSource: document.Project.Solution.Workspace.Kind == CodeAnalysis.WorkspaceKind.MetadataAsSource); + outliner.CollectBlockSpans(node, actualRegions, optionProvider, CancellationToken.None); // TODO: Determine why we get null outlining spans. return actualRegions.ToImmutableAndFree(); diff --git a/src/EditorFeatures/TestUtilities/Structure/AbstractSyntaxTriviaStructureProviderTests.cs b/src/EditorFeatures/TestUtilities/Structure/AbstractSyntaxTriviaStructureProviderTests.cs index d61e4aa5557d3..5e5c3cc2bff99 100644 --- a/src/EditorFeatures/TestUtilities/Structure/AbstractSyntaxTriviaStructureProviderTests.cs +++ b/src/EditorFeatures/TestUtilities/Structure/AbstractSyntaxTriviaStructureProviderTests.cs @@ -23,7 +23,10 @@ internal sealed override async Task> GetBlockSpansWork var outliner = CreateProvider(); var actualRegions = ArrayBuilder.GetInstance(); - outliner.CollectBlockSpans(document, trivia, actualRegions, CancellationToken.None); + var optionProvider = new BlockStructureOptionProvider( + document.Project.Solution.Options, + isMetadataAsSource: document.Project.Solution.Workspace.Kind == CodeAnalysis.WorkspaceKind.MetadataAsSource); + outliner.CollectBlockSpans(trivia, actualRegions, optionProvider, CancellationToken.None); // TODO: Determine why we get null outlining spans. return actualRegions.ToImmutableAndFree(); diff --git a/src/EditorFeatures/TestUtilities/Threading/StaTaskScheduler.cs b/src/EditorFeatures/TestUtilities/Threading/StaTaskScheduler.cs index 4156e506ea8f4..b955530567b75 100644 --- a/src/EditorFeatures/TestUtilities/Threading/StaTaskScheduler.cs +++ b/src/EditorFeatures/TestUtilities/Threading/StaTaskScheduler.cs @@ -5,8 +5,10 @@ #nullable disable using System; +using System.Reflection; using System.Threading; using System.Windows.Threading; +using Microsoft.CodeAnalysis.Test.Utilities; namespace Roslyn.Test.Utilities { @@ -24,6 +26,12 @@ public sealed class StaTaskScheduler : IDisposable static StaTaskScheduler() { + // Overwrite xunit's app domain handling to not call AppDomain.Unload + var getDefaultDomain = typeof(AppDomain).GetMethod("GetDefaultDomain", BindingFlags.NonPublic | BindingFlags.Static); + var defaultDomain = (AppDomain)getDefaultDomain.Invoke(null, null); + var hook = (XunitDisposeHook)defaultDomain.CreateInstanceFromAndUnwrap(typeof(XunitDisposeHook).Assembly.CodeBase, typeof(XunitDisposeHook).FullName, ignoreCase: false, BindingFlags.CreateInstance, binder: null, args: null, culture: null, activationAttributes: null); + hook.Execute(); + // We've created an STA thread, which has some extra requirements for COM Runtime // Callable Wrappers (RCWs). If any COM object is created on the STA thread, calls to that // object must be made from that thread; when the RCW is no longer being used by any diff --git a/src/EditorFeatures/TestUtilities/Workspaces/TestHostDocument.cs b/src/EditorFeatures/TestUtilities/Workspaces/TestHostDocument.cs index f3e814477842f..845b00eece6f5 100644 --- a/src/EditorFeatures/TestUtilities/Workspaces/TestHostDocument.cs +++ b/src/EditorFeatures/TestUtilities/Workspaces/TestHostDocument.cs @@ -135,14 +135,15 @@ internal TestHostDocument( } } - public TestHostDocument( + internal TestHostDocument( string text = "", string displayName = "", SourceCodeKind sourceCodeKind = SourceCodeKind.Regular, DocumentId? id = null, string? filePath = null, IReadOnlyList? folders = null, - ExportProvider? exportProvider = null) + ExportProvider? exportProvider = null, + IDocumentServiceProvider? documentServiceProvider = null) { _exportProvider = exportProvider; _id = id; @@ -153,6 +154,7 @@ public TestHostDocument( FilePath = filePath; _folders = folders; _roles = s_defaultRoles; + _documentServiceProvider = documentServiceProvider; } internal void SetProject(TestHostProject project) diff --git a/src/EditorFeatures/TestUtilities/Workspaces/TestWorkspace.cs b/src/EditorFeatures/TestUtilities/Workspaces/TestWorkspace.cs index 88994577e4e7b..97af0a07193d3 100644 --- a/src/EditorFeatures/TestUtilities/Workspaces/TestWorkspace.cs +++ b/src/EditorFeatures/TestUtilities/Workspaces/TestWorkspace.cs @@ -9,6 +9,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Formatting; @@ -208,6 +209,9 @@ public void AddTestProject(TestHostProject project) public new void OnParseOptionsChanged(ProjectId projectId, ParseOptions parseOptions) => base.OnParseOptionsChanged(projectId, parseOptions); + public new void OnAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference) + => base.OnAnalyzerReferenceAdded(projectId, analyzerReference); + public void OnDocumentRemoved(DocumentId documentId, bool closeDocument = false) { if (closeDocument && this.IsDocumentOpen(documentId)) @@ -305,7 +309,8 @@ protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text) var hostProject = this.GetTestProject(info.Id.ProjectId); var hostDocument = new TestHostDocument( text.ToString(), info.Name, info.SourceCodeKind, - info.Id, folders: info.Folders, exportProvider: ExportProvider); + info.Id, info.FilePath, info.Folders, ExportProvider, + info.DocumentServiceProvider); hostProject.AddDocument(hostDocument); this.OnDocumentAdded(hostDocument.ToDocumentInfo()); } @@ -701,12 +706,12 @@ public void ChangeSolution(Solution solution) public override bool CanApplyParseOptionChange(ParseOptions oldOptions, ParseOptions newOptions, Project project) => true; - internal override async Task CanAddProjectReferenceAsync(ProjectId referencingProject, ProjectId referencedProject, CancellationToken cancellationToken) + internal override bool CanAddProjectReference(ProjectId referencingProject, ProjectId referencedProject) { - // VisualStudioWorkspace switches to the main thread for this call, so do the same thing here to catch tests + // VisualStudioWorkspace asserts the main thread for this call, so do the same thing here to catch tests // that fail to account for this possibility. var threadingContext = ExportProvider.GetExportedValue(); - await threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken); + Contract.ThrowIfFalse(threadingContext.HasMainThread && threadingContext.JoinableTaskContext.IsOnMainThread); return true; } diff --git a/src/EditorFeatures/Text/xlf/TextEditorResources.cs.xlf b/src/EditorFeatures/Text/xlf/TextEditorResources.cs.xlf index 06dff5eac806e..ceabb7b796609 100644 --- a/src/EditorFeatures/Text/xlf/TextEditorResources.cs.xlf +++ b/src/EditorFeatures/Text/xlf/TextEditorResources.cs.xlf @@ -4,12 +4,12 @@ The snapshot does not contain the specified position. - The snapshot does not contain the specified position. + Snímek neobsahuje zadanou pozici. The snapshot does not contain the specified span. - The snapshot does not contain the specified span. + Snímek neobsahuje zadaný rozsah. diff --git a/src/EditorFeatures/Text/xlf/TextEditorResources.de.xlf b/src/EditorFeatures/Text/xlf/TextEditorResources.de.xlf index 1bc488bf1a1cb..aa92751bd4408 100644 --- a/src/EditorFeatures/Text/xlf/TextEditorResources.de.xlf +++ b/src/EditorFeatures/Text/xlf/TextEditorResources.de.xlf @@ -4,12 +4,12 @@ The snapshot does not contain the specified position. - The snapshot does not contain the specified position. + Die Momentaufnahme weist nicht die angegebene Position auf. The snapshot does not contain the specified span. - The snapshot does not contain the specified span. + Die Momentaufnahme weist nicht die angegebene Spanne auf. diff --git a/src/EditorFeatures/Text/xlf/TextEditorResources.es.xlf b/src/EditorFeatures/Text/xlf/TextEditorResources.es.xlf index f5ff3e046ee62..d1428264288f4 100644 --- a/src/EditorFeatures/Text/xlf/TextEditorResources.es.xlf +++ b/src/EditorFeatures/Text/xlf/TextEditorResources.es.xlf @@ -4,12 +4,12 @@ The snapshot does not contain the specified position. - The snapshot does not contain the specified position. + La instantánea no contiene la posición especificada. The snapshot does not contain the specified span. - The snapshot does not contain the specified span. + La instantánea no contiene el intervalo especificado. diff --git a/src/EditorFeatures/Text/xlf/TextEditorResources.fr.xlf b/src/EditorFeatures/Text/xlf/TextEditorResources.fr.xlf index f7c98f662bc06..7941667c61955 100644 --- a/src/EditorFeatures/Text/xlf/TextEditorResources.fr.xlf +++ b/src/EditorFeatures/Text/xlf/TextEditorResources.fr.xlf @@ -4,12 +4,12 @@ The snapshot does not contain the specified position. - The snapshot does not contain the specified position. + La capture instantanée ne contient pas la position spécifiée. The snapshot does not contain the specified span. - The snapshot does not contain the specified span. + La capture instantanée ne contient pas l'étendue spécifiée. diff --git a/src/EditorFeatures/Text/xlf/TextEditorResources.it.xlf b/src/EditorFeatures/Text/xlf/TextEditorResources.it.xlf index 7296e9e73672f..6f3363f474e5c 100644 --- a/src/EditorFeatures/Text/xlf/TextEditorResources.it.xlf +++ b/src/EditorFeatures/Text/xlf/TextEditorResources.it.xlf @@ -4,12 +4,12 @@ The snapshot does not contain the specified position. - The snapshot does not contain the specified position. + Lo snapshot non contiene la posizione specificata. The snapshot does not contain the specified span. - The snapshot does not contain the specified span. + Lo snapshot non contiene la selezione specificata. diff --git a/src/EditorFeatures/Text/xlf/TextEditorResources.ja.xlf b/src/EditorFeatures/Text/xlf/TextEditorResources.ja.xlf index 3e352677621b6..46ed4ea9ced73 100644 --- a/src/EditorFeatures/Text/xlf/TextEditorResources.ja.xlf +++ b/src/EditorFeatures/Text/xlf/TextEditorResources.ja.xlf @@ -4,12 +4,12 @@ The snapshot does not contain the specified position. - The snapshot does not contain the specified position. + 指定された位置がスナップショットに含まれていません。 The snapshot does not contain the specified span. - The snapshot does not contain the specified span. + 指定された範囲がスナップショットに含まれていません。 diff --git a/src/EditorFeatures/Text/xlf/TextEditorResources.ko.xlf b/src/EditorFeatures/Text/xlf/TextEditorResources.ko.xlf index ab803973e21d9..35b8dfabd3cda 100644 --- a/src/EditorFeatures/Text/xlf/TextEditorResources.ko.xlf +++ b/src/EditorFeatures/Text/xlf/TextEditorResources.ko.xlf @@ -4,12 +4,12 @@ The snapshot does not contain the specified position. - The snapshot does not contain the specified position. + 스냅샷에 지정된 위치가 없습니다. The snapshot does not contain the specified span. - The snapshot does not contain the specified span. + 스냅샷에 지정된 범위가 없습니다. diff --git a/src/EditorFeatures/Text/xlf/TextEditorResources.pl.xlf b/src/EditorFeatures/Text/xlf/TextEditorResources.pl.xlf index 687d8c7cddfe9..aa2a5d840d5fb 100644 --- a/src/EditorFeatures/Text/xlf/TextEditorResources.pl.xlf +++ b/src/EditorFeatures/Text/xlf/TextEditorResources.pl.xlf @@ -4,12 +4,12 @@ The snapshot does not contain the specified position. - The snapshot does not contain the specified position. + Migawka nie zawiera określonej pozycji. The snapshot does not contain the specified span. - The snapshot does not contain the specified span. + Migawka nie zawiera podanego okresu. diff --git a/src/EditorFeatures/Text/xlf/TextEditorResources.pt-BR.xlf b/src/EditorFeatures/Text/xlf/TextEditorResources.pt-BR.xlf index 560ec4426b0d7..2abe84d684d37 100644 --- a/src/EditorFeatures/Text/xlf/TextEditorResources.pt-BR.xlf +++ b/src/EditorFeatures/Text/xlf/TextEditorResources.pt-BR.xlf @@ -4,12 +4,12 @@ The snapshot does not contain the specified position. - The snapshot does not contain the specified position. + O instantâneo não contém a posição especificada. The snapshot does not contain the specified span. - The snapshot does not contain the specified span. + O instantâneo não contém o intervalo especificado. diff --git a/src/EditorFeatures/Text/xlf/TextEditorResources.ru.xlf b/src/EditorFeatures/Text/xlf/TextEditorResources.ru.xlf index c2dde4ec7f93a..e8caa57d6b103 100644 --- a/src/EditorFeatures/Text/xlf/TextEditorResources.ru.xlf +++ b/src/EditorFeatures/Text/xlf/TextEditorResources.ru.xlf @@ -4,12 +4,12 @@ The snapshot does not contain the specified position. - The snapshot does not contain the specified position. + Моментальный снимок не содержит указанную позицию. The snapshot does not contain the specified span. - The snapshot does not contain the specified span. + Моментальный снимок не содержит указанный диапазон. diff --git a/src/EditorFeatures/Text/xlf/TextEditorResources.tr.xlf b/src/EditorFeatures/Text/xlf/TextEditorResources.tr.xlf index ab1affc0b97e1..4262d4dff5bb9 100644 --- a/src/EditorFeatures/Text/xlf/TextEditorResources.tr.xlf +++ b/src/EditorFeatures/Text/xlf/TextEditorResources.tr.xlf @@ -4,12 +4,12 @@ The snapshot does not contain the specified position. - The snapshot does not contain the specified position. + Anlık görüntü belirtilen konumu içermiyor. The snapshot does not contain the specified span. - The snapshot does not contain the specified span. + Anlık görüntü belirtilen kapsamı içermiyor. diff --git a/src/EditorFeatures/Text/xlf/TextEditorResources.zh-Hans.xlf b/src/EditorFeatures/Text/xlf/TextEditorResources.zh-Hans.xlf index da8f5cb2f6ea1..9cb92cef2bab9 100644 --- a/src/EditorFeatures/Text/xlf/TextEditorResources.zh-Hans.xlf +++ b/src/EditorFeatures/Text/xlf/TextEditorResources.zh-Hans.xlf @@ -1,15 +1,15 @@  - + The snapshot does not contain the specified position. - The snapshot does not contain the specified position. + 快照不包含指定的位置。 The snapshot does not contain the specified span. - The snapshot does not contain the specified span. + 快照不包含指定的范围。 diff --git a/src/EditorFeatures/Text/xlf/TextEditorResources.zh-Hant.xlf b/src/EditorFeatures/Text/xlf/TextEditorResources.zh-Hant.xlf index 2fc9d0a7a4376..3abe3a6dbb474 100644 --- a/src/EditorFeatures/Text/xlf/TextEditorResources.zh-Hant.xlf +++ b/src/EditorFeatures/Text/xlf/TextEditorResources.zh-Hant.xlf @@ -1,15 +1,15 @@  - + The snapshot does not contain the specified position. - The snapshot does not contain the specified position. + 此快照集未包含指定的位置。 The snapshot does not contain the specified span. - The snapshot does not contain the specified span. + 此快照集未包含指定的範圍。 diff --git a/src/EditorFeatures/VisualBasic/AddImports/VisualBasicAddImportsOnPasteCommandHandler.vb b/src/EditorFeatures/VisualBasic/AddImports/VisualBasicAddImportsOnPasteCommandHandler.vb new file mode 100644 index 0000000000000..f91ff03e5ac2e --- /dev/null +++ b/src/EditorFeatures/VisualBasic/AddImports/VisualBasicAddImportsOnPasteCommandHandler.vb @@ -0,0 +1,30 @@ +' Licensed to the .NET Foundation under one or more agreements. +' The .NET Foundation licenses this file to you under the MIT license. +' See the LICENSE file in the project root for more information. + +Imports System.ComponentModel.Composition +Imports Microsoft.CodeAnalysis.Editor.Implementation.AddImports +Imports Microsoft.CodeAnalysis.Host.Mef +Imports Microsoft.VisualStudio.Commanding +Imports Microsoft.VisualStudio.Utilities + +Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.AddImports + + + + + + + Friend Class VisualBasicAddImportsOnPasteCommandHandler + Inherits AbstractAddImportsPasteCommandHandler + + + + Public Sub New(threadingContext As [Shared].Utilities.IThreadingContext) + MyBase.New(threadingContext) + End Sub + + Public Overrides ReadOnly Property DisplayName As String = VBEditorResources.Add_Missing_Imports_on_Paste + Protected Overrides ReadOnly Property DialogText As String = VBEditorResources.Adding_missing_imports + End Class +End Namespace diff --git a/src/EditorFeatures/VisualBasic/VBEditorResources.resx b/src/EditorFeatures/VisualBasic/VBEditorResources.resx index 4766b13d19381..d070f1034ddcd 100644 --- a/src/EditorFeatures/VisualBasic/VBEditorResources.resx +++ b/src/EditorFeatures/VisualBasic/VBEditorResources.resx @@ -180,4 +180,12 @@ Implement Abstract Class Or Interface + + Adding missing imports... + Thread awaited dialog text. "imports" is a language specific term and should not be localized + + + Add Missing Imports on Paste + "imports" is a language specific term and should not be localized + \ No newline at end of file diff --git a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.cs.xlf b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.cs.xlf index 2e08f73da70b4..891a32e7522f6 100644 --- a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.cs.xlf +++ b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.cs.xlf @@ -2,6 +2,16 @@ + + Add Missing Imports on Paste + Add Missing Imports on Paste + "imports" is a language specific term and should not be localized + + + Adding missing imports... + Adding missing imports... + Thread awaited dialog text. "imports" is a language specific term and should not be localized + Case Correction Oprava velkých a malých písmen diff --git a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.de.xlf b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.de.xlf index d2e659d669adc..53fc9740fbff1 100644 --- a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.de.xlf +++ b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.de.xlf @@ -2,6 +2,16 @@ + + Add Missing Imports on Paste + Add Missing Imports on Paste + "imports" is a language specific term and should not be localized + + + Adding missing imports... + Adding missing imports... + Thread awaited dialog text. "imports" is a language specific term and should not be localized + Case Correction Fallkorrektur diff --git a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.es.xlf b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.es.xlf index b1ab42332f662..011334fe4dfe8 100644 --- a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.es.xlf +++ b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.es.xlf @@ -2,6 +2,16 @@ + + Add Missing Imports on Paste + Add Missing Imports on Paste + "imports" is a language specific term and should not be localized + + + Adding missing imports... + Adding missing imports... + Thread awaited dialog text. "imports" is a language specific term and should not be localized + Case Correction Corrección de mayúsculas/minúsculas diff --git a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.fr.xlf b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.fr.xlf index 4d7797b20456b..5403247877f55 100644 --- a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.fr.xlf +++ b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.fr.xlf @@ -2,6 +2,16 @@ + + Add Missing Imports on Paste + Add Missing Imports on Paste + "imports" is a language specific term and should not be localized + + + Adding missing imports... + Adding missing imports... + Thread awaited dialog text. "imports" is a language specific term and should not be localized + Case Correction Correction de la casse diff --git a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.it.xlf b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.it.xlf index 9779988dee98d..cb1c191543066 100644 --- a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.it.xlf +++ b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.it.xlf @@ -2,6 +2,16 @@ + + Add Missing Imports on Paste + Add Missing Imports on Paste + "imports" is a language specific term and should not be localized + + + Adding missing imports... + Adding missing imports... + Thread awaited dialog text. "imports" is a language specific term and should not be localized + Case Correction Correzione maiuscole/minuscole diff --git a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.ja.xlf b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.ja.xlf index f4a6b466198ff..257a6076dfd7c 100644 --- a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.ja.xlf +++ b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.ja.xlf @@ -2,6 +2,16 @@ + + Add Missing Imports on Paste + Add Missing Imports on Paste + "imports" is a language specific term and should not be localized + + + Adding missing imports... + Adding missing imports... + Thread awaited dialog text. "imports" is a language specific term and should not be localized + Case Correction 大文字小文字の修正 diff --git a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.ko.xlf b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.ko.xlf index 5767314973387..ee600b947a85b 100644 --- a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.ko.xlf +++ b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.ko.xlf @@ -2,6 +2,16 @@ + + Add Missing Imports on Paste + Add Missing Imports on Paste + "imports" is a language specific term and should not be localized + + + Adding missing imports... + Adding missing imports... + Thread awaited dialog text. "imports" is a language specific term and should not be localized + Case Correction 대/소문자 수정 diff --git a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.pl.xlf b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.pl.xlf index e6538c52dd07d..f8a09ffe60edf 100644 --- a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.pl.xlf +++ b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.pl.xlf @@ -2,6 +2,16 @@ + + Add Missing Imports on Paste + Add Missing Imports on Paste + "imports" is a language specific term and should not be localized + + + Adding missing imports... + Adding missing imports... + Thread awaited dialog text. "imports" is a language specific term and should not be localized + Case Correction Poprawianie wielkości liter diff --git a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.pt-BR.xlf b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.pt-BR.xlf index 66436ec9d2227..92a0c715cbe84 100644 --- a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.pt-BR.xlf +++ b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.pt-BR.xlf @@ -2,6 +2,16 @@ + + Add Missing Imports on Paste + Add Missing Imports on Paste + "imports" is a language specific term and should not be localized + + + Adding missing imports... + Adding missing imports... + Thread awaited dialog text. "imports" is a language specific term and should not be localized + Case Correction Correção de Caso diff --git a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.ru.xlf b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.ru.xlf index 715a1023d7647..fcd69d18eb8a8 100644 --- a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.ru.xlf +++ b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.ru.xlf @@ -2,6 +2,16 @@ + + Add Missing Imports on Paste + Add Missing Imports on Paste + "imports" is a language specific term and should not be localized + + + Adding missing imports... + Adding missing imports... + Thread awaited dialog text. "imports" is a language specific term and should not be localized + Case Correction Исправление регистра diff --git a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.tr.xlf b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.tr.xlf index 8846696c2ddc0..22a01a8934f7c 100644 --- a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.tr.xlf +++ b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.tr.xlf @@ -2,6 +2,16 @@ + + Add Missing Imports on Paste + Add Missing Imports on Paste + "imports" is a language specific term and should not be localized + + + Adding missing imports... + Adding missing imports... + Thread awaited dialog text. "imports" is a language specific term and should not be localized + Case Correction Büyük/Küçük Harf Düzeltmesi diff --git a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.zh-Hans.xlf b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.zh-Hans.xlf index c564baf28cdf4..7a78110e6b501 100644 --- a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.zh-Hans.xlf +++ b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.zh-Hans.xlf @@ -1,7 +1,17 @@  - + + + Add Missing Imports on Paste + Add Missing Imports on Paste + "imports" is a language specific term and should not be localized + + + Adding missing imports... + Adding missing imports... + Thread awaited dialog text. "imports" is a language specific term and should not be localized + Case Correction 大小写更正 diff --git a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.zh-Hant.xlf b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.zh-Hant.xlf index 756fee2b3d42a..b41d1f4fbf980 100644 --- a/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.zh-Hant.xlf +++ b/src/EditorFeatures/VisualBasic/xlf/VBEditorResources.zh-Hant.xlf @@ -1,7 +1,17 @@  - + + + Add Missing Imports on Paste + Add Missing Imports on Paste + "imports" is a language specific term and should not be localized + + + Adding missing imports... + Adding missing imports... + Thread awaited dialog text. "imports" is a language specific term and should not be localized + Case Correction 大小寫修正 diff --git a/src/EditorFeatures/VisualBasicTest/ReplaceDocCommentTextWithTag/ReplaceDocCommentTextWithTagTests.vb b/src/EditorFeatures/VisualBasicTest/ReplaceDocCommentTextWithTag/ReplaceDocCommentTextWithTagTests.vb index a645f650ac8e5..bf05a0244ad7b 100644 --- a/src/EditorFeatures/VisualBasicTest/ReplaceDocCommentTextWithTag/ReplaceDocCommentTextWithTagTests.vb +++ b/src/EditorFeatures/VisualBasicTest/ReplaceDocCommentTextWithTag/ReplaceDocCommentTextWithTagTests.vb @@ -349,6 +349,34 @@ end class") class C sub WriteLine(Of TKey)(value as TKey) end sub +end class") + End Function + + + + Public Async Function TestMyBase() As Task + Await TestInRegularAndScriptAsync( +" +''' Testing keyword [||]MyBase. +class C(Of TKey) +end class", +" +''' Testing keyword . +class C(Of TKey) +end class") + End Function + + + + Public Async Function TestMyClass() As Task + Await TestInRegularAndScriptAsync( +" +''' Testing keyword [||]MyClass. +class C(Of TKey) +end class", +" +''' Testing keyword . +class C(Of TKey) end class") End Function End Class diff --git a/src/EditorFeatures/XunitHook/Microsoft.CodeAnalysis.XunitHook.csproj b/src/EditorFeatures/XunitHook/Microsoft.CodeAnalysis.XunitHook.csproj new file mode 100644 index 0000000000000..228aed4379387 --- /dev/null +++ b/src/EditorFeatures/XunitHook/Microsoft.CodeAnalysis.XunitHook.csproj @@ -0,0 +1,14 @@ + + + + + Library + Microsoft.CodeAnalysis.Test.Utilities + net472 + true + false + + + + + \ No newline at end of file diff --git a/src/EditorFeatures/XunitHook/XunitDisposeHook.cs b/src/EditorFeatures/XunitHook/XunitDisposeHook.cs new file mode 100644 index 0000000000000..3710ec84ec5ae --- /dev/null +++ b/src/EditorFeatures/XunitHook/XunitDisposeHook.cs @@ -0,0 +1,57 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace Microsoft.CodeAnalysis.Test.Utilities +{ + internal sealed class XunitDisposeHook : MarshalByRefObject + { + [SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Invoked across app domains")] + public void Execute() + { + if (!AppDomain.CurrentDomain.IsDefaultAppDomain()) + throw new InvalidOperationException(); + + var xunitUtilities = AppDomain.CurrentDomain.GetAssemblies().Where(static assembly => assembly.GetName().Name.StartsWith("xunit.runner.utility")).ToArray(); + foreach (var xunitUtility in xunitUtilities) + { + var appDomainManagerType = xunitUtility.GetType("Xunit.AppDomainManager_AppDomain"); + if (appDomainManagerType is null) + continue; + + // AppDomainManager_AppDomain.Dispose() calls AppDomain.Unload(), which is unfortunately not reliable + // when the test creates STA COM objects. Since this call to Unload() only occurs at the end of testing + // (immediately before the process is going to close anyway), we can simply hot-patch the executable + // code in Dispose() to return without taking any action. + // + // This is a workaround for https://github.com/xunit/xunit/issues/2097. The fix in + // https://github.com/xunit/xunit/pull/2192 was not viable because xunit v2 is no longer shipping + // updates. Once xunit v3 is available, it will no longer be necessary. + var method = appDomainManagerType.GetMethod("Dispose"); + RuntimeHelpers.PrepareMethod(method.MethodHandle); + var functionPointer = method.MethodHandle.GetFunctionPointer(); + + switch (RuntimeInformation.ProcessArchitecture) + { + case Architecture.X86: + case Architecture.X64: + // 😱 Overwrite the compiled method to just return. + // Note that the same sequence works for x86 and x64. + + // ret + Marshal.WriteByte(functionPointer, 0xC3); + break; + + default: + throw new NotSupportedException(); + } + } + } + } +} diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EETypeParameterSymbol.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EETypeParameterSymbol.cs index 58472bcbff225..d6631399d085c 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EETypeParameterSymbol.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EETypeParameterSymbol.cs @@ -59,6 +59,14 @@ public override bool HasReferenceTypeConstraint get { return _sourceTypeParameter.HasReferenceTypeConstraint; } } + public override bool IsReferenceTypeFromConstraintTypes + { + get + { + return _sourceTypeParameter.IsReferenceTypeFromConstraintTypes || CalculateIsReferenceTypeFromConstraintTypes(ConstraintTypesNoUseSiteDiagnostics); + } + } + internal override bool? ReferenceTypeConstraintIsNullable { get { return _sourceTypeParameter.ReferenceTypeConstraintIsNullable; } @@ -87,6 +95,14 @@ public override bool HasValueTypeConstraint get { return _sourceTypeParameter.HasValueTypeConstraint; } } + public override bool IsValueTypeFromConstraintTypes + { + get + { + return _sourceTypeParameter.IsValueTypeFromConstraintTypes || CalculateIsValueTypeFromConstraintTypes(ConstraintTypesNoUseSiteDiagnostics); + } + } + public override bool HasUnmanagedTypeConstraint { get { return _sourceTypeParameter.HasUnmanagedTypeConstraint; } @@ -117,14 +133,14 @@ public override bool IsImplicitlyDeclared get { return true; } } - internal override void EnsureAllConstraintsAreResolved(bool canIgnoreNullableContext) + internal override void EnsureAllConstraintsAreResolved() { - _sourceTypeParameter.EnsureAllConstraintsAreResolved(canIgnoreNullableContext); + _sourceTypeParameter.EnsureAllConstraintsAreResolved(); } - internal override ImmutableArray GetConstraintTypes(ConsList inProgress, bool canIgnoreNullableContext) + internal override ImmutableArray GetConstraintTypes(ConsList inProgress) { - var constraintTypes = _sourceTypeParameter.GetConstraintTypes(inProgress, canIgnoreNullableContext); + var constraintTypes = _sourceTypeParameter.GetConstraintTypes(inProgress); if (constraintTypes.IsEmpty) { diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/SimpleTypeParameterSymbol.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/SimpleTypeParameterSymbol.cs index 5c960315bbe01..de45ef9551757 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/SimpleTypeParameterSymbol.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/SimpleTypeParameterSymbol.cs @@ -52,6 +52,11 @@ public override bool HasReferenceTypeConstraint get { return false; } } + public override bool IsReferenceTypeFromConstraintTypes + { + get { return false; } + } + internal override bool? ReferenceTypeConstraintIsNullable { get { return false; } @@ -66,6 +71,11 @@ public override bool HasValueTypeConstraint get { return false; } } + public override bool IsValueTypeFromConstraintTypes + { + get { return false; } + } + public override bool HasUnmanagedTypeConstraint { get { return false; } @@ -91,11 +101,11 @@ public override ImmutableArray DeclaringSyntaxReferences get { throw ExceptionUtilities.Unreachable; } } - internal override void EnsureAllConstraintsAreResolved(bool canIgnoreNullableContext) + internal override void EnsureAllConstraintsAreResolved() { } - internal override ImmutableArray GetConstraintTypes(ConsList inProgress, bool canIgnoreNullableContext) + internal override ImmutableArray GetConstraintTypes(ConsList inProgress) { return ImmutableArray.Empty; } diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTests.cs index 9b3110030f677..b69b7d2d0c36b 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTests.cs @@ -4816,14 +4816,12 @@ static void Main() string error; var testData = new CompilationTestData(); var result = context.CompileExpression("F()", out error, testData); - // Currently, the name of the evaluation method is used for - // [CallerMemberName] so "F()" will generate "[] [<>m0] [1]". testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 17 (0x11) .maxstack 3 IL_0000: ldstr """" - IL_0005: ldstr ""<>m0"" + IL_0005: ldstr ""Main"" IL_000a: ldc.i4.1 IL_000b: call ""object C.F(string, string, int)"" IL_0010: ret diff --git a/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.cs.xlf b/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.cs.xlf index f48e296b9cb47..6740096267e16 100644 --- a/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.cs.xlf +++ b/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.cs.xlf @@ -24,7 +24,7 @@ '{0}' threw an exception of type '{1}' - '{0} – došlo k výjimce typu {1}. + {0} – došlo k výjimce typu {1}. Threw an exception while evaluating a value. diff --git a/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.ja.xlf b/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.ja.xlf index 1772ae2d0eb5a..2965633285edb 100644 --- a/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.ja.xlf +++ b/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.ja.xlf @@ -34,7 +34,7 @@ Cannot dereference '{0}'. The pointer is not valid. - {0}' を逆参照できません。ポインターが無効です。 + '{0}' を逆参照できません。ポインターが無効です。 Invalid pointer dereference @@ -69,12 +69,12 @@ Only Enumerable types can have Results View - 結果ビューを含むことができるのは、列挙可能な型だけです。 + 結果ビューを含むことができるのは、列挙可能な型だけです Cannot use "results" format specifier on non-enumerable type Expanding the Results View will enumerate the IEnumerable - 結果ビューを展開すると、IEnumerable が列挙されます。 + 結果ビューを展開すると、IEnumerable が列挙されます Warning reported in Results View value diff --git a/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.ko.xlf b/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.ko.xlf index 6ff6dd0680df3..44f1a7a0a4fbd 100644 --- a/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.ko.xlf +++ b/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.ko.xlf @@ -34,7 +34,7 @@ Cannot dereference '{0}'. The pointer is not valid. - {0}'을(를) 역참조할 수 없습니다. 포인터가 잘못되었습니다. + '{0}'을(를) 역참조할 수 없습니다. 포인터가 잘못되었습니다. Invalid pointer dereference diff --git a/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.pl.xlf b/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.pl.xlf index 80da095ceb940..c71476d322715 100644 --- a/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.pl.xlf +++ b/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.pl.xlf @@ -24,7 +24,7 @@ '{0}' threw an exception of type '{1}' - '„{0}”: zwrócono wyjątek typu „{1}” + „{0}”: zwrócono wyjątek typu „{1}” Threw an exception while evaluating a value. diff --git a/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.ru.xlf b/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.ru.xlf index da25beae7f518..a6e473c8033bc 100644 --- a/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.ru.xlf +++ b/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.ru.xlf @@ -24,7 +24,7 @@ '{0}' threw an exception of type '{1}' - '"{0}" выдал исключение типа "{1}" + "{0}" выдал исключение типа "{1}" Threw an exception while evaluating a value. diff --git a/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.tr.xlf b/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.tr.xlf index 14cfaf141c5f5..d65b7d47ed3ac 100644 --- a/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.tr.xlf +++ b/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.tr.xlf @@ -34,7 +34,7 @@ Cannot dereference '{0}'. The pointer is not valid. - {0}' başvurusu çözülemiyor. İşaretçi geçerli değil. + '{0}' başvurusu çözülemiyor. İşaretçi geçerli değil. Invalid pointer dereference diff --git a/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.zh-Hans.xlf b/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.zh-Hans.xlf index 0fb10b6c2a1ab..ce9be8bb8eeff 100644 --- a/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.zh-Hans.xlf +++ b/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Dynamic View @@ -24,7 +24,7 @@ '{0}' threw an exception of type '{1}' - '“{0}”引发了类型“{1}”的异常 + “{0}”引发了类型“{1}”的异常 Threw an exception while evaluating a value. diff --git a/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.zh-Hant.xlf b/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.zh-Hant.xlf index 0f95ebcbae4d8..77528dbe77c28 100644 --- a/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.zh-Hant.xlf +++ b/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Dynamic View diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/xlf/Resources.ja.xlf b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/xlf/Resources.ja.xlf index cbc0eb766dde5..f123c7b5c3545 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/xlf/Resources.ja.xlf +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/xlf/Resources.ja.xlf @@ -4,7 +4,7 @@ Statements of type '{0}' are not allowed in the Immediate window. - {0}' 型のステートメントはイミディエイト ウィンドウでは使用できません。 + '{0}' 型のステートメントはイミディエイト ウィンドウでは使用できません。 diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/xlf/Resources.ko.xlf b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/xlf/Resources.ko.xlf index f51a5a9263951..e123eabd8993e 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/xlf/Resources.ko.xlf +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/xlf/Resources.ko.xlf @@ -4,7 +4,7 @@ Statements of type '{0}' are not allowed in the Immediate window. - {0}' 형식의 문은 직접 실행 창에서 허용되지 않습니다. + '{0}' 형식의 문은 직접 실행 창에서 허용되지 않습니다. diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/xlf/Resources.tr.xlf b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/xlf/Resources.tr.xlf index 7c5702e5cb8a6..fedd2c2b882c1 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/xlf/Resources.tr.xlf +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/xlf/Resources.tr.xlf @@ -4,7 +4,7 @@ Statements of type '{0}' are not allowed in the Immediate window. - {0}' türündeki deyimler Yürütme penceresinde kullanılamaz. + '{0}' türündeki deyimler Yürütme penceresinde kullanılamaz. diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/xlf/Resources.zh-Hans.xlf b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/xlf/Resources.zh-Hans.xlf index 2d5f60e5273d8..5559259236d67 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/xlf/Resources.zh-Hans.xlf +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/xlf/Resources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Statements of type '{0}' are not allowed in the Immediate window. diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/xlf/Resources.zh-Hant.xlf b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/xlf/Resources.zh-Hant.xlf index 30b00dd54b8ec..4fc5d97278e7c 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/xlf/Resources.zh-Hant.xlf +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/xlf/Resources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Statements of type '{0}' are not allowed in the Immediate window. diff --git a/src/Features/CSharp/Portable/CodeRefactorings/ConvertLocalFunctionToMethod/CSharpConvertLocalFunctionToMethodCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/CodeRefactorings/ConvertLocalFunctionToMethod/CSharpConvertLocalFunctionToMethodCodeRefactoringProvider.cs index dad44de950eed..56a2b494bbedf 100644 --- a/src/Features/CSharp/Portable/CodeRefactorings/ConvertLocalFunctionToMethod/CSharpConvertLocalFunctionToMethodCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/CodeRefactorings/ConvertLocalFunctionToMethod/CSharpConvertLocalFunctionToMethodCodeRefactoringProvider.cs @@ -107,13 +107,18 @@ private static async Task UpdateDocumentAsync( var containerSymbol = semanticModel.GetDeclaredSymbol(container, cancellationToken); var isStatic = containerSymbol.IsStatic || captures.All(capture => !capture.IsThisParameter()); + // GetSymbolModifiers actually checks if the local function needs to be unsafe, not whether + // it is declared as such, so this check we don't need to worry about whether the containing method + // is unsafe, this will just work regardless. + var needsUnsafe = declaredSymbol.GetSymbolModifiers().IsUnsafe; + var methodName = GenerateUniqueMethodName(declaredSymbol); var parameters = declaredSymbol.Parameters; var methodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol( containingType: declaredSymbol.ContainingType, attributes: default, accessibility: Accessibility.Private, - modifiers: new DeclarationModifiers(isStatic, isAsync: declaredSymbol.IsAsync), + modifiers: new DeclarationModifiers(isStatic, isAsync: declaredSymbol.IsAsync, isUnsafe: needsUnsafe), returnType: declaredSymbol.ReturnType, refKind: default, explicitInterfaceImplementations: default, diff --git a/src/Features/CSharp/Portable/Completion/CompletionProviders/ImportCompletion/ExtensionMethodImportCompletionProvider.cs b/src/Features/CSharp/Portable/Completion/CompletionProviders/ImportCompletion/ExtensionMethodImportCompletionProvider.cs index 9e58038357570..a2e11b6cbd2dc 100644 --- a/src/Features/CSharp/Portable/Completion/CompletionProviders/ImportCompletion/ExtensionMethodImportCompletionProvider.cs +++ b/src/Features/CSharp/Portable/Completion/CompletionProviders/ImportCompletion/ExtensionMethodImportCompletionProvider.cs @@ -5,13 +5,16 @@ using System; using System.Collections.Immutable; using System.Composition; +using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; +using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Text; @@ -56,5 +59,18 @@ protected override bool IsFinalSemicolonOfUsingOrExtern(SyntaxNode directive, Sy _ => false, }; } + + protected override Task ShouldProvideParenthesisCompletionAsync( + Document document, + CompletionItem item, + char? commitKey, + CancellationToken cancellationToken) + // Ideally we should check if the inferred type for this location is delegate to decide whether to add parenthesis or not + // However, for an extension method like + // static class C { public static int ToInt(this Bar b) => 1; } + // it can only be used as like: bar.ToInt(); + // Func x = bar.ToInt or Func x = bar.ToInt is illegal. It can't be assign to delegate. + // Therefore at here we always assume the user always wants to add parenthesis. + => Task.FromResult(commitKey == ';'); } } diff --git a/src/Features/CSharp/Portable/Completion/CompletionProviders/ImportCompletion/TypeImportCompletionProvider.cs b/src/Features/CSharp/Portable/Completion/CompletionProviders/ImportCompletion/TypeImportCompletionProvider.cs index 6e85edd4c9428..d9da9c996ac79 100644 --- a/src/Features/CSharp/Portable/Completion/CompletionProviders/ImportCompletion/TypeImportCompletionProvider.cs +++ b/src/Features/CSharp/Portable/Completion/CompletionProviders/ImportCompletion/TypeImportCompletionProvider.cs @@ -9,9 +9,11 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; +using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; +using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Text; @@ -54,5 +56,23 @@ protected override bool IsFinalSemicolonOfUsingOrExtern(SyntaxNode directive, Sy _ => false, }; } + + protected override async Task ShouldProvideParenthesisCompletionAsync( + Document document, + CompletionItem item, + char? commitKey, + CancellationToken cancellationToken) + { + if (commitKey == ';') + { + // Only consider add '()' if the type is used under object creation context + var position = item.Span.Start; + var syntaxTree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); + var leftToken = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); + return syntaxTree.IsObjectCreationTypeContext(position, leftToken, cancellationToken); + } + + return false; + } } } diff --git a/src/Features/CSharp/Portable/Completion/CompletionProviders/ObjectCreationCompletionProvider.cs b/src/Features/CSharp/Portable/Completion/CompletionProviders/ObjectCreationCompletionProvider.cs index 91e9373df5127..c31e234f8947b 100644 --- a/src/Features/CSharp/Portable/Completion/CompletionProviders/ObjectCreationCompletionProvider.cs +++ b/src/Features/CSharp/Portable/Completion/CompletionProviders/ObjectCreationCompletionProvider.cs @@ -12,6 +12,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; +using Microsoft.CodeAnalysis.Completion.Log; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; @@ -116,13 +117,13 @@ protected override (string displayText, string suffix, string insertionText) Get private static readonly CompletionItemRules s_objectRules = CompletionItemRules.Create( - commitCharacterRules: ImmutableArray.Create(CharacterSetModificationRule.Create(CharacterSetModificationKind.Replace, ' ', '(', '[')), + commitCharacterRules: ImmutableArray.Create(CharacterSetModificationRule.Create(CharacterSetModificationKind.Replace, ' ', '(', '[', ';')), matchPriority: MatchPriority.Preselect, selectionBehavior: CompletionItemSelectionBehavior.HardSelection); private static readonly CompletionItemRules s_defaultRules = CompletionItemRules.Create( - commitCharacterRules: ImmutableArray.Create(CharacterSetModificationRule.Create(CharacterSetModificationKind.Replace, ' ', '(', '[', '{')), + commitCharacterRules: ImmutableArray.Create(CharacterSetModificationRule.Create(CharacterSetModificationKind.Replace, ' ', '(', '[', '{', ';')), matchPriority: MatchPriority.Preselect, selectionBehavior: CompletionItemSelectionBehavior.HardSelection); @@ -145,5 +146,17 @@ protected override CompletionItemRules GetCompletionItemRules(IReadOnlyList CompletionItemSelectionBehavior.HardSelection; + + protected override CompletionItem CreateItem( + CompletionContext completionContext, + string displayText, + string displayTextSuffix, + string insertionText, + List symbols, + SyntaxContext context, + bool preselect, + SupportedPlatformData supportedPlatformData) + { + var item = base.CreateItem( + completionContext, + displayText, + displayTextSuffix, + insertionText, + symbols, + context, + preselect, + supportedPlatformData); + + var symbol = symbols[0]; + if (symbol.IsKind(SymbolKind.Method)) + { + var isInferredTypeDelegate = context.InferredTypes.Any(type => type.IsDelegateType()); + if (!isInferredTypeDelegate) + { + item = SymbolCompletionItem.AddShouldProvideParenthesisCompletion(item); + } + } + else if (symbol.IsKind(SymbolKind.NamedType) || symbol is IAliasSymbol aliasSymbol && aliasSymbol.Target.IsType) + { + var isObjectCreationTypeContext = context switch + { + CSharpSyntaxContext csharpSyntaxContext => csharpSyntaxContext.IsObjectCreationTypeContext, + _ => false + }; + + if (isObjectCreationTypeContext) + { + item = SymbolCompletionItem.AddShouldProvideParenthesisCompletion(item); + } + } + + return item; + } + + protected override string GetInsertionText(CompletionItem item, char ch) + { + if (ch == ';' && SymbolCompletionItem.GetShouldProvideParenthesisCompletion(item)) + { + CompletionProvidersLogger.LogCommitUsingSemicolonToAddParenthesis(); + var insertionText = SymbolCompletionItem.GetInsertionText(item); + return insertionText + "()"; + } + + return base.GetInsertionText(item, ch); + } } } diff --git a/src/Features/CSharp/Portable/QuickInfo/CSharpDiagnosticAnalyzerQuickInfoProvider.cs b/src/Features/CSharp/Portable/QuickInfo/CSharpDiagnosticAnalyzerQuickInfoProvider.cs index 0be6cce463a8b..65d6a8e562414 100644 --- a/src/Features/CSharp/Portable/QuickInfo/CSharpDiagnosticAnalyzerQuickInfoProvider.cs +++ b/src/Features/CSharp/Portable/QuickInfo/CSharpDiagnosticAnalyzerQuickInfoProvider.cs @@ -47,23 +47,41 @@ public CSharpDiagnosticAnalyzerQuickInfoProvider(IDiagnosticAnalyzerService diag private QuickInfoItem? GetQuickinfoForPragmaWarning(Document document, SyntaxToken token) { - var errorCode = token.Parent switch + var errorCodeNode = token.Parent switch { PragmaWarningDirectiveTriviaSyntax directive => token.IsKind(SyntaxKind.EndOfDirectiveToken) - ? directive.ErrorCodes.LastOrDefault() as IdentifierNameSyntax - : directive.ErrorCodes.FirstOrDefault() as IdentifierNameSyntax, - IdentifierNameSyntax { Parent: PragmaWarningDirectiveTriviaSyntax _ } identifier - => identifier, + ? directive.ErrorCodes.LastOrDefault() + : directive.ErrorCodes.FirstOrDefault(), + { Parent: PragmaWarningDirectiveTriviaSyntax } node => node, _ => null, }; + if (errorCodeNode is null) + { + return null; + } - if (errorCode != null) + // https://docs.microsoft.com/en-US/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-pragma-warning + // warning-list: A comma-separated list of warning numbers. The "CS" prefix is optional. + // errorCodeNode is single error code from the comma separated list + var errorCode = errorCodeNode switch + { + // case CS0219 or SA0012: + IdentifierNameSyntax identifierName => identifierName.Identifier.ValueText, + // case 0219 or 219: + // Take the number and add the "CS" prefix. + LiteralExpressionSyntax { RawKind: (int)SyntaxKind.NumericLiteralExpression } literal + => int.TryParse(literal.Token.ValueText, out var errorCodeNumber) + ? $"CS{errorCodeNumber:0000}" + : literal.Token.ValueText, + _ => null, + }; + if (errorCode is null) { - return GetQuickInfoFromSupportedDiagnosticsOfProjectAnalyzers(document, errorCode.Identifier.ValueText, errorCode.Span); + return null; } - return null; + return GetQuickInfoFromSupportedDiagnosticsOfProjectAnalyzers(document, errorCode, errorCodeNode.Span); } private async Task GetQuickInfoForSuppressMessageAttributeAsync( @@ -83,8 +101,8 @@ PragmaWarningDirectiveTriviaSyntax directive Parent: AttributeSyntax { Name: var attributeName - } _ - } _ + } + } } argument when attributeName.IsSuppressMessageAttribute() && (argument.NameColon is null diff --git a/src/Features/CSharp/Portable/ReplaceDocCommentTextWithTag/CSharpReplaceDocCommentTextWithTagCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/ReplaceDocCommentTextWithTag/CSharpReplaceDocCommentTextWithTagCodeRefactoringProvider.cs index 83f84f6d88731..0f59bcac0323b 100644 --- a/src/Features/CSharp/Portable/ReplaceDocCommentTextWithTag/CSharpReplaceDocCommentTextWithTagCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/ReplaceDocCommentTextWithTag/CSharpReplaceDocCommentTextWithTagCodeRefactoringProvider.cs @@ -26,7 +26,9 @@ internal class CSharpReplaceDocCommentTextWithTagCodeRefactoringProvider : SyntaxFacts.GetText(SyntaxKind.AbstractKeyword), SyntaxFacts.GetText(SyntaxKind.SealedKeyword), SyntaxFacts.GetText(SyntaxKind.AsyncKeyword), - SyntaxFacts.GetText(SyntaxKind.AwaitKeyword)); + SyntaxFacts.GetText(SyntaxKind.AwaitKeyword), + SyntaxFacts.GetText(SyntaxKind.BaseKeyword), + SyntaxFacts.GetText(SyntaxKind.ThisKeyword)); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] diff --git a/src/Features/CSharp/Portable/Structure/CSharpStructureHelpers.cs b/src/Features/CSharp/Portable/Structure/CSharpStructureHelpers.cs index a10654436ae5f..ffcdd201e6eb6 100644 --- a/src/Features/CSharp/Portable/Structure/CSharpStructureHelpers.cs +++ b/src/Features/CSharp/Portable/Structure/CSharpStructureHelpers.cs @@ -244,14 +244,14 @@ void completeSingleLineCommentGroup() public static void CollectCommentBlockSpans( SyntaxNode node, ArrayBuilder spans, - bool isMetadataAsSource) + BlockStructureOptionProvider optionProvider) { if (node == null) { throw new ArgumentNullException(nameof(node)); } - if (isMetadataAsSource && TryGetLeadingCollapsibleSpan(node, out var span)) + if (optionProvider.IsMetadataAsSource && TryGetLeadingCollapsibleSpan(node, out var span)) { spans.Add(span); } diff --git a/src/Features/CSharp/Portable/Structure/Providers/AccessorDeclarationStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/AccessorDeclarationStructureProvider.cs index b098ea3d0094c..43ced7a1ad6da 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/AccessorDeclarationStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/AccessorDeclarationStructureProvider.cs @@ -6,7 +6,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; @@ -17,11 +16,10 @@ internal class AccessorDeclarationStructureProvider : AbstractSyntaxNodeStructur protected override void CollectBlockSpans( AccessorDeclarationSyntax accessorDeclaration, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { - CSharpStructureHelpers.CollectCommentBlockSpans(accessorDeclaration, spans, isMetadataAsSource); + CSharpStructureHelpers.CollectCommentBlockSpans(accessorDeclaration, spans, optionProvider); // fault tolerance if (accessorDeclaration.Body == null || @@ -37,7 +35,7 @@ protected override void CollectBlockSpans( // Check IsNode to compress blank lines after this node if it is the last child of the parent. // // All accessor kinds are grouped together in Metadata as Source. - var compressEmptyLines = isMetadataAsSource + var compressEmptyLines = optionProvider.IsMetadataAsSource && (!nextSibling.IsNode || nextSibling.AsNode() is AccessorDeclarationSyntax); spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( diff --git a/src/Features/CSharp/Portable/Structure/Providers/AnonymousMethodExpressionStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/AnonymousMethodExpressionStructureProvider.cs index 33ff86c71f054..0fb14ae59d59c 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/AnonymousMethodExpressionStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/AnonymousMethodExpressionStructureProvider.cs @@ -6,7 +6,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; @@ -17,8 +16,7 @@ internal class AnonymousMethodExpressionStructureProvider : AbstractSyntaxNodeSt protected override void CollectBlockSpans( AnonymousMethodExpressionSyntax anonymousMethod, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { // fault tolerance diff --git a/src/Features/CSharp/Portable/Structure/Providers/ArrowExpressionClauseStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/ArrowExpressionClauseStructureProvider.cs index 13bca2357651f..b7862e4277182 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/ArrowExpressionClauseStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/ArrowExpressionClauseStructureProvider.cs @@ -7,7 +7,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; @@ -19,8 +18,7 @@ internal class ArrowExpressionClauseStructureProvider : AbstractSyntaxNodeStruct protected override void CollectBlockSpans( ArrowExpressionClauseSyntax node, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { var previousToken = node.ArrowToken.GetPreviousToken(); diff --git a/src/Features/CSharp/Portable/Structure/Providers/BlockSyntaxStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/BlockSyntaxStructureProvider.cs index fa30f2c6a867b..7c21d961a93c3 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/BlockSyntaxStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/BlockSyntaxStructureProvider.cs @@ -6,7 +6,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; @@ -18,8 +17,7 @@ internal class BlockSyntaxStructureProvider : AbstractSyntaxNodeStructureProvide protected override void CollectBlockSpans( BlockSyntax node, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { var parentKind = node.Parent.Kind(); diff --git a/src/Features/CSharp/Portable/Structure/Providers/CompilationUnitStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/CompilationUnitStructureProvider.cs index dab648f87e209..8da5e08643e51 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/CompilationUnitStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/CompilationUnitStructureProvider.cs @@ -7,7 +7,6 @@ using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; @@ -18,11 +17,10 @@ internal class CompilationUnitStructureProvider : AbstractSyntaxNodeStructurePro protected override void CollectBlockSpans( CompilationUnitSyntax compilationUnit, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { - CSharpStructureHelpers.CollectCommentBlockSpans(compilationUnit, spans, isMetadataAsSource); + CSharpStructureHelpers.CollectCommentBlockSpans(compilationUnit, spans, optionProvider); // extern aliases and usings are outlined in a single region var externsAndUsings = new List(); diff --git a/src/Features/CSharp/Portable/Structure/Providers/ConstructorDeclarationStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/ConstructorDeclarationStructureProvider.cs index 28d6cfb7486b7..8fc712b26dc1c 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/ConstructorDeclarationStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/ConstructorDeclarationStructureProvider.cs @@ -6,7 +6,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; @@ -17,11 +16,10 @@ internal class ConstructorDeclarationStructureProvider : AbstractSyntaxNodeStruc protected override void CollectBlockSpans( ConstructorDeclarationSyntax constructorDeclaration, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { - CSharpStructureHelpers.CollectCommentBlockSpans(constructorDeclaration, spans, isMetadataAsSource); + CSharpStructureHelpers.CollectCommentBlockSpans(constructorDeclaration, spans, optionProvider); // fault tolerance if (constructorDeclaration.Body == null || @@ -37,7 +35,7 @@ protected override void CollectBlockSpans( // Check IsNode to compress blank lines after this node if it is the last child of the parent. // // Whitespace between constructors is collapsed in Metadata as Source. - var compressEmptyLines = isMetadataAsSource + var compressEmptyLines = optionProvider.IsMetadataAsSource && (!nextSibling.IsNode || nextSibling.IsKind(SyntaxKind.ConstructorDeclaration)); spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( diff --git a/src/Features/CSharp/Portable/Structure/Providers/ConversionOperatorDeclarationStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/ConversionOperatorDeclarationStructureProvider.cs index 42544c7971894..14151199ad587 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/ConversionOperatorDeclarationStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/ConversionOperatorDeclarationStructureProvider.cs @@ -6,7 +6,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; @@ -17,11 +16,10 @@ internal class ConversionOperatorDeclarationStructureProvider : AbstractSyntaxNo protected override void CollectBlockSpans( ConversionOperatorDeclarationSyntax operatorDeclaration, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { - CSharpStructureHelpers.CollectCommentBlockSpans(operatorDeclaration, spans, isMetadataAsSource); + CSharpStructureHelpers.CollectCommentBlockSpans(operatorDeclaration, spans, optionProvider); // fault tolerance if (operatorDeclaration.Body == null || @@ -37,7 +35,7 @@ protected override void CollectBlockSpans( // Check IsNode to compress blank lines after this node if it is the last child of the parent. // // Whitespace between conversion operators is collapsed in Metadata as Source. - var compressEmptyLines = isMetadataAsSource + var compressEmptyLines = optionProvider.IsMetadataAsSource && (!nextSibling.IsNode || nextSibling.IsKind(SyntaxKind.ConversionOperatorDeclaration)); spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( diff --git a/src/Features/CSharp/Portable/Structure/Providers/DelegateDeclarationStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/DelegateDeclarationStructureProvider.cs index ac69427f84cdd..8588957b32994 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/DelegateDeclarationStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/DelegateDeclarationStructureProvider.cs @@ -6,7 +6,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; @@ -17,11 +16,10 @@ internal class DelegateDeclarationStructureProvider : AbstractSyntaxNodeStructur protected override void CollectBlockSpans( DelegateDeclarationSyntax delegateDeclaration, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { - CSharpStructureHelpers.CollectCommentBlockSpans(delegateDeclaration, spans, isMetadataAsSource); + CSharpStructureHelpers.CollectCommentBlockSpans(delegateDeclaration, spans, optionProvider); } } } diff --git a/src/Features/CSharp/Portable/Structure/Providers/DestructorDeclarationStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/DestructorDeclarationStructureProvider.cs index 40c4bec71e986..5f0160fc25452 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/DestructorDeclarationStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/DestructorDeclarationStructureProvider.cs @@ -6,7 +6,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; @@ -17,11 +16,10 @@ internal class DestructorDeclarationStructureProvider : AbstractSyntaxNodeStruct protected override void CollectBlockSpans( DestructorDeclarationSyntax destructorDeclaration, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { - CSharpStructureHelpers.CollectCommentBlockSpans(destructorDeclaration, spans, isMetadataAsSource); + CSharpStructureHelpers.CollectCommentBlockSpans(destructorDeclaration, spans, optionProvider); // fault tolerance if (destructorDeclaration.Body == null || diff --git a/src/Features/CSharp/Portable/Structure/Providers/DisabledTextTriviaStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/DisabledTextTriviaStructureProvider.cs index 576b0a19b9185..73fe07bc7e298 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/DisabledTextTriviaStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/DisabledTextTriviaStructureProvider.cs @@ -14,9 +14,9 @@ namespace Microsoft.CodeAnalysis.CSharp.Structure internal class DisabledTextTriviaStructureProvider : AbstractSyntaxTriviaStructureProvider { public override void CollectBlockSpans( - Document document, SyntaxTrivia trivia, ArrayBuilder spans, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { CollectBlockSpans(trivia.SyntaxTree, trivia, spans, cancellationToken); diff --git a/src/Features/CSharp/Portable/Structure/Providers/DocumentationCommentStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/DocumentationCommentStructureProvider.cs index 4b469c1fa2ed5..1bade76d74964 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/DocumentationCommentStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/DocumentationCommentStructureProvider.cs @@ -7,7 +7,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; @@ -19,8 +18,7 @@ internal class DocumentationCommentStructureProvider : AbstractSyntaxNodeStructu protected override void CollectBlockSpans( DocumentationCommentTriviaSyntax documentationComment, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { var startPos = documentationComment.FullSpan.Start; @@ -30,7 +28,7 @@ protected override void CollectBlockSpans( var span = TextSpan.FromBounds(startPos, endPos); - var bannerLength = options.GetOption(BlockStructureOptions.MaximumBannerLength, LanguageNames.CSharp); + var bannerLength = optionProvider.GetOption(BlockStructureOptions.MaximumBannerLength, LanguageNames.CSharp); var bannerText = CSharpSyntaxFacts.Instance.GetBannerText( documentationComment, bannerLength, cancellationToken); diff --git a/src/Features/CSharp/Portable/Structure/Providers/EnumDeclarationStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/EnumDeclarationStructureProvider.cs index 5dc53d553914f..5466ddbf2a1af 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/EnumDeclarationStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/EnumDeclarationStructureProvider.cs @@ -6,7 +6,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; @@ -17,11 +16,10 @@ internal class EnumDeclarationStructureProvider : AbstractSyntaxNodeStructurePro protected override void CollectBlockSpans( EnumDeclarationSyntax enumDeclaration, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { - CSharpStructureHelpers.CollectCommentBlockSpans(enumDeclaration, spans, isMetadataAsSource); + CSharpStructureHelpers.CollectCommentBlockSpans(enumDeclaration, spans, optionProvider); if (!enumDeclaration.OpenBraceToken.IsMissing && !enumDeclaration.CloseBraceToken.IsMissing) @@ -32,7 +30,7 @@ protected override void CollectBlockSpans( // Check IsNode to compress blank lines after this node if it is the last child of the parent. // // Whitespace between type declarations is collapsed in Metadata as Source. - var compressEmptyLines = isMetadataAsSource + var compressEmptyLines = optionProvider.IsMetadataAsSource && (!nextSibling.IsNode || nextSibling.AsNode() is BaseTypeDeclarationSyntax); spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( diff --git a/src/Features/CSharp/Portable/Structure/Providers/EnumMemberDeclarationStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/EnumMemberDeclarationStructureProvider.cs index d7aef414238e6..394d6b0c20229 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/EnumMemberDeclarationStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/EnumMemberDeclarationStructureProvider.cs @@ -6,7 +6,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; @@ -17,11 +16,10 @@ internal class EnumMemberDeclarationStructureProvider : AbstractSyntaxNodeStruct protected override void CollectBlockSpans( EnumMemberDeclarationSyntax enumMemberDeclaration, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { - CSharpStructureHelpers.CollectCommentBlockSpans(enumMemberDeclaration, spans, isMetadataAsSource); + CSharpStructureHelpers.CollectCommentBlockSpans(enumMemberDeclaration, spans, optionProvider); } } } diff --git a/src/Features/CSharp/Portable/Structure/Providers/EventDeclarationStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/EventDeclarationStructureProvider.cs index c5e37b680ce08..01a250dd062f2 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/EventDeclarationStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/EventDeclarationStructureProvider.cs @@ -6,7 +6,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; @@ -17,11 +16,10 @@ internal class EventDeclarationStructureProvider : AbstractSyntaxNodeStructurePr protected override void CollectBlockSpans( EventDeclarationSyntax eventDeclaration, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { - CSharpStructureHelpers.CollectCommentBlockSpans(eventDeclaration, spans, isMetadataAsSource); + CSharpStructureHelpers.CollectCommentBlockSpans(eventDeclaration, spans, optionProvider); // fault tolerance if (eventDeclaration.AccessorList == null || @@ -38,7 +36,7 @@ protected override void CollectBlockSpans( // Check IsNode to compress blank lines after this node if it is the last child of the parent. // // Full events are grouped together with event field definitions in Metadata as Source. - var compressEmptyLines = isMetadataAsSource + var compressEmptyLines = optionProvider.IsMetadataAsSource && (!nextSibling.IsNode || nextSibling.IsKind(SyntaxKind.EventDeclaration) || nextSibling.IsKind(SyntaxKind.EventFieldDeclaration)); spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( diff --git a/src/Features/CSharp/Portable/Structure/Providers/EventFieldDeclarationStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/EventFieldDeclarationStructureProvider.cs index 4176549c4a808..996b2952bfbdd 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/EventFieldDeclarationStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/EventFieldDeclarationStructureProvider.cs @@ -6,7 +6,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; @@ -17,11 +16,10 @@ internal class EventFieldDeclarationStructureProvider : AbstractSyntaxNodeStruct protected override void CollectBlockSpans( EventFieldDeclarationSyntax eventFieldDeclaration, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { - CSharpStructureHelpers.CollectCommentBlockSpans(eventFieldDeclaration, spans, isMetadataAsSource); + CSharpStructureHelpers.CollectCommentBlockSpans(eventFieldDeclaration, spans, optionProvider); } } } diff --git a/src/Features/CSharp/Portable/Structure/Providers/FieldDeclarationStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/FieldDeclarationStructureProvider.cs index 228a713b18763..9c0332aafd826 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/FieldDeclarationStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/FieldDeclarationStructureProvider.cs @@ -6,7 +6,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; @@ -17,11 +16,10 @@ internal class FieldDeclarationStructureProvider : AbstractSyntaxNodeStructurePr protected override void CollectBlockSpans( FieldDeclarationSyntax fieldDeclaration, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { - CSharpStructureHelpers.CollectCommentBlockSpans(fieldDeclaration, spans, isMetadataAsSource); + CSharpStructureHelpers.CollectCommentBlockSpans(fieldDeclaration, spans, optionProvider); } } } diff --git a/src/Features/CSharp/Portable/Structure/Providers/IndexerDeclarationStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/IndexerDeclarationStructureProvider.cs index 5640e2f985119..494604d751a70 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/IndexerDeclarationStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/IndexerDeclarationStructureProvider.cs @@ -6,7 +6,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; @@ -17,11 +16,10 @@ internal class IndexerDeclarationStructureProvider : AbstractSyntaxNodeStructure protected override void CollectBlockSpans( IndexerDeclarationSyntax indexerDeclaration, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { - CSharpStructureHelpers.CollectCommentBlockSpans(indexerDeclaration, spans, isMetadataAsSource); + CSharpStructureHelpers.CollectCommentBlockSpans(indexerDeclaration, spans, optionProvider); // fault tolerance if (indexerDeclaration.AccessorList == null || @@ -38,7 +36,7 @@ protected override void CollectBlockSpans( // Check IsNode to compress blank lines after this node if it is the last child of the parent. // // Indexers are grouped together with properties in Metadata as Source. - var compressEmptyLines = isMetadataAsSource + var compressEmptyLines = optionProvider.IsMetadataAsSource && (!nextSibling.IsNode || nextSibling.IsKind(SyntaxKind.IndexerDeclaration) || nextSibling.IsKind(SyntaxKind.PropertyDeclaration)); spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( diff --git a/src/Features/CSharp/Portable/Structure/Providers/InitializerExpressionStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/InitializerExpressionStructureProvider.cs index a55c1cef986ac..dffa69df6b412 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/InitializerExpressionStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/InitializerExpressionStructureProvider.cs @@ -6,7 +6,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; @@ -18,8 +17,7 @@ internal class InitializerExpressionStructureProvider : AbstractSyntaxNodeStruct protected override void CollectBlockSpans( InitializerExpressionSyntax node, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { if (node.Parent is InitializerExpressionSyntax) diff --git a/src/Features/CSharp/Portable/Structure/Providers/InterpolatedStringExpressionStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/InterpolatedStringExpressionStructureProvider.cs index f40a6c51c0b6a..08035b0092b47 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/InterpolatedStringExpressionStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/InterpolatedStringExpressionStructureProvider.cs @@ -6,7 +6,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; @@ -14,7 +13,11 @@ namespace Microsoft.CodeAnalysis.CSharp.Structure { internal sealed class InterpolatedStringExpressionStructureProvider : AbstractSyntaxNodeStructureProvider { - protected override void CollectBlockSpans(InterpolatedStringExpressionSyntax node, ArrayBuilder spans, bool isMetadataAsSource, OptionSet options, CancellationToken cancellationToken) + protected override void CollectBlockSpans( + InterpolatedStringExpressionSyntax node, + ArrayBuilder spans, + BlockStructureOptionProvider optionProvider, + CancellationToken cancellationToken) { if (node.StringStartToken.IsMissing || node.StringEndToken.IsMissing) diff --git a/src/Features/CSharp/Portable/Structure/Providers/MethodDeclarationStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/MethodDeclarationStructureProvider.cs index a00184ca6715d..ebb2b3c3da236 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/MethodDeclarationStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/MethodDeclarationStructureProvider.cs @@ -6,7 +6,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; @@ -17,11 +16,10 @@ internal class MethodDeclarationStructureProvider : AbstractSyntaxNodeStructureP protected override void CollectBlockSpans( MethodDeclarationSyntax methodDeclaration, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { - CSharpStructureHelpers.CollectCommentBlockSpans(methodDeclaration, spans, isMetadataAsSource); + CSharpStructureHelpers.CollectCommentBlockSpans(methodDeclaration, spans, optionProvider); // fault tolerance if (methodDeclaration.Body == null || @@ -37,7 +35,7 @@ protected override void CollectBlockSpans( // Check IsNode to compress blank lines after this node if it is the last child of the parent. // // Whitespace between methods is collapsed in Metadata as Source. - var compressEmptyLines = isMetadataAsSource + var compressEmptyLines = optionProvider.IsMetadataAsSource && (!nextSibling.IsNode || nextSibling.IsKind(SyntaxKind.MethodDeclaration)); spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( diff --git a/src/Features/CSharp/Portable/Structure/Providers/NamespaceDeclarationStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/NamespaceDeclarationStructureProvider.cs index c02065dd92039..4061afa44a66b 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/NamespaceDeclarationStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/NamespaceDeclarationStructureProvider.cs @@ -7,7 +7,6 @@ using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; @@ -18,12 +17,11 @@ internal class NamespaceDeclarationStructureProvider : AbstractSyntaxNodeStructu protected override void CollectBlockSpans( NamespaceDeclarationSyntax namespaceDeclaration, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { // add leading comments - CSharpStructureHelpers.CollectCommentBlockSpans(namespaceDeclaration, spans, isMetadataAsSource); + CSharpStructureHelpers.CollectCommentBlockSpans(namespaceDeclaration, spans, optionProvider); if (!namespaceDeclaration.OpenBraceToken.IsMissing && !namespaceDeclaration.CloseBraceToken.IsMissing) @@ -45,7 +43,7 @@ protected override void CollectBlockSpans( // add any leading comments before the extern aliases and usings if (externsAndUsings.Count > 0) { - CSharpStructureHelpers.CollectCommentBlockSpans(externsAndUsings.First(), spans, isMetadataAsSource); + CSharpStructureHelpers.CollectCommentBlockSpans(externsAndUsings.First(), spans, optionProvider); } spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( diff --git a/src/Features/CSharp/Portable/Structure/Providers/OperatorDeclarationStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/OperatorDeclarationStructureProvider.cs index 7a74de0ef119d..2c2bf6336e2fb 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/OperatorDeclarationStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/OperatorDeclarationStructureProvider.cs @@ -6,7 +6,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; @@ -17,11 +16,10 @@ internal class OperatorDeclarationStructureProvider : AbstractSyntaxNodeStructur protected override void CollectBlockSpans( OperatorDeclarationSyntax operatorDeclaration, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { - CSharpStructureHelpers.CollectCommentBlockSpans(operatorDeclaration, spans, isMetadataAsSource); + CSharpStructureHelpers.CollectCommentBlockSpans(operatorDeclaration, spans, optionProvider); // fault tolerance if (operatorDeclaration.Body == null || @@ -37,7 +35,7 @@ protected override void CollectBlockSpans( // Check IsNode to compress blank lines after this node if it is the last child of the parent. // // Whitespace between operators is collapsed in Metadata as Source. - var compressEmptyLines = isMetadataAsSource + var compressEmptyLines = optionProvider.IsMetadataAsSource && (!nextSibling.IsNode || nextSibling.IsKind(SyntaxKind.OperatorDeclaration)); spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( diff --git a/src/Features/CSharp/Portable/Structure/Providers/ParenthesizedLambdaExpressionStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/ParenthesizedLambdaExpressionStructureProvider.cs index 61127b50bae5c..c739bf4891b70 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/ParenthesizedLambdaExpressionStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/ParenthesizedLambdaExpressionStructureProvider.cs @@ -6,7 +6,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; @@ -17,8 +16,7 @@ internal class ParenthesizedLambdaExpressionStructureProvider : AbstractSyntaxNo protected override void CollectBlockSpans( ParenthesizedLambdaExpressionSyntax lambdaExpression, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { // fault tolerance diff --git a/src/Features/CSharp/Portable/Structure/Providers/PropertyDeclarationStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/PropertyDeclarationStructureProvider.cs index 0e3e884263670..69835a774fa31 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/PropertyDeclarationStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/PropertyDeclarationStructureProvider.cs @@ -6,7 +6,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; @@ -17,11 +16,10 @@ internal class PropertyDeclarationStructureProvider : AbstractSyntaxNodeStructur protected override void CollectBlockSpans( PropertyDeclarationSyntax propertyDeclaration, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { - CSharpStructureHelpers.CollectCommentBlockSpans(propertyDeclaration, spans, isMetadataAsSource); + CSharpStructureHelpers.CollectCommentBlockSpans(propertyDeclaration, spans, optionProvider); // fault tolerance if (propertyDeclaration.AccessorList == null || @@ -37,7 +35,7 @@ protected override void CollectBlockSpans( // Check IsNode to compress blank lines after this node if it is the last child of the parent. // // Properties are grouped together with indexers in Metadata as Source. - var compressEmptyLines = isMetadataAsSource + var compressEmptyLines = optionProvider.IsMetadataAsSource && (!nextSibling.IsNode || nextSibling.IsKind(SyntaxKind.PropertyDeclaration) || nextSibling.IsKind(SyntaxKind.IndexerDeclaration)); spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( diff --git a/src/Features/CSharp/Portable/Structure/Providers/RegionDirectiveStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/RegionDirectiveStructureProvider.cs index 8a40743a9f07f..04b72cf584a9a 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/RegionDirectiveStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/RegionDirectiveStructureProvider.cs @@ -7,7 +7,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; @@ -35,8 +34,7 @@ private static string GetBannerText(DirectiveTriviaSyntax simpleDirective) protected override void CollectBlockSpans( RegionDirectiveTriviaSyntax regionDirective, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { var match = regionDirective.GetMatchingDirective(cancellationToken); @@ -50,7 +48,7 @@ protected override void CollectBlockSpans( // #endregion // // For other files, auto-collapse regions based on the user option. - var autoCollapse = isMetadataAsSource || options.GetOption( + var autoCollapse = optionProvider.IsMetadataAsSource || optionProvider.GetOption( BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.CSharp); spans.Add(new BlockSpan( @@ -59,7 +57,7 @@ protected override void CollectBlockSpans( type: BlockTypes.PreprocessorRegion, bannerText: GetBannerText(regionDirective), autoCollapse: autoCollapse, - isDefaultCollapsed: !isMetadataAsSource)); + isDefaultCollapsed: !optionProvider.IsMetadataAsSource)); } } } diff --git a/src/Features/CSharp/Portable/Structure/Providers/SimpleLambdaExpressionStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/SimpleLambdaExpressionStructureProvider.cs index 7d98e9f7207b8..c73c5f6fa321e 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/SimpleLambdaExpressionStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/SimpleLambdaExpressionStructureProvider.cs @@ -6,7 +6,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; @@ -17,8 +16,7 @@ internal class SimpleLambdaExpressionStructureProvider : AbstractSyntaxNodeStruc protected override void CollectBlockSpans( SimpleLambdaExpressionSyntax lambdaExpression, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { // fault tolerance diff --git a/src/Features/CSharp/Portable/Structure/Providers/StringLiteralExpressionStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/StringLiteralExpressionStructureProvider.cs index 5af444943f3d3..00dcd24fc7e36 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/StringLiteralExpressionStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/StringLiteralExpressionStructureProvider.cs @@ -6,7 +6,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; @@ -14,7 +13,11 @@ namespace Microsoft.CodeAnalysis.CSharp.Structure { internal sealed class StringLiteralExpressionStructureProvider : AbstractSyntaxNodeStructureProvider { - protected override void CollectBlockSpans(LiteralExpressionSyntax node, ArrayBuilder spans, bool isMetadataAsSource, OptionSet options, CancellationToken cancellationToken) + protected override void CollectBlockSpans( + LiteralExpressionSyntax node, + ArrayBuilder spans, + BlockStructureOptionProvider optionProvider, + CancellationToken cancellationToken) { if (node.IsKind(SyntaxKind.StringLiteralExpression) && !node.ContainsDiagnostics) diff --git a/src/Features/CSharp/Portable/Structure/Providers/SwitchStatementStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/SwitchStatementStructureProvider.cs index 081b4273c77df..330364149e1e6 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/SwitchStatementStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/SwitchStatementStructureProvider.cs @@ -6,7 +6,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; @@ -18,8 +17,7 @@ internal class SwitchStatementStructureProvider : AbstractSyntaxNodeStructurePro protected override void CollectBlockSpans( SwitchStatementSyntax node, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { spans.Add(new BlockSpan( diff --git a/src/Features/CSharp/Portable/Structure/Providers/TypeDeclarationStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/TypeDeclarationStructureProvider.cs index 9e14987640a6a..7d097d0bbb72a 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/TypeDeclarationStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/TypeDeclarationStructureProvider.cs @@ -6,7 +6,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; @@ -17,11 +16,10 @@ internal class TypeDeclarationStructureProvider : AbstractSyntaxNodeStructurePro protected override void CollectBlockSpans( TypeDeclarationSyntax typeDeclaration, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { - CSharpStructureHelpers.CollectCommentBlockSpans(typeDeclaration, spans, isMetadataAsSource); + CSharpStructureHelpers.CollectCommentBlockSpans(typeDeclaration, spans, optionProvider); if (!typeDeclaration.OpenBraceToken.IsMissing && !typeDeclaration.CloseBraceToken.IsMissing) @@ -38,7 +36,7 @@ protected override void CollectBlockSpans( // Collapse to Definitions doesn't collapse type nodes, but a Toggle All Outlining would collapse groups // of types to the compressed form of not showing blank lines. All kinds of types are grouped together // in Metadata as Source. - var compressEmptyLines = isMetadataAsSource + var compressEmptyLines = optionProvider.IsMetadataAsSource && (!nextSibling.IsNode || nextSibling.AsNode() is BaseTypeDeclarationSyntax); spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.cs.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.cs.xlf index a86b5f5e5bba8..32d5dd7abb79b 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.cs.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.cs.xlf @@ -34,7 +34,7 @@ Apply file header preferences - Apply file header preferences + Použít předvolby hlaviček souborů @@ -89,12 +89,12 @@ Change to 'as' expression - Change to 'as' expression + Změnit na výraz as Change to cast - Change to cast + Změnit na přetypování @@ -644,7 +644,7 @@ '{0}' does not contain a constructor that takes that many arguments. - '{0} neobsahuje konstruktor, který přebírá tolik argumentů. + {0} neobsahuje konstruktor, který přebírá tolik argumentů. diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.de.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.de.xlf index 55325e7923b0a..9a9a990254eb8 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.de.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.de.xlf @@ -34,7 +34,7 @@ Apply file header preferences - Apply file header preferences + Dateiheadereinstellungen anwenden @@ -89,12 +89,12 @@ Change to 'as' expression - Change to 'as' expression + In as-Ausdruck ändern Change to cast - Change to cast + In "cast" ändern @@ -644,7 +644,7 @@ '{0}' does not contain a constructor that takes that many arguments. - '"{0}" enthält keinen Konstruktor, der viele Argumente verwendet. + "{0}" enthält keinen Konstruktor, der viele Argumente verwendet. diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.es.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.es.xlf index 2464e15ab1f7f..a3a23d78cf33f 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.es.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.es.xlf @@ -34,7 +34,7 @@ Apply file header preferences - Apply file header preferences + Aplicar preferencias de encabezado de archivo @@ -89,12 +89,12 @@ Change to 'as' expression - Change to 'as' expression + Cambiar a la expresión "as" Change to cast - Change to cast + Cambiar a cast diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.fr.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.fr.xlf index 6ae4d519fc784..2dd8c62d867d3 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.fr.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.fr.xlf @@ -34,7 +34,7 @@ Apply file header preferences - Apply file header preferences + Appliquer les préférences d'en-tête de fichier @@ -89,12 +89,12 @@ Change to 'as' expression - Change to 'as' expression + Changer en expression 'as' Change to cast - Change to cast + Changer en cast @@ -304,7 +304,7 @@ Selection does not contain a valid node - La sélection ne contient pas un nœud valide. + La sélection ne contient pas un nœud valide diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.it.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.it.xlf index e1ff1862df9f6..dfc2f20b7d69c 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.it.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.it.xlf @@ -34,7 +34,7 @@ Apply file header preferences - Apply file header preferences + Applica le preferenze relative alle intestazioni di file @@ -89,12 +89,12 @@ Change to 'as' expression - Change to 'as' expression + Cambia in espressione 'as' Change to cast - Change to cast + Cambia in cast diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ja.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ja.xlf index a8c19bf40c033..f25a29e0b3833 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ja.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ja.xlf @@ -34,7 +34,7 @@ Apply file header preferences - Apply file header preferences + ファイル ヘッダーの基本設定を適用する @@ -89,12 +89,12 @@ Change to 'as' expression - Change to 'as' expression + 'as' 式に変更 Change to cast - Change to cast + キャストに変更 @@ -304,7 +304,7 @@ Selection does not contain a valid node - 選択には有効なノードは含まれません。 + 選択には有効なノードは含まれません diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ko.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ko.xlf index 156110b575d86..1e69bf064eb23 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ko.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ko.xlf @@ -34,7 +34,7 @@ Apply file header preferences - Apply file header preferences + 파일 헤더 기본 설정 적용 @@ -89,12 +89,12 @@ Change to 'as' expression - Change to 'as' expression + 'as' 식으로 변경 Change to cast - Change to cast + 캐스트로 변경 @@ -274,7 +274,7 @@ Simplify name '{0}' - {0}' 이름 단순화 + '{0}' 이름 단순화 @@ -419,12 +419,12 @@ Generate explicit conversion operator in '{0}' - {0}'에서 명시적 변환 연산자 생성 + '{0}'에서 명시적 변환 연산자 생성 Generate implicit conversion operator in '{0}' - {0}'에서 암시적 변환 연산자 생성 + '{0}'에서 암시적 변환 연산자 생성 diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pl.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pl.xlf index 9101c488299b3..77bd93ac75bff 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pl.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pl.xlf @@ -34,7 +34,7 @@ Apply file header preferences - Apply file header preferences + Zastosuj preferencje nagłówka pliku @@ -89,12 +89,12 @@ Change to 'as' expression - Change to 'as' expression + Zmień na wyrażenie „as” Change to cast - Change to cast + Zmień na rzutowanie diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pt-BR.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pt-BR.xlf index adfb31cf81010..08eb1c37ac7b6 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pt-BR.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pt-BR.xlf @@ -34,7 +34,7 @@ Apply file header preferences - Apply file header preferences + Aplicar as preferências de cabeçalho de arquivo @@ -89,12 +89,12 @@ Change to 'as' expression - Change to 'as' expression + Alterar para a expressão 'as' Change to cast - Change to cast + Alterar para conversão @@ -249,7 +249,7 @@ <element name> : - <nome do elemento:> + <nome do elemento> : diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ru.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ru.xlf index a9d33d9bea606..3a31a1f1dabd0 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ru.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ru.xlf @@ -34,7 +34,7 @@ Apply file header preferences - Apply file header preferences + Применить параметры заголовка файла @@ -89,12 +89,12 @@ Change to 'as' expression - Change to 'as' expression + Изменить на выражение "as" Change to cast - Change to cast + Изменить на приведение @@ -644,7 +644,7 @@ '{0}' does not contain a constructor that takes that many arguments. - '"{0}" не содержит конструктор, который принимает такое количество аргументов. + "{0}" не содержит конструктор, который принимает такое количество аргументов. diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.tr.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.tr.xlf index 9838746026bac..4da7854d48e9a 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.tr.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.tr.xlf @@ -34,7 +34,7 @@ Apply file header preferences - Apply file header preferences + Dosya üst bilgisi tercihlerini uygula @@ -89,12 +89,12 @@ Change to 'as' expression - Change to 'as' expression + 'as' ifadesine değiştir Change to cast - Change to cast + Tür dönüştürme olarak değiştir @@ -274,12 +274,12 @@ Simplify name '{0}' - {0}' adını basitleştir + '{0}' adını basitleştir Simplify member access '{0}' - {0}' üye erişimini basitleştir + '{0}' üye erişimini basitleştir @@ -419,12 +419,12 @@ Generate explicit conversion operator in '{0}' - {0}' içinde açık dönüşüm işleci oluştur + '{0}' içinde açık dönüşüm işleci oluştur Generate implicit conversion operator in '{0}' - {0}' içinde örtük dönüşüm işleci oluştur + '{0}' içinde örtük dönüşüm işleci oluştur @@ -649,7 +649,7 @@ The name '{0}' does not exist in the current context. - {0}' adı geçerli bağlamda yok. + '{0}' adı geçerli bağlamda yok. diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hans.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hans.xlf index 8c28aad16c07d..7cfde0eca8f7f 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hans.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Add await and ConfigureAwait(false) @@ -34,7 +34,7 @@ Apply file header preferences - Apply file header preferences + 应用文件头首选项 @@ -89,12 +89,12 @@ Change to 'as' expression - Change to 'as' expression + 更改为 "as" 表达式 Change to cast - Change to cast + 更改为强制转换 @@ -644,7 +644,7 @@ '{0}' does not contain a constructor that takes that many arguments. - '“{0}”不包含采用许多参数的构造函数。 + “{0}”不包含采用许多参数的构造函数。 diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hant.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hant.xlf index e2c66a3589b2d..b7813a2f5ad58 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hant.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Add await and ConfigureAwait(false) @@ -34,7 +34,7 @@ Apply file header preferences - Apply file header preferences + 套用檔案標題的喜好設定 @@ -89,12 +89,12 @@ Change to 'as' expression - Change to 'as' expression + 變更為 'as' 運算式 Change to cast - Change to cast + 變更為 'cast' diff --git a/src/Features/Core/Portable/AddImport/AbstractAddImportFeatureService.cs b/src/Features/Core/Portable/AddImport/AbstractAddImportFeatureService.cs index 4e2a75a850a43..49b8b9bc3c55b 100644 --- a/src/Features/Core/Portable/AddImport/AbstractAddImportFeatureService.cs +++ b/src/Features/Core/Portable/AddImport/AbstractAddImportFeatureService.cs @@ -511,7 +511,7 @@ private static bool NotNull(SymbolReference reference) public ImmutableArray GetCodeActionsForFixes( Document document, ImmutableArray fixes, - IPackageInstallerService installerService, int maxResults) + IPackageInstallerService? installerService, int maxResults) { var codeActionsBuilder = ArrayBuilder.GetInstance(); @@ -530,13 +530,13 @@ public ImmutableArray GetCodeActionsForFixes( return codeActionsBuilder.ToImmutableAndFree(); } - private static CodeAction? TryCreateCodeAction(Document document, AddImportFixData fixData, IPackageInstallerService installerService) + private static CodeAction? TryCreateCodeAction(Document document, AddImportFixData fixData, IPackageInstallerService? installerService) => fixData.Kind switch { AddImportFixKind.ProjectSymbol => new ProjectSymbolReferenceCodeAction(document, fixData), AddImportFixKind.MetadataSymbol => new MetadataSymbolReferenceCodeAction(document, fixData), AddImportFixKind.ReferenceAssemblySymbol => new AssemblyReferenceCodeAction(document, fixData), - AddImportFixKind.PackageSymbol => !installerService.IsInstalled(document.Project.Solution.Workspace, document.Project.Id, fixData.PackageName) + AddImportFixKind.PackageSymbol => installerService?.IsInstalled(document.Project.Solution.Workspace, document.Project.Id, fixData.PackageName) == false ? new ParentInstallPackageCodeAction(document, fixData, installerService) : null, _ => throw ExceptionUtilities.Unreachable, diff --git a/src/Features/Core/Portable/AddImport/CodeActions/AssemblyReferenceCodeAction.cs b/src/Features/Core/Portable/AddImport/CodeActions/AssemblyReferenceCodeAction.cs index a652f79ad22b6..20f3d551c7056 100644 --- a/src/Features/Core/Portable/AddImport/CodeActions/AssemblyReferenceCodeAction.cs +++ b/src/Features/Core/Portable/AddImport/CodeActions/AssemblyReferenceCodeAction.cs @@ -7,6 +7,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Host; +using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddImport @@ -23,17 +24,6 @@ public AssemblyReferenceCodeAction( Contract.ThrowIfFalse(fixData.Kind == AddImportFixKind.ReferenceAssemblySymbol); } - private Task ResolvePathAsync(CancellationToken cancellationToken) - { - var assemblyResolverService = OriginalDocument.Project.Solution.Workspace.Services.GetRequiredService(); - - return assemblyResolverService.ResolveAssemblyPathAsync( - OriginalDocument.Project.Id, - FixData.AssemblyReferenceAssemblyName, - FixData.AssemblyReferenceFullyQualifiedTypeName, - cancellationToken); - } - protected override Task> ComputePreviewOperationsAsync(CancellationToken cancellationToken) => ComputeOperationsAsync(isPreview: true, cancellationToken); @@ -45,21 +35,82 @@ private async Task> ComputeOperationsAsync(bool var newDocument = await GetUpdatedDocumentAsync(cancellationToken).ConfigureAwait(false); var newProject = newDocument.Project; - // Now add the actual assembly reference. - if (!isPreview) + if (isPreview) { - var resolvedPath = await ResolvePathAsync(cancellationToken).ConfigureAwait(false); - if (!string.IsNullOrWhiteSpace(resolvedPath)) - { - var service = OriginalDocument.Project.Solution.Workspace.Services.GetRequiredService(); - var reference = service.GetReference(resolvedPath, MetadataReferenceProperties.Assembly); - newProject = newProject.WithMetadataReferences( - newProject.MetadataReferences.Concat(reference)); - } + // If this is a preview, just return an ApplyChangesOperation for the updated document + var operation = new ApplyChangesOperation(newProject.Solution); + return SpecializedCollections.SingletonEnumerable(operation); } + else + { + // Otherwise return an operation that can apply the text changes and add the reference + var operation = new AddAssemblyReferenceCodeActionOperation( + FixData.AssemblyReferenceAssemblyName, + FixData.AssemblyReferenceFullyQualifiedTypeName, + newProject); + return SpecializedCollections.SingletonEnumerable(operation); + } + } + + private sealed class AddAssemblyReferenceCodeActionOperation : CodeActionOperation + { + private readonly string _assemblyReferenceAssemblyName; + private readonly string _assemblyReferenceFullyQualifiedTypeName; + private readonly Project _newProject; + + public AddAssemblyReferenceCodeActionOperation( + string assemblyReferenceAssemblyName, + string assemblyReferenceFullyQualifiedTypeName, + Project newProject) + { + _assemblyReferenceAssemblyName = assemblyReferenceAssemblyName; + _assemblyReferenceFullyQualifiedTypeName = assemblyReferenceFullyQualifiedTypeName; + _newProject = newProject; + } + + internal override bool ApplyDuringTests => true; + + public override void Apply(Workspace workspace, CancellationToken cancellationToken) + { + var operation = GetApplyChangesOperation(workspace); + if (operation is null) + return; - var operation = new ApplyChangesOperation(newProject.Solution); - return SpecializedCollections.SingletonEnumerable(operation); + operation.Apply(workspace, cancellationToken); + } + + internal override bool TryApply(Workspace workspace, IProgressTracker progressTracker, CancellationToken cancellationToken) + { + var operation = GetApplyChangesOperation(workspace); + if (operation is null) + return false; + + return operation.TryApply(workspace, progressTracker, cancellationToken); + } + + private ApplyChangesOperation? GetApplyChangesOperation(Workspace workspace) + { + var resolvedPath = ResolvePath(workspace); + if (string.IsNullOrWhiteSpace(resolvedPath)) + return null; + + var service = workspace.Services.GetRequiredService(); + var reference = service.GetReference(resolvedPath, MetadataReferenceProperties.Assembly); + var newProject = _newProject.WithMetadataReferences( + _newProject.MetadataReferences.Concat(reference)); + + return new ApplyChangesOperation(newProject.Solution); + } + + private string? ResolvePath(Workspace workspace) + { + var assemblyResolverService = workspace.Services.GetRequiredService(); + + return assemblyResolverService.ResolveAssemblyPath( + _newProject.Id, + _assemblyReferenceAssemblyName, + _assemblyReferenceFullyQualifiedTypeName); + } } } } diff --git a/src/Features/Core/Portable/AddImport/CodeActions/MetadataSymbolReferenceCodeAction.cs b/src/Features/Core/Portable/AddImport/CodeActions/MetadataSymbolReferenceCodeAction.cs index 556935f6957f0..713dc90adaa54 100644 --- a/src/Features/Core/Portable/AddImport/CodeActions/MetadataSymbolReferenceCodeAction.cs +++ b/src/Features/Core/Portable/AddImport/CodeActions/MetadataSymbolReferenceCodeAction.cs @@ -2,11 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable - using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddImport @@ -21,14 +21,14 @@ public MetadataSymbolReferenceCodeAction(Document originalDocument, AddImportFix Contract.ThrowIfFalse(fixData.Kind == AddImportFixKind.MetadataSymbol); } - protected override Task UpdateProjectAsync(Project project, bool isPreview, CancellationToken cancellationToken) + protected override Task UpdateProjectAsync(Project project, bool isPreview, CancellationToken cancellationToken) { - var projectWithReference = project.Solution.GetProject(FixData.PortableExecutableReferenceProjectId); + var projectWithReference = project.Solution.GetRequiredProject(FixData.PortableExecutableReferenceProjectId); var reference = projectWithReference.MetadataReferences .OfType() .First(pe => pe.FilePath == FixData.PortableExecutableReferenceFilePathToAdd); - return Task.FromResult(project.AddMetadataReference(reference)); + return Task.FromResult(new ApplyChangesOperation(project.AddMetadataReference(reference).Solution)); } } } diff --git a/src/Features/Core/Portable/AddImport/CodeActions/ProjectSymbolReferenceCodeAction.cs b/src/Features/Core/Portable/AddImport/CodeActions/ProjectSymbolReferenceCodeAction.cs index b9794366710df..51e66bfdf738a 100644 --- a/src/Features/Core/Portable/AddImport/CodeActions/ProjectSymbolReferenceCodeAction.cs +++ b/src/Features/Core/Portable/AddImport/CodeActions/ProjectSymbolReferenceCodeAction.cs @@ -2,10 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable - using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddImport @@ -31,22 +31,58 @@ public ProjectSymbolReferenceCodeAction( private bool ShouldAddProjectReference() => FixData.ProjectReferenceToAdd != null && FixData.ProjectReferenceToAdd != OriginalDocument.Project.Id; - protected override async Task UpdateProjectAsync(Project project, bool isPreview, CancellationToken cancellationToken) + protected override Task UpdateProjectAsync(Project project, bool isPreview, CancellationToken cancellationToken) { if (!ShouldAddProjectReference()) { - return project; + return SpecializedTasks.Null(); } - if (!isPreview) + var projectWithAddedReference = project.AddProjectReference(new ProjectReference(FixData.ProjectReferenceToAdd)); + var applyOperation = new ApplyChangesOperation(projectWithAddedReference.Solution); + if (isPreview) + { + return Task.FromResult(applyOperation); + } + + return Task.FromResult(new AddProjectReferenceCodeActionOperation(OriginalDocument.Project.Id, FixData.ProjectReferenceToAdd, applyOperation)); + } + + private sealed class AddProjectReferenceCodeActionOperation : CodeActionOperation + { + private readonly ProjectId _referencingProject; + private readonly ProjectId _referencedProject; + private readonly ApplyChangesOperation _applyOperation; + + public AddProjectReferenceCodeActionOperation(ProjectId referencingProject, ProjectId referencedProject, ApplyChangesOperation applyOperation) { - if (!await project.Solution.Workspace.CanAddProjectReferenceAsync(OriginalDocument.Project.Id, FixData.ProjectReferenceToAdd, cancellationToken).ConfigureAwait(false)) - { - return project; - } + _referencingProject = referencingProject; + _referencedProject = referencedProject; + _applyOperation = applyOperation; } - return project.AddProjectReference(new ProjectReference(FixData.ProjectReferenceToAdd)); + internal override bool ApplyDuringTests => true; + + public override void Apply(Workspace workspace, CancellationToken cancellationToken) + { + if (!CanApply(workspace)) + return; + + _applyOperation.Apply(workspace, cancellationToken); + } + + internal override bool TryApply(Workspace workspace, IProgressTracker progressTracker, CancellationToken cancellationToken) + { + if (!CanApply(workspace)) + return false; + + return _applyOperation.TryApply(workspace, progressTracker, cancellationToken); + } + + private bool CanApply(Workspace workspace) + { + return workspace.CanAddProjectReference(_referencingProject, _referencedProject); + } } } } diff --git a/src/Features/Core/Portable/AddImport/CodeActions/SymbolReference.SymbolReferenceCodeAction.cs b/src/Features/Core/Portable/AddImport/CodeActions/SymbolReference.SymbolReferenceCodeAction.cs index 24158d85adc8e..882aabe48023f 100644 --- a/src/Features/Core/Portable/AddImport/CodeActions/SymbolReference.SymbolReferenceCodeAction.cs +++ b/src/Features/Core/Portable/AddImport/CodeActions/SymbolReference.SymbolReferenceCodeAction.cs @@ -2,13 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable - using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddImport { @@ -31,32 +30,38 @@ protected SymbolReferenceCodeAction( protected override async Task> ComputePreviewOperationsAsync(CancellationToken cancellationToken) { - var changedSolution = await GetChangedSolutionAsync(isPreview: true, cancellationToken).ConfigureAwait(false); - if (changedSolution == null) + var operation = await GetChangeSolutionOperationAsync(isPreview: true, cancellationToken).ConfigureAwait(false); + if (operation is null) { return Array.Empty(); } - return new CodeActionOperation[] { new ApplyChangesOperation(changedSolution) }; + return SpecializedCollections.SingletonEnumerable(operation); } - protected override Task GetChangedSolutionAsync(CancellationToken cancellationToken) + protected override async Task> ComputeOperationsAsync(CancellationToken cancellationToken) { - return GetChangedSolutionAsync(isPreview: false, cancellationToken); + var operation = await GetChangeSolutionOperationAsync(isPreview: false, cancellationToken).ConfigureAwait(false); + if (operation is null) + { + return Array.Empty(); + } + + return SpecializedCollections.SingletonEnumerable(operation); } - private async Task GetChangedSolutionAsync(bool isPreview, CancellationToken cancellationToken) + private async Task GetChangeSolutionOperationAsync(bool isPreview, CancellationToken cancellationToken) { var updatedDocument = await GetUpdatedDocumentAsync(cancellationToken).ConfigureAwait(false); - // Defer to subtype to add any p2p or metadata refs as appropriate. + // Defer to subtype to add any p2p or metadata refs as appropriate. If no changes to project references + // are necessary, the call to 'UpdateProjectAsync' will return null, in which case we fall back to just + // returning the updated document with its text changes. var updatedProject = await UpdateProjectAsync(updatedDocument.Project, isPreview, cancellationToken).ConfigureAwait(false); - - var updatedSolution = updatedProject.Solution; - return updatedSolution; + return updatedProject ?? new ApplyChangesOperation(updatedDocument.Project.Solution); } - protected abstract Task UpdateProjectAsync(Project project, bool isPreview, CancellationToken cancellationToken); + protected abstract Task UpdateProjectAsync(Project project, bool isPreview, CancellationToken cancellationToken); } } } diff --git a/src/Features/Core/Portable/AddImport/IAddImportFeatureService.cs b/src/Features/Core/Portable/AddImport/IAddImportFeatureService.cs index bc3f9a8c20179..a40c621a855f1 100644 --- a/src/Features/Core/Portable/AddImport/IAddImportFeatureService.cs +++ b/src/Features/Core/Portable/AddImport/IAddImportFeatureService.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable - using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; @@ -42,6 +40,6 @@ Task> GetFixesAsync( /// ImmutableArray GetCodeActionsForFixes( Document document, ImmutableArray fixes, - IPackageInstallerService installerService, int maxResults); + IPackageInstallerService? installerService, int maxResults); } } diff --git a/src/Features/Core/Portable/CodeRefactorings/AddMissingImports/AbstractAddMissingImportsFeatureService.cs b/src/Features/Core/Portable/CodeRefactorings/AddMissingImports/AbstractAddMissingImportsFeatureService.cs index b466c018078f7..44652478b83f2 100644 --- a/src/Features/Core/Portable/CodeRefactorings/AddMissingImports/AbstractAddMissingImportsFeatureService.cs +++ b/src/Features/Core/Portable/CodeRefactorings/AddMissingImports/AbstractAddMissingImportsFeatureService.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable - using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; @@ -21,6 +19,8 @@ using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Text; +using Microsoft.CodeAnalysis.Utilities; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddMissingImports { @@ -28,27 +28,35 @@ internal abstract class AbstractAddMissingImportsFeatureService : IAddMissingImp { protected abstract ImmutableArray FixableDiagnosticIds { get; } - public async Task HasMissingImportsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken) + /// + public async Task AddMissingImportsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken) { - // Get the diagnostics that indicate a missing import. - var diagnostics = await GetDiagnosticsAsync(document, textSpan, cancellationToken).ConfigureAwait(false); - if (diagnostics.IsEmpty) + var analysisResult = await AnalyzeAsync(document, textSpan, cancellationToken).ConfigureAwait(false); + return await AddMissingImportsAsync(document, analysisResult, cancellationToken).ConfigureAwait(false); + } + + /// + public async Task AddMissingImportsAsync(Document document, AddMissingImportsAnalysisResult analysisResult, CancellationToken cancellationToken) + { + if (analysisResult.CanAddMissingImports) { - return false; + // Apply those fixes to the document. + var newDocument = await ApplyFixesAsync(document, analysisResult.AddImportFixData, cancellationToken).ConfigureAwait(false); + return newDocument; } - // Find fixes for the diagnostic where there is only a single fix. - var usableFixes = await GetUnambiguousFixesAsync(document, diagnostics, cancellationToken).ConfigureAwait(false); - return !usableFixes.IsEmpty; + return document; } - public async Task AddMissingImportsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken) + /// + public async Task AnalyzeAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken) { // Get the diagnostics that indicate a missing import. var diagnostics = await GetDiagnosticsAsync(document, textSpan, cancellationToken).ConfigureAwait(false); if (diagnostics.IsEmpty) { - return document.Project; + return new AddMissingImportsAnalysisResult( + ImmutableArray.Empty); } // Find fixes for the diagnostic where there is only a single fix. @@ -56,14 +64,8 @@ public async Task AddMissingImportsAsync(Document document, TextSpan te // We do not want to add project or framework references without the user's input, so filter those out. var usableFixes = unambiguousFixes.WhereAsArray(fixData => DoesNotAddReference(fixData, document.Project.Id)); - if (usableFixes.IsEmpty) - { - return document.Project; - } - // Apply those fixes to the document. - var newDocument = await ApplyFixesAsync(document, usableFixes, cancellationToken).ConfigureAwait(false); - return newDocument.Project; + return new AddMissingImportsAnalysisResult(usableFixes); } private static bool DoesNotAddReference(AddImportFixData fixData, ProjectId currentProjectId) @@ -89,10 +91,10 @@ private async Task> GetDiagnosticsAsync(Document docu private static async Task> GetUnambiguousFixesAsync(Document document, ImmutableArray diagnostics, CancellationToken cancellationToken) { var solution = document.Project.Solution; - var symbolSearchService = solution.Workspace.Services.GetService(); + var symbolSearchService = solution.Workspace.Services.GetRequiredService(); // Since we are not currently considering NuGet packages, pass an empty array var packageSources = ImmutableArray.Empty; - var addImportService = document.GetLanguageService(); + var addImportService = document.GetRequiredLanguageService(); // We only need to receive 2 results back per diagnostic to determine that the fix is ambiguous. var getFixesForDiagnosticsTasks = diagnostics @@ -130,9 +132,9 @@ private static async Task ApplyFixesAsync(Document document, Immutable var solution = document.Project.Solution; var progressTracker = new ProgressTracker(); - var textDiffingService = solution.Workspace.Services.GetService(); + var textDiffingService = solution.Workspace.Services.GetRequiredService(); var packageInstallerService = solution.Workspace.Services.GetService(); - var addImportService = document.GetLanguageService(); + var addImportService = document.GetRequiredLanguageService(); // Do not limit the results since we plan to fix all the reported issues. var codeActions = addImportService.GetCodeActionsForFixes(document, fixes, packageInstallerService, maxResults: int.MaxValue); @@ -170,11 +172,11 @@ private static async Task ApplyFixesAsync(Document document, Immutable // length of the text we are inserting so that we can format the span afterwards. var insertSpans = allTextChanges .GroupBy(change => change.Span) - .Select(changes => new TextSpan(changes.Key.Start, changes.Sum(change => change.NewText.Length))); + .Select(changes => new TextSpan(changes.Key.Start, changes.Sum(change => change.NewText!.Length))); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var newText = text.WithChanges(orderedTextInserts); - var newDocument = newProject.GetDocument(document.Id).WithText(newText); + var newDocument = newProject.GetRequiredDocument(document.Id).WithText(newText); // When imports are added to a code file that has no previous imports, extra // newlines are generated between each import because the fix is expecting to @@ -185,7 +187,7 @@ private static async Task ApplyFixesAsync(Document document, Immutable private static async Task CleanUpNewLinesAsync(Document document, IEnumerable insertSpans, CancellationToken cancellationToken) { - var languageFormatter = document.GetLanguageService(); + var languageFormatter = document.GetRequiredLanguageService(); var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var newDocument = document; @@ -203,7 +205,7 @@ private static async Task CleanUpNewLinesAsync(Document document, IEnu private static async Task CleanUpNewLinesAsync(Document document, TextSpan insertSpan, ISyntaxFormattingService languageFormatter, OptionSet optionSet, CancellationToken cancellationToken) { - var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var optionService = document.Project.Solution.Workspace.Services.GetRequiredService(); var shouldUseFormattingSpanCollapse = optionSet.GetOption(FormattingOptions.AllowDisjointSpanMerging); @@ -237,9 +239,36 @@ private static async Task CleanUpNewLinesAsync(Document document, Text IDocumentTextDifferencingService textDiffingService, CancellationToken cancellationToken) { - var newSolution = await codeAction.GetChangedSolutionAsync( - progressTracker, cancellationToken: cancellationToken).ConfigureAwait(false); - var newDocument = newSolution.GetDocument(document.Id); + // CodeAction.GetChangedSolutionAsync is only implemented for code actions that can fully compute the new + // solution without deferred computation or taking a dependency on the main thread. In other cases, the + // implementation of GetChangedSolutionAsync will throw an exception and the code action application is + // expected to apply the changes by executing the operations in GetOperationsAsync (which may have other + // side effects). This code cannot assume the input CodeAction supports GetChangedSolutionAsync, so it first + // attempts to apply text changes obtained from GetOperationsAsync. Two forms are supported: + // + // 1. GetOperationsAsync returns an empty list of operations (i.e. no changes are required) + // 2. GetOperationsAsync returns a list of operations, where the first change is an ApplyChangesOperation to + // change the text in the solution, and any remaining changes are deferred computation changes. + // + // If GetOperationsAsync does not adhere to one of these patterns, the code falls back to calling + // GetChangedSolutionAsync since there is no clear way to apply the changes otherwise. + var operations = await codeAction.GetOperationsAsync(cancellationToken).ConfigureAwait(false); + Solution newSolution; + if (operations.Length == 0) + { + newSolution = document.Project.Solution; + } + else if (operations.Length == 1 && operations[0] is ApplyChangesOperation applyChangesOperation) + { + newSolution = applyChangesOperation.ChangedSolution; + } + else + { + newSolution = await codeAction.GetRequiredChangedSolutionAsync( + progressTracker, cancellationToken: cancellationToken).ConfigureAwait(false); + } + + var newDocument = newSolution.GetRequiredDocument(document.Id); // Use Line differencing to reduce the possibility of changes that overwrite existing code. var textChanges = await textDiffingService.GetTextChangesAsync( @@ -256,7 +285,7 @@ private sealed class CleanUpNewLinesFormatter : AbstractFormattingRule public CleanUpNewLinesFormatter(SourceText text) => _text = text; - public override AdjustNewLinesOperation GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) + public override AdjustNewLinesOperation? GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) { // Since we know the general shape of these new import statements, we simply look for where // tokens are not on the same line and force them to only be separated by a single newline. diff --git a/src/Features/Core/Portable/CodeRefactorings/AddMissingImports/AbstractAddMissingImportsRefactoringProvider.cs b/src/Features/Core/Portable/CodeRefactorings/AddMissingImports/AbstractAddMissingImportsRefactoringProvider.cs index 62aa95f1d1c1c..4db4b844c33d1 100644 --- a/src/Features/Core/Portable/CodeRefactorings/AddMissingImports/AbstractAddMissingImportsRefactoringProvider.cs +++ b/src/Features/Core/Portable/CodeRefactorings/AddMissingImports/AbstractAddMissingImportsRefactoringProvider.cs @@ -11,6 +11,7 @@ using Microsoft.CodeAnalysis.PasteTracking; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddMissingImports { @@ -34,25 +35,24 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte // Check pasted text span for missing imports var addMissingImportsService = document.GetLanguageService(); - var hasMissingImports = await addMissingImportsService.HasMissingImportsAsync(document, textSpan, cancellationToken).ConfigureAwait(false); - if (!hasMissingImports) + var analysis = await addMissingImportsService.AnalyzeAsync(document, textSpan, cancellationToken).ConfigureAwait(false); + if (!analysis.CanAddMissingImports) { return; } var addImportsCodeAction = new AddMissingImportsCodeAction( CodeActionTitle, - cancellationToken => AddMissingImportsAsync(document, textSpan, cancellationToken)); + cancellationToken => AddMissingImportsAsync(document, addMissingImportsService, analysis, cancellationToken)); + context.RegisterRefactoring(addImportsCodeAction, textSpan); } - private static async Task AddMissingImportsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken) + private static async Task AddMissingImportsAsync(Document document, IAddMissingImportsFeatureService addMissingImportsService, AddMissingImportsAnalysisResult analysis, CancellationToken cancellationToken) { - // Add missing imports for the pasted text span. - var addMissingImportsService = document.GetLanguageService(); - var newProject = await addMissingImportsService.AddMissingImportsAsync(document, textSpan, cancellationToken).ConfigureAwait(false); - return newProject.Solution; + var modifiedDocument = await addMissingImportsService.AddMissingImportsAsync(document, analysis, cancellationToken).ConfigureAwait(false); + return modifiedDocument.Project.Solution; } private class AddMissingImportsCodeAction : CodeActions.CodeAction.SolutionChangeAction diff --git a/src/Features/Core/Portable/CodeRefactorings/AddMissingImports/AddMissingImportsAnalysisResult.cs b/src/Features/Core/Portable/CodeRefactorings/AddMissingImports/AddMissingImportsAnalysisResult.cs new file mode 100644 index 0000000000000..734190005a73e --- /dev/null +++ b/src/Features/Core/Portable/CodeRefactorings/AddMissingImports/AddMissingImportsAnalysisResult.cs @@ -0,0 +1,22 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.AddImport; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.AddMissingImports +{ + internal sealed class AddMissingImportsAnalysisResult + { + public ImmutableArray AddImportFixData { get; } + public bool CanAddMissingImports => !AddImportFixData.IsEmpty; + + public AddMissingImportsAnalysisResult( + ImmutableArray addImportFixData) + { + AddImportFixData = addImportFixData; + } + } +} diff --git a/src/Features/Core/Portable/CodeRefactorings/AddMissingImports/IAddMissingImportsFeatureService.cs b/src/Features/Core/Portable/CodeRefactorings/AddMissingImports/IAddMissingImportsFeatureService.cs index a1d6e3db1b5ca..a05c56f33d20e 100644 --- a/src/Features/Core/Portable/CodeRefactorings/AddMissingImports/IAddMissingImportsFeatureService.cs +++ b/src/Features/Core/Portable/CodeRefactorings/AddMissingImports/IAddMissingImportsFeatureService.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable - using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; @@ -13,8 +11,23 @@ namespace Microsoft.CodeAnalysis.AddMissingImports { internal interface IAddMissingImportsFeatureService : ILanguageService { - Task HasMissingImportsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken); + /// + /// Attempts to add missing imports to the document within the textspan provided. The imports added will + /// not add assembly references to the project. In case of failure, null is returned. Failure can happen + /// if there are ambiguous imports, no known resolutions to import, or if no imports that would be provided + /// would be added without adding a reference for the project. + /// + Task AddMissingImportsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken); + + /// + /// Analyzes the document inside the texstpan to determine if imports can be added. + /// + Task AnalyzeAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken); - Task AddMissingImportsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken); + /// + /// Performs the same action as but + /// with a predetermined analysis of the input instead of recalculating it + /// + Task AddMissingImportsAsync(Document document, AddMissingImportsAnalysisResult analysisResult, CancellationToken cancellationToken); } } diff --git a/src/Features/Core/Portable/Completion/Log/CompletionProvidersLogger.cs b/src/Features/Core/Portable/Completion/Log/CompletionProvidersLogger.cs index 401a5664df625..39cdd8ff7e1a5 100644 --- a/src/Features/Core/Portable/Completion/Log/CompletionProvidersLogger.cs +++ b/src/Features/Core/Portable/Completion/Log/CompletionProvidersLogger.cs @@ -38,6 +38,7 @@ internal enum ActionInfo CommitsOfExtensionMethodImportCompletionItem, ExtensionMethodCompletionPartialResultCount, ExtensionMethodCompletionTimeoutCount, + CommitUsingSemicolonToAddParenthesis, } internal static void LogTypeImportCompletionTicksDataPoint(int count) @@ -85,6 +86,9 @@ internal static void LogExtensionMethodCompletionPartialResultCount() => internal static void LogExtensionMethodCompletionTimeoutCount() => s_logAggregator.IncreaseCount((int)ActionInfo.ExtensionMethodCompletionTimeoutCount); + internal static void LogCommitUsingSemicolonToAddParenthesis() => + s_logAggregator.IncreaseCount((int)ActionInfo.CommitUsingSemicolonToAddParenthesis); + internal static void ReportTelemetry() { Logger.Log(FunctionId.Intellisense_CompletionProviders_Data, KeyValueLogMessage.Create(m => diff --git a/src/Features/Core/Portable/Completion/Providers/AbstractRecommendationServiceBasedCompletionProvider.cs b/src/Features/Core/Portable/Completion/Providers/AbstractRecommendationServiceBasedCompletionProvider.cs index a6b086a6fff5e..39b8d60d4dc45 100644 --- a/src/Features/Core/Portable/Completion/Providers/AbstractRecommendationServiceBasedCompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/Providers/AbstractRecommendationServiceBasedCompletionProvider.cs @@ -4,7 +4,6 @@ #nullable disable -using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; @@ -65,9 +64,15 @@ private static ITypeSymbol GetSymbolType(ISymbol symbol) return symbol.GetSymbolType(); } - protected override CompletionItem CreateItem(CompletionContext completionContext, - string displayText, string displayTextSuffix, string insertionText, - List symbols, SyntaxContext context, bool preselect, SupportedPlatformData supportedPlatformData) + protected override CompletionItem CreateItem( + CompletionContext completionContext, + string displayText, + string displayTextSuffix, + string insertionText, + List symbols, + SyntaxContext context, + bool preselect, + SupportedPlatformData supportedPlatformData) { var rules = GetCompletionItemRules(symbols, context, preselect); var matchPriority = preselect ? ComputeSymbolMatchPriority(symbols[0]) : MatchPriority.Default; diff --git a/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractImportCompletionProvider.cs b/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractImportCompletionProvider.cs index 78065526a375c..41c44c153a8d3 100644 --- a/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractImportCompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractImportCompletionProvider.cs @@ -7,6 +7,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddImports; +using Microsoft.CodeAnalysis.Completion.Log; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Formatting; @@ -26,6 +27,7 @@ internal abstract class AbstractImportCompletionProvider : LSPCompletionProvider protected abstract bool ShouldProvideCompletion(CompletionContext completionContext, SyntaxContext syntaxContext); protected abstract Task AddCompletionItemsAsync(CompletionContext completionContext, SyntaxContext syntaxContext, HashSet namespacesInScope, bool isExpandedCompletion, CancellationToken cancellationToken); protected abstract bool IsFinalSemicolonOfUsingOrExtern(SyntaxNode directive, SyntaxToken token); + protected abstract Task ShouldProvideParenthesisCompletionAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken); // For telemetry reporting protected abstract void LogCommit(); @@ -108,13 +110,23 @@ internal override async Task GetChangeAsync(Document document, { LogCommit(); var containingNamespace = ImportCompletionItem.GetContainingNamespace(completionItem); + var provideParenthesisCompletion = await ShouldProvideParenthesisCompletionAsync( + document, + completionItem, + commitKey, + cancellationToken).ConfigureAwait(false); + + var insertText = completionItem.DisplayText; + if (provideParenthesisCompletion) + { + insertText += "()"; + CompletionProvidersLogger.LogCommitUsingSemicolonToAddParenthesis(); + } if (await ShouldCompleteWithFullyQualifyTypeName().ConfigureAwait(false)) { - var fullyQualifiedName = $"{containingNamespace}.{completionItem.DisplayText}"; - var change = new TextChange(completionListSpan, fullyQualifiedName); - - return CompletionChange.Create(change); + var completionText = $"{containingNamespace}.{insertText}"; + return CompletionChange.Create(new TextChange(completionListSpan, completionText)); } // Find context node so we can use it to decide where to insert using/imports. @@ -122,15 +134,15 @@ internal override async Task GetChangeAsync(Document document, var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var addImportContextNode = root.FindToken(completionListSpan.Start, findInsideTrivia: true).Parent; - // Add required using/imports directive. + // Add required using/imports directive. var addImportService = document.GetRequiredLanguageService(); var generator = document.GetRequiredLanguageService(); var optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var placeSystemNamespaceFirst = optionSet.GetOption(GenerationOptions.PlaceSystemNamespaceFirst, document.Project.Language); var allowInHiddenRegions = document.CanAddImportsInHiddenRegions(); - var compilation = await document.Project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var importNode = CreateImport(document, containingNamespace); + var compilation = await document.Project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var rootWithImport = addImportService.AddImport(compilation, root, addImportContextNode!, importNode, generator, placeSystemNamespaceFirst, allowInHiddenRegions, cancellationToken); var documentWithImport = document.WithSyntaxRoot(rootWithImport); // This only formats the annotated import we just added, not the entire document. @@ -154,13 +166,13 @@ internal override async Task GetChangeAsync(Document document, // above, we will get a TextChange of "AsnEncodedDat" with 0 length span, instead of a change of // the full display text with a span of length 1. This will later mess up span-tracking and end up // with "AsnEncodedDatasd" in the code. - builder.Add(new TextChange(completionListSpan, completionItem.DisplayText)); + builder.Add(new TextChange(completionListSpan, insertText)); // Then get the combined change var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var newText = text.WithChanges(builder); - - return CompletionChange.Create(Utilities.Collapse(newText, builder.ToImmutableAndFree())); + var change = Utilities.Collapse(newText, builder.ToImmutableAndFree()); + return CompletionChange.Create(change); async Task ShouldCompleteWithFullyQualifyTypeName() { diff --git a/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/ImportCompletionItem.cs b/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/ImportCompletionItem.cs index 17497e1d2c014..37a4cabe67202 100644 --- a/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/ImportCompletionItem.cs +++ b/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/ImportCompletionItem.cs @@ -59,7 +59,7 @@ public static CompletionItem Create( // Use " " as sort text. The space before namespace makes items with identical display name // but from different namespace all show up in the list, it also makes sure item with shorter name shows first, - // e.g. 'SomeType` before 'SomeTypeWithLongerName'. + // e.g. 'SomeType` before 'SomeTypeWithLongerName'. var sortTextBuilder = PooledStringBuilder.GetInstance(); sortTextBuilder.Builder.AppendFormat(SortTextFormat, name, containingNamespace); @@ -158,13 +158,13 @@ private static (ISymbol? symbol, int overloadCount) GetSymbolAndOverloadCount(Co return default; } - // Otherwise, this is a type item, so we don't have SymbolKey data. But we should still have all + // Otherwise, this is a type item, so we don't have SymbolKey data. But we should still have all // the data to construct its full metadata name var containingNamespace = GetContainingNamespace(item); var typeName = item.Properties.TryGetValue(AttributeFullName, out var attributeFullName) ? attributeFullName : item.DisplayText; var fullyQualifiedName = GetFullyQualifiedName(containingNamespace, typeName); - // We choose not to display the number of "type overloads" for simplicity. + // We choose not to display the number of "type overloads" for simplicity. // Otherwise, we need additional logic to track internal and public visible // types separately, and cache both completion items. if (item.Properties.TryGetValue(TypeAritySuffixName, out var aritySuffix)) diff --git a/src/Features/Core/Portable/Completion/Providers/SymbolCompletionItem.cs b/src/Features/Core/Portable/Completion/Providers/SymbolCompletionItem.cs index de4cc1a316d8f..33330c87dd3c5 100644 --- a/src/Features/Core/Portable/Completion/Providers/SymbolCompletionItem.cs +++ b/src/Features/Core/Portable/Completion/Providers/SymbolCompletionItem.cs @@ -67,7 +67,6 @@ public static CompletionItem AddSymbolInfo(IReadOnlyList symbols, Compl { var symbol = symbols[0]; var isGeneric = symbol.GetArity() > 0; - item = item .AddProperty("SymbolKind", ((int)symbol.Kind).ToString()) .AddProperty("SymbolName", symbol.Name); @@ -75,6 +74,19 @@ public static CompletionItem AddSymbolInfo(IReadOnlyList symbols, Compl return isGeneric ? item.AddProperty("IsGeneric", isGeneric.ToString()) : item; } + public static CompletionItem AddShouldProvideParenthesisCompletion(CompletionItem item) + => item.AddProperty("ShouldProvideParenthesisCompletion", true.ToString()); + + public static bool GetShouldProvideParenthesisCompletion(CompletionItem item) + { + if (item.Properties.TryGetValue("ShouldProvideParenthesisCompletion", out _)) + { + return true; + } + + return false; + } + public static string EncodeSymbols(IReadOnlyList symbols) { if (symbols.Count > 1) diff --git a/src/Features/Core/Portable/Diagnostics/AnalyzerHelper.cs b/src/Features/Core/Portable/Diagnostics/AnalyzerHelper.cs index ca930aaebaaec..0cae834bc7ed4 100644 --- a/src/Features/Core/Portable/Diagnostics/AnalyzerHelper.cs +++ b/src/Features/Core/Portable/Diagnostics/AnalyzerHelper.cs @@ -32,6 +32,7 @@ internal static partial class AnalyzerHelper internal const string WRN_UnableToLoadAnalyzerIdCS = "CS8034"; internal const string WRN_UnableToLoadAnalyzerIdVB = "BC42378"; internal const string WRN_AnalyzerReferencesNetFrameworkIdCS = "CS8850"; + internal const string WRN_AnalyzerReferencesNetFrameworkIdVB = "BC42503"; // Shared with Compiler internal const string AnalyzerExceptionDiagnosticId = "AD0001"; @@ -202,7 +203,7 @@ static string GetLanguageSpecificId(string? language, string noLanguageId, strin break; case AnalyzerLoadFailureEventArgs.FailureErrorCode.ReferencesFramework: - id = GetLanguageSpecificId(language, WRN_AnalyzerReferencesNetFrameworkId, WRN_AnalyzerReferencesNetFrameworkIdCS, WRN_AnalyzerReferencesNetFrameworkId /*Not supported by VB*/); + id = GetLanguageSpecificId(language, WRN_AnalyzerReferencesNetFrameworkId, WRN_AnalyzerReferencesNetFrameworkIdCS, WRN_AnalyzerReferencesNetFrameworkIdVB); messageFormat = FeaturesResources.The_assembly_0_containing_type_1_references_NET_Framework; message = string.Format(FeaturesResources.The_assembly_0_containing_type_1_references_NET_Framework, fullPath, e.TypeName); break; diff --git a/src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/AbstractRegexDiagnosticAnalyzer.cs b/src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/AbstractRegexDiagnosticAnalyzer.cs index e12c1da0dde88..dd28c002b71c9 100644 --- a/src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/AbstractRegexDiagnosticAnalyzer.cs +++ b/src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/AbstractRegexDiagnosticAnalyzer.cs @@ -50,7 +50,7 @@ public void Analyze(SemanticModelAnalysisContext context) return; } - var detector = RegexPatternDetector.TryGetOrCreate(semanticModel, _info); + var detector = RegexPatternDetector.TryGetOrCreate(semanticModel.Compilation, _info); if (detector == null) { return; @@ -86,7 +86,7 @@ private void AnalyzeToken( { if (token.RawKind == _info.StringLiteralTokenKind) { - var tree = detector.TryParseRegexPattern(token, cancellationToken); + var tree = detector.TryParseRegexPattern(token, context.SemanticModel, cancellationToken); if (tree != null) { foreach (var diag in tree.Diagnostics) diff --git a/src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/LanguageServices/RegexPatternDetector.cs b/src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/LanguageServices/RegexPatternDetector.cs index 1569629158790..fa34e1b62205c 100644 --- a/src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/LanguageServices/RegexPatternDetector.cs +++ b/src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/LanguageServices/RegexPatternDetector.cs @@ -27,15 +27,13 @@ internal sealed class RegexPatternDetector private const string _patternName = "pattern"; /// - /// Cache so that we can reuse the same when analyzing a particular semantic - /// model. This saves the time from having to recreate this for every string literal that features examine for - /// a particular semantic model. + /// Cache so that we can reuse the same when analyzing a particular + /// compilation model. This saves the time from having to recreate this for every string literal that features + /// examine for a particular compilation. /// - private static readonly ConditionalWeakTable _modelToDetector = - new(); + private static readonly ConditionalWeakTable _modelToDetector = new(); private readonly EmbeddedLanguageInfo _info; - private readonly SemanticModel _semanticModel; private readonly INamedTypeSymbol _regexType; private readonly HashSet _methodNamesOfInterest; @@ -59,42 +57,39 @@ internal sealed class RegexPatternDetector .ToDictionary(f => f.Name, f => (RegexOptions)f.GetValue(null), StringComparer.OrdinalIgnoreCase); public RegexPatternDetector( - SemanticModel semanticModel, EmbeddedLanguageInfo info, INamedTypeSymbol regexType, HashSet methodNamesOfInterest) { _info = info; - _semanticModel = semanticModel; _regexType = regexType; _methodNamesOfInterest = methodNamesOfInterest; } public static RegexPatternDetector TryGetOrCreate( - SemanticModel semanticModel, EmbeddedLanguageInfo info) + Compilation compilation, EmbeddedLanguageInfo info) { // Do a quick non-allocating check first. - if (_modelToDetector.TryGetValue(semanticModel, out var detector)) + if (_modelToDetector.TryGetValue(compilation, out var detector)) { return detector; } return _modelToDetector.GetValue( - semanticModel, _ => TryCreate(semanticModel, info)); + compilation, _ => TryCreate(compilation, info)); } private static RegexPatternDetector TryCreate( - SemanticModel semanticModel, EmbeddedLanguageInfo info) + Compilation compilation, EmbeddedLanguageInfo info) { - var regexType = semanticModel.Compilation.GetTypeByMetadataName(typeof(Regex).FullName); + var regexType = compilation.GetTypeByMetadataName(typeof(Regex).FullName); if (regexType == null) { return null; } var methodNamesOfInterest = GetMethodNamesOfInterest(regexType, info.SyntaxFacts); - return new RegexPatternDetector( - semanticModel, info, regexType, methodNamesOfInterest); + return new RegexPatternDetector(info, regexType, methodNamesOfInterest); } public static bool IsPossiblyPatternToken(SyntaxToken token, ISyntaxFacts syntaxFacts) @@ -217,7 +212,7 @@ where method.Parameters.Any(p => p.Name == _patternName) return result; } - public bool IsRegexPattern(SyntaxToken token, CancellationToken cancellationToken, out RegexOptions options) + public bool IsRegexPattern(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out RegexOptions options) { options = default; if (!IsPossiblyPatternToken(token, _info.SyntaxFacts)) @@ -249,16 +244,16 @@ public bool IsRegexPattern(SyntaxToken token, CancellationToken cancellationToke // Note we do not use GetAllSymbols here because we don't want to incur the // allocation. - var symbolInfo = _semanticModel.GetSymbolInfo(invocationOrCreation, cancellationToken); + var symbolInfo = semanticModel.GetSymbolInfo(invocationOrCreation, cancellationToken); var method = symbolInfo.Symbol; - if (TryAnalyzeInvocation(argumentNode, method, cancellationToken, out options)) + if (TryAnalyzeInvocation(argumentNode, semanticModel, method, cancellationToken, out options)) { return true; } foreach (var candidate in symbolInfo.CandidateSymbols) { - if (TryAnalyzeInvocation(argumentNode, candidate, cancellationToken, out options)) + if (TryAnalyzeInvocation(argumentNode, semanticModel, candidate, cancellationToken, out options)) { return true; } @@ -273,24 +268,24 @@ public bool IsRegexPattern(SyntaxToken token, CancellationToken cancellationToke { if (syntaxFacts.StringComparer.Compare(nameof(Regex), name) == 0) { - var constructor = _semanticModel.GetSymbolInfo(invocationOrCreation, cancellationToken).GetAnySymbol(); + var constructor = semanticModel.GetSymbolInfo(invocationOrCreation, cancellationToken).GetAnySymbol(); if (_regexType.Equals(constructor?.ContainingType)) { // Argument to "new Regex". Need to do deeper analysis return AnalyzeStringLiteral( - argumentNode, cancellationToken, out options); + argumentNode, semanticModel, cancellationToken, out options); } } } } else if (syntaxFacts.IsImplicitObjectCreationExpression(invocationOrCreation)) { - var constructor = _semanticModel.GetSymbolInfo(invocationOrCreation, cancellationToken).GetAnySymbol(); + var constructor = semanticModel.GetSymbolInfo(invocationOrCreation, cancellationToken).GetAnySymbol(); if (_regexType.Equals(constructor?.ContainingType)) { // Argument to "new Regex". Need to do deeper analysis return AnalyzeStringLiteral( - argumentNode, cancellationToken, out options); + argumentNode, semanticModel, cancellationToken, out options); } } @@ -298,7 +293,7 @@ public bool IsRegexPattern(SyntaxToken token, CancellationToken cancellationToke } private bool TryAnalyzeInvocation( - SyntaxNode argumentNode, ISymbol method, + SyntaxNode argumentNode, SemanticModel semanticModel, ISymbol method, CancellationToken cancellationToken, out RegexOptions options) { if (method != null && @@ -307,16 +302,16 @@ private bool TryAnalyzeInvocation( _regexType.Equals(method.ContainingType)) { return AnalyzeStringLiteral( - argumentNode, cancellationToken, out options); + argumentNode, semanticModel, cancellationToken, out options); } options = default; return false; } - public RegexTree TryParseRegexPattern(SyntaxToken token, CancellationToken cancellationToken) + public RegexTree TryParseRegexPattern(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken) { - if (!this.IsRegexPattern(token, cancellationToken, out var options)) + if (!this.IsRegexPattern(token, semanticModel, cancellationToken, out var options)) { return null; } @@ -327,22 +322,23 @@ public RegexTree TryParseRegexPattern(SyntaxToken token, CancellationToken cance private bool AnalyzeStringLiteral( SyntaxNode argumentNode, + SemanticModel semanticModel, CancellationToken cancellationToken, out RegexOptions options) { options = default; - var parameter = _info.SemanticFacts.FindParameterForArgument(_semanticModel, argumentNode, cancellationToken); + var parameter = _info.SemanticFacts.FindParameterForArgument(semanticModel, argumentNode, cancellationToken); if (parameter?.Name != _patternName) { return false; } - options = GetRegexOptions(argumentNode, cancellationToken); + options = GetRegexOptions(argumentNode, semanticModel, cancellationToken); return true; } - private RegexOptions GetRegexOptions(SyntaxNode argumentNode, CancellationToken cancellationToken) + private RegexOptions GetRegexOptions(SyntaxNode argumentNode, SemanticModel semanticModel, CancellationToken cancellationToken) { var syntaxFacts = _info.SyntaxFacts; var argumentList = argumentNode.Parent; @@ -354,10 +350,10 @@ private RegexOptions GetRegexOptions(SyntaxNode argumentNode, CancellationToken var expr = syntaxFacts.GetExpressionOfArgument(siblingArg); if (expr != null) { - var exprType = _semanticModel.GetTypeInfo(expr, cancellationToken); + var exprType = semanticModel.GetTypeInfo(expr, cancellationToken); if (exprType.Type?.Name == nameof(RegexOptions)) { - var constVal = _semanticModel.GetConstantValue(expr, cancellationToken); + var constVal = semanticModel.GetConstantValue(expr, cancellationToken); if (constVal.HasValue) { return (RegexOptions)(int)constVal.Value; diff --git a/src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/LanguageServices/RegexSyntaxClassifier.cs b/src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/LanguageServices/RegexSyntaxClassifier.cs index 03620a9f7e22c..7d5dcde3a14ae 100644 --- a/src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/LanguageServices/RegexSyntaxClassifier.cs +++ b/src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/LanguageServices/RegexSyntaxClassifier.cs @@ -56,8 +56,8 @@ public override void AddClassifications( return; } - var detector = RegexPatternDetector.TryGetOrCreate(semanticModel, _info); - var tree = detector?.TryParseRegexPattern(token, cancellationToken); + var detector = RegexPatternDetector.TryGetOrCreate(semanticModel.Compilation, _info); + var tree = detector?.TryParseRegexPattern(token, semanticModel, cancellationToken); if (tree == null) { return; diff --git a/src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/RegexEmbeddedLanguage.cs b/src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/RegexEmbeddedLanguage.cs index 16add99f15b45..92591a94af188 100644 --- a/src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/RegexEmbeddedLanguage.cs +++ b/src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/RegexEmbeddedLanguage.cs @@ -50,8 +50,8 @@ public RegexEmbeddedLanguage( return default; var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); - var detector = RegexPatternDetector.TryGetOrCreate(semanticModel, this.Info); - var tree = detector?.TryParseRegexPattern(token, cancellationToken); + var detector = RegexPatternDetector.TryGetOrCreate(semanticModel.Compilation, this.Info); + var tree = detector?.TryParseRegexPattern(token, semanticModel, cancellationToken); return tree == null ? default : (tree, token); } diff --git a/src/Features/Core/Portable/FindUsages/IRemoteFindUsagesService.cs b/src/Features/Core/Portable/FindUsages/IRemoteFindUsagesService.cs index 07416ea752a79..bb0120eb78077 100644 --- a/src/Features/Core/Portable/FindUsages/IRemoteFindUsagesService.cs +++ b/src/Features/Core/Portable/FindUsages/IRemoteFindUsagesService.cs @@ -2,19 +2,17 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable - using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; -using System.Linq; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; +using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; @@ -110,21 +108,39 @@ public ValueTask ReportProgressAsync(int current, int maximum) public ValueTask SetSearchTitleAsync(string title) => _context.SetSearchTitleAsync(title); - public ValueTask OnDefinitionFoundAsync(SerializableDefinitionItem definition) + public async ValueTask OnDefinitionFoundAsync(SerializableDefinitionItem definition) { - var id = definition.Id; - var rehydrated = definition.Rehydrate(_solution); + try + { + var id = definition.Id; + var rehydrated = await definition.RehydrateAsync(_solution, _context.CancellationToken).ConfigureAwait(false); - lock (_idToDefinition) + lock (_idToDefinition) + { + _idToDefinition.Add(id, rehydrated); + } + + await _context.OnDefinitionFoundAsync(rehydrated).ConfigureAwait(false); + } + catch (OperationCanceledException oce) when (oce.CancellationToken == _context.CancellationToken) { - _idToDefinition.Add(id, rehydrated); + // Eat the cancellation exception since we're unsure if it's safe to propagate back to the remote side } - - return _context.OnDefinitionFoundAsync(rehydrated); } - public ValueTask OnReferenceFoundAsync(SerializableSourceReferenceItem reference) - => _context.OnReferenceFoundAsync(reference.Rehydrate(_solution, GetDefinition(reference.DefinitionId))); + public async ValueTask OnReferenceFoundAsync(SerializableSourceReferenceItem reference) + { + try + { + var rehydrated = await reference.RehydrateAsync(_solution, GetDefinition(reference.DefinitionId), _context.CancellationToken).ConfigureAwait(false); + + await _context.OnReferenceFoundAsync(rehydrated).ConfigureAwait(false); + } + catch (OperationCanceledException oce) when (oce.CancellationToken == _context.CancellationToken) + { + // Eat the cancellation exception since we're unsure if it's safe to propagate back to the remote side + } + } private DefinitionItem GetDefinition(int definitionId) { @@ -154,8 +170,13 @@ public SerializableDocumentSpan(DocumentId documentId, TextSpan sourceSpan) public static SerializableDocumentSpan Dehydrate(DocumentSpan documentSpan) => new(documentSpan.Document.Id, documentSpan.SourceSpan); - public DocumentSpan Rehydrate(Solution solution) - => new(solution.GetDocument(DocumentId), SourceSpan); + public async ValueTask RehydrateAsync(Solution solution, CancellationToken cancellationToken) + { + var document = solution.GetDocument(DocumentId) ?? + await solution.GetSourceGeneratedDocumentAsync(DocumentId, cancellationToken).ConfigureAwait(false); + Contract.ThrowIfNull(document); + return new DocumentSpan(document, SourceSpan); + } } [DataContract] @@ -221,16 +242,21 @@ public static SerializableDefinitionItem Dehydrate(int id, DefinitionItem item) item.DisplayableProperties, item.DisplayIfNoReferences); - public DefinitionItem Rehydrate(Solution solution) - => new DefinitionItem.DefaultDefinitionItem( + public async ValueTask RehydrateAsync(Solution solution, CancellationToken cancellationToken) + { + var sourceSpansTasks = SourceSpans.SelectAsArray(ss => ss.RehydrateAsync(solution, cancellationToken).AsTask()); + var sourceSpans = await Task.WhenAll(sourceSpansTasks).ConfigureAwait(false); + + return new DefinitionItem.DefaultDefinitionItem( Tags, DisplayParts, NameDisplayParts, OriginationParts, - SourceSpans.SelectAsArray(ss => ss.Rehydrate(solution)), + sourceSpans.ToImmutableArray(), Properties, DisplayableProperties, DisplayIfNoReferences); + } } [DataContract] @@ -266,9 +292,9 @@ public static SerializableSourceReferenceItem Dehydrate(int definitionId, Source item.SymbolUsageInfo, item.AdditionalProperties); - public SourceReferenceItem Rehydrate(Solution solution, DefinitionItem definition) + public async Task RehydrateAsync(Solution solution, DefinitionItem definition, CancellationToken cancellationToken) => new(definition, - SourceSpan.Rehydrate(solution), + await SourceSpan.RehydrateAsync(solution, cancellationToken).ConfigureAwait(false), SymbolUsageInfo, AdditionalProperties.ToImmutableDictionary(t => t.Key, t => t.Value)); } diff --git a/src/Features/Core/Portable/GenerateMember/AbstractGenerateMemberService.cs b/src/Features/Core/Portable/GenerateMember/AbstractGenerateMemberService.cs index 495a7e24cfb2c..e4fb57fbc600e 100644 --- a/src/Features/Core/Portable/GenerateMember/AbstractGenerateMemberService.cs +++ b/src/Features/Core/Portable/GenerateMember/AbstractGenerateMemberService.cs @@ -154,7 +154,7 @@ private static void TryDetermineTypeToGenerateInWorker( return; } - if (syntaxFacts.IsObjectInitializerNamedAssignmentIdentifier( + if (syntaxFacts.IsMemberInitializerNamedAssignmentIdentifier( expression, out var initializedObject)) { typeToGenerateIn = semanticModel.GetTypeInfo(initializedObject, cancellationToken).Type as INamedTypeSymbol; diff --git a/src/Features/Core/Portable/GenerateMember/GenerateVariable/AbstractGenerateVariableService.State.cs b/src/Features/Core/Portable/GenerateMember/GenerateVariable/AbstractGenerateVariableService.State.cs index e5d1ac53a5471..c7c76d9ae1d1f 100644 --- a/src/Features/Core/Portable/GenerateMember/GenerateVariable/AbstractGenerateVariableService.State.cs +++ b/src/Features/Core/Portable/GenerateMember/GenerateVariable/AbstractGenerateVariableService.State.cs @@ -276,7 +276,7 @@ private bool TryInitializeSimpleName( IsInConstructor = DetermineIsInConstructor(semanticDocument, simpleName); IsInMemberContext = simpleName != SimpleNameOrMemberAccessExpressionOpt || - syntaxFacts.IsObjectInitializerNamedAssignmentIdentifier(SimpleNameOrMemberAccessExpressionOpt); + syntaxFacts.IsMemberInitializerNamedAssignmentIdentifier(SimpleNameOrMemberAccessExpressionOpt); ContainingMethod = semanticModel.GetEnclosingSymbol(IdentifierToken.SpanStart, cancellationToken); diff --git a/src/Features/Core/Portable/ReplacePropertyWithMethods/ReplacePropertyWithMethodsCodeRefactoringProvider.cs b/src/Features/Core/Portable/ReplacePropertyWithMethods/ReplacePropertyWithMethodsCodeRefactoringProvider.cs index b7bc55e02dc4b..26ba3f8e13cc1 100644 --- a/src/Features/Core/Portable/ReplacePropertyWithMethods/ReplacePropertyWithMethodsCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/ReplacePropertyWithMethods/ReplacePropertyWithMethodsCodeRefactoringProvider.cs @@ -262,7 +262,7 @@ private static async Task ReplaceReferencesAsync( editor.ReplaceNode(parent, parent.WithAdditionalAnnotations( ConflictAnnotation.Create(FeaturesResources.Property_referenced_implicitly))); } - else if (syntaxFacts.IsObjectInitializerNamedAssignmentIdentifier(parent)) + else if (syntaxFacts.IsMemberInitializerNamedAssignmentIdentifier(parent)) { editor.ReplaceNode(parent, parent.WithAdditionalAnnotations( ConflictAnnotation.Create(FeaturesResources.Property_reference_cannot_be_updated))); diff --git a/src/Features/Core/Portable/Structure/BlockStructureContext.cs b/src/Features/Core/Portable/Structure/BlockStructureContext.cs index 34d208e913dcd..0039d87e3c1bf 100644 --- a/src/Features/Core/Portable/Structure/BlockStructureContext.cs +++ b/src/Features/Core/Portable/Structure/BlockStructureContext.cs @@ -13,14 +13,16 @@ internal class BlockStructureContext { private readonly ImmutableArray.Builder _spans = ImmutableArray.CreateBuilder(); - public Document Document { get; } + public SyntaxTree SyntaxTree { get; } + public BlockStructureOptionProvider OptionProvider { get; } public CancellationToken CancellationToken { get; } internal ImmutableArray Spans => _spans.ToImmutable(); - public BlockStructureContext(Document document, CancellationToken cancellationToken) + public BlockStructureContext(SyntaxTree syntaxTree, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { - Document = document; + SyntaxTree = syntaxTree; + OptionProvider = optionProvider; CancellationToken = cancellationToken; } diff --git a/src/Features/Core/Portable/Structure/BlockStructureOptionProvider.cs b/src/Features/Core/Portable/Structure/BlockStructureOptionProvider.cs new file mode 100644 index 0000000000000..b593d68af9794 --- /dev/null +++ b/src/Features/Core/Portable/Structure/BlockStructureOptionProvider.cs @@ -0,0 +1,24 @@ +// Licensed to the .NET Foundation under one or more 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.Options; + +namespace Microsoft.CodeAnalysis.Structure +{ + internal sealed class BlockStructureOptionProvider + { + private readonly OptionSet _options; + + public BlockStructureOptionProvider(OptionSet options, bool isMetadataAsSource) + { + _options = options; + IsMetadataAsSource = isMetadataAsSource; + } + + public bool IsMetadataAsSource { get; } + + public T GetOption(PerLanguageOption2 option, string language) + => _options.GetOption(option, language); + } +} diff --git a/src/Features/Core/Portable/Structure/BlockStructureService.cs b/src/Features/Core/Portable/Structure/BlockStructureService.cs index 0bf25f7a50d11..6ff70586b8699 100644 --- a/src/Features/Core/Portable/Structure/BlockStructureService.cs +++ b/src/Features/Core/Portable/Structure/BlockStructureService.cs @@ -29,7 +29,7 @@ public static BlockStructureService GetService(Document document) /// /// Gets the for the provided document. Note that the - /// default implementation works by calling into + /// default implementation works by calling into /// and blocking on the async operation. Subclasses should provide more efficient /// implementations that do not block on async operations if possible. /// diff --git a/src/Features/Core/Portable/Structure/BlockStructureServiceWithProviders.cs b/src/Features/Core/Portable/Structure/BlockStructureServiceWithProviders.cs index e75a795804d62..45cc428bf07e6 100644 --- a/src/Features/Core/Portable/Structure/BlockStructureServiceWithProviders.cs +++ b/src/Features/Core/Portable/Structure/BlockStructureServiceWithProviders.cs @@ -9,7 +9,9 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Structure { @@ -44,10 +46,64 @@ private ImmutableArray GetImportedProviders() } public override async Task GetBlockStructureAsync( - Document document, CancellationToken cancellationToken) + Document document, + CancellationToken cancellationToken) { - var context = new BlockStructureContext(document, cancellationToken); - foreach (var provider in _providers) + var context = await CreateContextAsync(document, cancellationToken).ConfigureAwait(false); + return await GetBlockStructureAsync(context, _providers).ConfigureAwait(false); + } + + public override BlockStructure GetBlockStructure( + Document document, + CancellationToken cancellationToken) + { + var context = CreateContextAsync(document, cancellationToken).WaitAndGetResult(cancellationToken); + return GetBlockStructure(context, _providers); + } + + public async Task GetBlockStructureAsync( + SyntaxTree syntaxTree, + OptionSet options, + bool isMetadataAsSource, + CancellationToken cancellationToken) + { + var context = CreateContext(syntaxTree, options, isMetadataAsSource, cancellationToken); + return await GetBlockStructureAsync(context, _providers).ConfigureAwait(false); + } + + public BlockStructure GetBlockStructure( + SyntaxTree syntaxTree, + OptionSet options, + bool isMetadataAsSource, + CancellationToken cancellationToken) + { + var context = CreateContext(syntaxTree, options, isMetadataAsSource, cancellationToken); + return GetBlockStructure(context, _providers); + } + + private static async Task CreateContextAsync(Document document, CancellationToken cancellationToken) + { + var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); + var options = document.Project.Solution.Options; + var isMetadataAsSource = document.Project.Solution.Workspace.Kind == WorkspaceKind.MetadataAsSource; + return CreateContext(syntaxTree, options, isMetadataAsSource, cancellationToken); + } + + private static BlockStructureContext CreateContext( + SyntaxTree syntaxTree, + OptionSet options, + bool isMetadataAsSource, + CancellationToken cancellationToken) + { + var optionProvider = new BlockStructureOptionProvider(options, isMetadataAsSource); + return new BlockStructureContext(syntaxTree, optionProvider, cancellationToken); + } + + private static async Task GetBlockStructureAsync( + BlockStructureContext context, + ImmutableArray providers) + { + foreach (var provider in providers) { await provider.ProvideBlockStructureAsync(context).ConfigureAwait(false); } @@ -55,11 +111,11 @@ public override async Task GetBlockStructureAsync( return CreateBlockStructure(context); } - public override BlockStructure GetBlockStructure( - Document document, CancellationToken cancellationToken) + private static BlockStructure GetBlockStructure( + BlockStructureContext context, + ImmutableArray providers) { - var context = new BlockStructureContext(document, cancellationToken); - foreach (var provider in _providers) + foreach (var provider in providers) { provider.ProvideBlockStructure(context); } @@ -69,15 +125,14 @@ public override BlockStructure GetBlockStructure( private static BlockStructure CreateBlockStructure(BlockStructureContext context) { - var options = context.Document.Project.Solution.Workspace.Options; - var language = context.Document.Project.Language; - - var showIndentGuidesForCodeLevelConstructs = options.GetOption(BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, language); - var showIndentGuidesForDeclarationLevelConstructs = options.GetOption(BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, language); - var showIndentGuidesForCommentsAndPreprocessorRegions = options.GetOption(BlockStructureOptions.ShowBlockStructureGuidesForCommentsAndPreprocessorRegions, language); - var showOutliningForCodeLevelConstructs = options.GetOption(BlockStructureOptions.ShowOutliningForCodeLevelConstructs, language); - var showOutliningForDeclarationLevelConstructs = options.GetOption(BlockStructureOptions.ShowOutliningForDeclarationLevelConstructs, language); - var showOutliningForCommentsAndPreprocessorRegions = options.GetOption(BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions, language); + var language = context.SyntaxTree.Options.Language; + + var showIndentGuidesForCodeLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, language); + var showIndentGuidesForDeclarationLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, language); + var showIndentGuidesForCommentsAndPreprocessorRegions = context.OptionProvider.GetOption(BlockStructureOptions.ShowBlockStructureGuidesForCommentsAndPreprocessorRegions, language); + var showOutliningForCodeLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowOutliningForCodeLevelConstructs, language); + var showOutliningForDeclarationLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowOutliningForDeclarationLevelConstructs, language); + var showOutliningForCommentsAndPreprocessorRegions = context.OptionProvider.GetOption(BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions, language); using var _ = ArrayBuilder.GetInstance(out var updatedSpans); foreach (var span in context.Spans) diff --git a/src/Features/Core/Portable/Structure/Syntax/AbstractBlockStructureProvider.cs b/src/Features/Core/Portable/Structure/Syntax/AbstractBlockStructureProvider.cs index 7c58f0873fe1b..890605016397c 100644 --- a/src/Features/Core/Portable/Structure/Syntax/AbstractBlockStructureProvider.cs +++ b/src/Features/Core/Portable/Structure/Syntax/AbstractBlockStructureProvider.cs @@ -37,7 +37,7 @@ public override void ProvideBlockStructure(BlockStructureContext context) { try { - var syntaxRoot = context.Document.GetSyntaxRootSynchronously(context.CancellationToken); + var syntaxRoot = context.SyntaxTree.GetRoot(context.CancellationToken); ProvideBlockStructureWorker(context, syntaxRoot); } @@ -54,7 +54,7 @@ public override async Task ProvideBlockStructureAsync(BlockStructureContext cont { try { - var syntaxRoot = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); + var syntaxRoot = await context.SyntaxTree.GetRootAsync(context.CancellationToken).ConfigureAwait(false); ProvideBlockStructureWorker(context, syntaxRoot); } @@ -69,7 +69,7 @@ private void ProvideBlockStructureWorker( { using var _ = ArrayBuilder.GetInstance(out var spans); BlockSpanCollector.CollectBlockSpans( - context.Document, syntaxRoot, _nodeProviderMap, _triviaProviderMap, spans, context.CancellationToken); + syntaxRoot, context.OptionProvider, _nodeProviderMap, _triviaProviderMap, spans, context.CancellationToken); foreach (var span in spans) { diff --git a/src/Features/Core/Portable/Structure/Syntax/AbstractSyntaxNodeStructureProvider.cs b/src/Features/Core/Portable/Structure/Syntax/AbstractSyntaxNodeStructureProvider.cs index a80e735805322..7327d60e20a43 100644 --- a/src/Features/Core/Portable/Structure/Syntax/AbstractSyntaxNodeStructureProvider.cs +++ b/src/Features/Core/Portable/Structure/Syntax/AbstractSyntaxNodeStructureProvider.cs @@ -6,7 +6,6 @@ using System; using System.Threading; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Structure @@ -15,40 +14,28 @@ internal abstract class AbstractSyntaxNodeStructureProvider : Abstr where TSyntaxNode : SyntaxNode { public sealed override void CollectBlockSpans( - Document document, - SyntaxNode node, - ArrayBuilder spans, - CancellationToken cancellationToken) - { - var isMetadataAsSource = document.Project.Solution.Workspace.Kind == WorkspaceKind.MetadataAsSource; - var options = document.Project.Solution.Options; - CollectBlockSpans(node, spans, isMetadataAsSource, options, cancellationToken); - } - - public sealed override void CollectBlockSpans( - Document document, SyntaxTrivia trivia, ArrayBuilder spans, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { throw new NotSupportedException(); } - private void CollectBlockSpans( + public sealed override void CollectBlockSpans( SyntaxNode node, ArrayBuilder spans, - bool isMetadataAsSource, - OptionSet options, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { if (node is TSyntaxNode tSyntax) { - CollectBlockSpans(tSyntax, spans, isMetadataAsSource, options, cancellationToken); + CollectBlockSpans(tSyntax, spans, optionProvider, cancellationToken); } } protected abstract void CollectBlockSpans( TSyntaxNode node, ArrayBuilder spans, - bool isMetadataAsSource, OptionSet options, CancellationToken cancellationToken); + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken); } } diff --git a/src/Features/Core/Portable/Structure/Syntax/AbstractSyntaxStructureProvider.cs b/src/Features/Core/Portable/Structure/Syntax/AbstractSyntaxStructureProvider.cs index de718d4fec93d..0bb36c11b7a53 100644 --- a/src/Features/Core/Portable/Structure/Syntax/AbstractSyntaxStructureProvider.cs +++ b/src/Features/Core/Portable/Structure/Syntax/AbstractSyntaxStructureProvider.cs @@ -12,15 +12,15 @@ namespace Microsoft.CodeAnalysis.Structure internal abstract class AbstractSyntaxStructureProvider { public abstract void CollectBlockSpans( - Document document, SyntaxNode node, ArrayBuilder spans, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken); public abstract void CollectBlockSpans( - Document document, SyntaxTrivia trivia, ArrayBuilder spans, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken); } } diff --git a/src/Features/Core/Portable/Structure/Syntax/AbstractSyntaxTriviaStructureProvider.cs b/src/Features/Core/Portable/Structure/Syntax/AbstractSyntaxTriviaStructureProvider.cs index 27fa4f7b7f4eb..7379eb854cdc9 100644 --- a/src/Features/Core/Portable/Structure/Syntax/AbstractSyntaxTriviaStructureProvider.cs +++ b/src/Features/Core/Portable/Structure/Syntax/AbstractSyntaxTriviaStructureProvider.cs @@ -13,9 +13,9 @@ namespace Microsoft.CodeAnalysis.Structure internal abstract class AbstractSyntaxTriviaStructureProvider : AbstractSyntaxStructureProvider { public sealed override void CollectBlockSpans( - Document document, SyntaxNode node, ArrayBuilder spans, + BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { throw new NotSupportedException(); diff --git a/src/Features/Core/Portable/Structure/Syntax/BlockSpanCollector.cs b/src/Features/Core/Portable/Structure/Syntax/BlockSpanCollector.cs index 83fc2317ebea2..2cc54b9edc7db 100644 --- a/src/Features/Core/Portable/Structure/Syntax/BlockSpanCollector.cs +++ b/src/Features/Core/Portable/Structure/Syntax/BlockSpanCollector.cs @@ -13,20 +13,20 @@ namespace Microsoft.CodeAnalysis.Structure { internal class BlockSpanCollector { - private readonly Document _document; + private readonly BlockStructureOptionProvider _optionProvider; private readonly ImmutableDictionary> _nodeProviderMap; private readonly ImmutableDictionary> _triviaProviderMap; private readonly ArrayBuilder _spans; private readonly CancellationToken _cancellationToken; private BlockSpanCollector( - Document document, + BlockStructureOptionProvider optionProvider, ImmutableDictionary> nodeOutlinerMap, ImmutableDictionary> triviaOutlinerMap, ArrayBuilder spans, CancellationToken cancellationToken) { - _document = document; + _optionProvider = optionProvider; _nodeProviderMap = nodeOutlinerMap; _triviaProviderMap = triviaOutlinerMap; _spans = spans; @@ -34,14 +34,14 @@ private BlockSpanCollector( } public static void CollectBlockSpans( - Document document, SyntaxNode syntaxRoot, + BlockStructureOptionProvider optionProvider, ImmutableDictionary> nodeOutlinerMap, ImmutableDictionary> triviaOutlinerMap, ArrayBuilder spans, CancellationToken cancellationToken) { - var collector = new BlockSpanCollector(document, nodeOutlinerMap, triviaOutlinerMap, spans, cancellationToken); + var collector = new BlockSpanCollector(optionProvider, nodeOutlinerMap, triviaOutlinerMap, spans, cancellationToken); collector.Collect(syntaxRoot); } @@ -70,7 +70,7 @@ private void GetBlockSpans(SyntaxNode node) { _cancellationToken.ThrowIfCancellationRequested(); - provider.CollectBlockSpans(_document, node, _spans, _cancellationToken); + provider.CollectBlockSpans(node, _spans, _optionProvider, _cancellationToken); } } } @@ -92,7 +92,7 @@ private void GetOutliningSpans(SyntaxTriviaList triviaList) { _cancellationToken.ThrowIfCancellationRequested(); - provider.CollectBlockSpans(_document, trivia, _spans, _cancellationToken); + provider.CollectBlockSpans(trivia, _spans, _optionProvider, _cancellationToken); } } } diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.cs.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.cs.xlf index 86d263491f545..2623bba996db4 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.cs.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.cs.xlf @@ -162,7 +162,7 @@ Ujistěte se, že specifikátor tt použijete pro jazyky, pro které je nezbytn <infer> - <infer> + <vyvodit> @@ -172,7 +172,7 @@ Ujistěte se, že specifikátor tt použijete pro jazyky, pro které je nezbytn <omit> - <omit> + <vynechat> @@ -347,7 +347,7 @@ Ujistěte se, že specifikátor tt použijete pro jazyky, pro které je nezbytn Extract base class... - Extract base class... + Extrahovat základní třídu... @@ -502,12 +502,12 @@ Ujistěte se, že specifikátor tt použijete pro jazyky, pro které je nezbytn Inline '{0}' - Inline '{0}' + Inline refaktoring metody {0} Inline and keep '{0}' - Inline and keep '{0}' + Inline refaktoring metody {0} se zachováním deklarace @@ -607,17 +607,17 @@ Ujistěte se, že specifikátor tt použijete pro jazyky, pro které je nezbytn Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. - Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. + Když se upraví tělo funkce {0}, ladicí relace nebude moct pokračovat, protože tělo má příliš mnoho příkazů. Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} - Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} + Po změně těla funkce {0} nebude moct ladicí relace pokračovat z důvodu interní chyby: {1} Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. - Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. + Když se upraví zdrojový soubor {0}, ladicí relace nebude moct pokračovat, protože soubor je příliš velký. @@ -642,7 +642,7 @@ Ujistěte se, že specifikátor tt použijete pro jazyky, pro které je nezbytn Modifying source file '{0}' will prevent the debug session from continuing due to internal error: {1} - Po změně zdrojového souboru {0} nebude moct ladicí relace pokračovat z důvodu interní chyby: {1}. + Když se upraví zdrojový soubor {0}, ladicí relace nebude moct pokračovat kvůli vnitřní chybě: {1} @@ -652,7 +652,7 @@ Ujistěte se, že specifikátor tt použijete pro jazyky, pro které je nezbytn No valid location to insert method call. - No valid location to insert method call. + Není k dispozici žádné platné umístění, kam vložit volání metody. @@ -682,7 +682,7 @@ Ujistěte se, že specifikátor tt použijete pro jazyky, pro které je nezbytn Pull member(s) up to new base class... - Pull member(s) up to new base class... + Načíst členy do nové základní třídy... @@ -1013,7 +1013,7 @@ Ukotvení $ najde shodu s \n, ale nenajde shodu s \r\n (kombinace znaků návrat expression - expression + výraz @@ -1283,7 +1283,7 @@ Ukotvení $ najde shodu s \n, ale nenajde shodu s \r\n (kombinace znaků návrat name - name + název @@ -1383,7 +1383,7 @@ Je možné zřetězit dva nebo více rozsahů znaků. Pokud chcete například z no - no + ne @@ -1766,7 +1766,7 @@ Pokud je zadané chování kompatibilní s ECMAScriptem, je \w ekvivalentem [a-z yes - yes + ano @@ -1887,7 +1887,7 @@ Pozitivní kontrolní výrazy zpětného vyhledávání s nulovou délkou se obv The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. - The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + Sestavení {0}, které obsahuje typ {1}, se odkazuje na architekturu .NET Framework, což se nepodporuje. @@ -2092,22 +2092,22 @@ Pozitivní kontrolní výrazy zpětného vyhledávání s nulovou délkou se obv '{0}' cannot be null or empty. - Hodnota {0} nemůže být null nebo prázdná. + Hodnota {0} nemůže být nulová a toto pole nemůže být prázdné. '{0}' cannot be null or whitespace. - Hodnota {0} nemůže být null ani prázdný znak. + Hodnota {0} nemůže být null ani prázdný znak. '{0}' is not null here. - '{0}' is not null here. + {0} tady není null. '{0}' may be null here. - '{0}' may be null here. + {0} tady může být null. diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.de.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.de.xlf index 2e8472c16d36a..a2fddbcff93fa 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.de.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.de.xlf @@ -162,7 +162,7 @@ Stellen Sie sicher, dass Sie den Bezeichner "tt" für Sprachen verwenden, für d <infer> - <infer> + <ableiten> @@ -347,7 +347,7 @@ Stellen Sie sicher, dass Sie den Bezeichner "tt" für Sprachen verwenden, für d Extract base class... - Extract base class... + Basisklasse extrahieren... @@ -502,12 +502,12 @@ Stellen Sie sicher, dass Sie den Bezeichner "tt" für Sprachen verwenden, für d Inline '{0}' - Inline '{0}' + "{0}" inline einbinden Inline and keep '{0}' - Inline and keep '{0}' + "{0}" inline einbinden und beibehalten @@ -542,7 +542,7 @@ Stellen Sie sicher, dass Sie den Bezeichner "tt" für Sprachen verwenden, für d Make class 'abstract' - Make class 'abstract' + Klasse als "abstract" festlegen @@ -607,17 +607,17 @@ Stellen Sie sicher, dass Sie den Bezeichner "tt" für Sprachen verwenden, für d Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. - Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. + Durch Ändern des Texts von "{0}" wird die Fortsetzung der Debugsitzung verhindert, weil der Text zu viele Anweisungen enthält. Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} - Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} + Durch das Ändern des Texts von "{0}" wird die Fortsetzung der Debugsitzung aufgrund des folgenden internen Fehlers verhindert: {1}. Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. - Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. + Durch das Ändern der Quelldatei "{0}" wird die Fortsetzung der Debugsitzung verhindert, weil die Datei zu groß ist. @@ -642,7 +642,7 @@ Stellen Sie sicher, dass Sie den Bezeichner "tt" für Sprachen verwenden, für d Modifying source file '{0}' will prevent the debug session from continuing due to internal error: {1} - Durch das Ändern der Quelldatei "{0}" wird verhindert, dass die Debugsitzung aufgrund eines internen Fehlers fortgesetzt wird: {1}. + Durch das Ändern der Quelldatei "{0}" wird die Fortsetzung der Debugsitzung aufgrund des folgenden internen Fehlers verhindert: {1}. @@ -652,7 +652,7 @@ Stellen Sie sicher, dass Sie den Bezeichner "tt" für Sprachen verwenden, für d No valid location to insert method call. - No valid location to insert method call. + Keine gültige Position zum Einfügen eines Methodenaufrufs. @@ -682,7 +682,7 @@ Stellen Sie sicher, dass Sie den Bezeichner "tt" für Sprachen verwenden, für d Pull member(s) up to new base class... - Pull member(s) up to new base class... + Member auf neue Basisklasse ziehen... @@ -1013,7 +1013,7 @@ Der $-Anker stimmt mit "\n", aber nicht mit "\r\n" überein (Kombination aus Wag expression - expression + expression @@ -1283,7 +1283,7 @@ Der $-Anker stimmt mit "\n", aber nicht mit "\r\n" überein (Kombination aus Wag name - name + Name @@ -1383,7 +1383,7 @@ Mehrere Zeichenbereiche können verkettet werden. Um beispielsweise den Bereich no - no + Nein @@ -1766,7 +1766,7 @@ Wenn das ECMAScript-konforme Verhalten angegeben wird, ist "\w" gleichbedeutend yes - yes + Ja @@ -1832,7 +1832,7 @@ Positive Lookbehindassertionen mit Nullbreite werden normalerweise am Anfang reg Remove 'async' modifier - Remove 'async' modifier + async-Modifizierer entfernen @@ -1887,7 +1887,7 @@ Positive Lookbehindassertionen mit Nullbreite werden normalerweise am Anfang reg The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. - The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + Die Assembly "{0}" mit dem Typ "{1}" verweist auf das .NET Framework. Dies wird nicht unterstützt. @@ -2092,22 +2092,22 @@ Positive Lookbehindassertionen mit Nullbreite werden normalerweise am Anfang reg '{0}' cannot be null or empty. - "{0}" darf nicht NULL oder leer sein. + "{0}" kann nicht NULL oder leer sein. '{0}' cannot be null or whitespace. - "{0}" darf nicht NULL oder ein Leerraumzeichen sein. + "{0}" darf nicht NULL oder ein Leerraumzeichen sein. '{0}' is not null here. - '{0}' is not null here. + "{0}" ist hier nicht NULL. '{0}' may be null here. - '{0}' may be null here. + "{0}" darf hier NULL sein. diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.es.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.es.xlf index 4b1b1200af854..8c1b0edf1961c 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.es.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.es.xlf @@ -172,7 +172,7 @@ Asegúrese de usar el especificador "tt" para los idiomas para los que es necesa <omit> - <omit> + <omitir> @@ -347,7 +347,7 @@ Asegúrese de usar el especificador "tt" para los idiomas para los que es necesa Extract base class... - Extract base class... + Extraer clase base... @@ -502,12 +502,12 @@ Asegúrese de usar el especificador "tt" para los idiomas para los que es necesa Inline '{0}' - Inline '{0}' + En línea "{0}" Inline and keep '{0}' - Inline and keep '{0}' + Alinear y mantener "{0}" @@ -542,7 +542,7 @@ Asegúrese de usar el especificador "tt" para los idiomas para los que es necesa Make class 'abstract' - Make class 'abstract' + Convertir la clase en "abstract" @@ -607,17 +607,17 @@ Asegúrese de usar el especificador "tt" para los idiomas para los que es necesa Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. - Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. + Si se modifica el cuerpo de "{0}", se impedirá que continúe la sesión de depuración porque el cuerpo tiene demasiadas instrucciones. Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} - Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} + Si se modifica el cuerpo de "{0}", se impedirá que continúe la sesión de depuración debido a un error interno: {1}. Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. - Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. + La modificación del archivo de código fuente "{0}" impedirá que continúe la sesión de depuración porque el archivo es demasiado grande. @@ -642,7 +642,7 @@ Asegúrese de usar el especificador "tt" para los idiomas para los que es necesa Modifying source file '{0}' will prevent the debug session from continuing due to internal error: {1} - Modificar fuente archivo {0} evitará que la sesión de depuración continua debido a un error interno: {1} + Si se modifica el archivo de código fuente "{0}", se impedirá que continúe la sesión de depuración debido a un error interno: {1}. @@ -652,7 +652,7 @@ Asegúrese de usar el especificador "tt" para los idiomas para los que es necesa No valid location to insert method call. - No valid location to insert method call. + No hay ninguna ubicación válida para insertar una llamada de método. @@ -682,7 +682,7 @@ Asegúrese de usar el especificador "tt" para los idiomas para los que es necesa Pull member(s) up to new base class... - Pull member(s) up to new base class... + Extraer miembros a una nueva clase base... @@ -1013,7 +1013,7 @@ El limitador $ coincide con \n pero no coincide con \r\n (la combinación de ret expression - expression + expresión @@ -1283,7 +1283,7 @@ El limitador $ coincide con \n pero no coincide con \r\n (la combinación de ret name - name + nombre @@ -1383,7 +1383,7 @@ Se pueden concatenar dos o más intervalos de caracteres. Por ejemplo, para espe no - no + no @@ -1766,7 +1766,7 @@ Si se especifica un comportamiento compatible con ECMAScript, \w equivale a [a-z yes - yes + @@ -1832,7 +1832,7 @@ Las aserciones de búsqueda retrasada (lookbehind) positivas de ancho cero se us Remove 'async' modifier - Remove 'async' modifier + Quitar el modificador "async" @@ -1887,7 +1887,7 @@ Las aserciones de búsqueda retrasada (lookbehind) positivas de ancho cero se us The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. - The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + El ensamblado "{0}" que contiene el tipo "{1}" hace referencia a .NET Framework, lo cual no se admite. @@ -2092,22 +2092,22 @@ Las aserciones de búsqueda retrasada (lookbehind) positivas de ancho cero se us '{0}' cannot be null or empty. - "{0}" no puede ser NULL ni estar vacío. + '{0}' no puede ser nulo ni estar vacío. '{0}' cannot be null or whitespace. - "{0}" no puede ser NULL ni un espacio en blanco. + "{0}" no puede ser NULL ni un espacio en blanco. '{0}' is not null here. - '{0}' is not null here. + "{0}" no es NULL aquí. '{0}' may be null here. - '{0}' may be null here. + "{0}" puede ser NULL aquí. @@ -4012,7 +4012,7 @@ Esta versión se utiliza en: {2} Fully qualify '{0}' - {0}' completo + '{0}' completo diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.fr.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.fr.xlf index fac080b5424f8..1147237719676 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.fr.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.fr.xlf @@ -162,7 +162,7 @@ Veillez à utiliser le spécificateur "tt" pour les langues où il est nécessai <infer> - <inférence> + <déduire> @@ -347,7 +347,7 @@ Veillez à utiliser le spécificateur "tt" pour les langues où il est nécessai Extract base class... - Extract base class... + Extraire la classe de base... @@ -502,12 +502,12 @@ Veillez à utiliser le spécificateur "tt" pour les langues où il est nécessai Inline '{0}' - Inline '{0}' + Inline '{0}' Inline and keep '{0}' - Inline and keep '{0}' + Inline et conserver '{0}' @@ -542,7 +542,7 @@ Veillez à utiliser le spécificateur "tt" pour les langues où il est nécessai Make class 'abstract' - Make class 'abstract' + Rendre la classe 'abstract' @@ -607,17 +607,17 @@ Veillez à utiliser le spécificateur "tt" pour les langues où il est nécessai Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. - Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. + Le fait de modifier le corps de '{0}' empêche la session de débogage de se poursuivre, car le corps contient trop d'instructions. Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} - Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} + Le fait de modifier le corps de '{0}' empêche la session de débogage de se poursuivre en raison d'une erreur interne : {1} Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. - Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. + Le fait de modifier le fichier source '{0}' empêche la session de débogage de se poursuivre, car le fichier est trop volumineux. @@ -642,7 +642,7 @@ Veillez à utiliser le spécificateur "tt" pour les langues où il est nécessai Modifying source file '{0}' will prevent the debug session from continuing due to internal error: {1} - Le fait de modifier le fichier source {0} empêche la session de débogage de se poursuivre en raison de l’erreur interne : {1}. + Le fait de modifier le fichier source '{0}' empêche la session de débogage de se poursuivre en raison d'une erreur interne : {1} @@ -652,7 +652,7 @@ Veillez à utiliser le spécificateur "tt" pour les langues où il est nécessai No valid location to insert method call. - No valid location to insert method call. + Aucun emplacement valide pour l'insertion de l'appel de méthode. @@ -682,7 +682,7 @@ Veillez à utiliser le spécificateur "tt" pour les langues où il est nécessai Pull member(s) up to new base class... - Pull member(s) up to new base class... + Tirer (pull) le ou les membres jusqu'à la nouvelle classe de base... @@ -1013,7 +1013,7 @@ L'ancre $ correspond à \n mais ne correspond pas à \r\n (combinaison de caract expression - expression + expression @@ -1283,7 +1283,7 @@ L'ancre $ correspond à \n mais ne correspond pas à \r\n (combinaison de caract name - name + nom @@ -1383,7 +1383,7 @@ Vous pouvez concaténer au moins deux plages de caractères. Par exemple, pour s no - no + non @@ -1766,7 +1766,7 @@ Si vous spécifiez un comportement conforme à ECMAScript, \w équivaut à [a-zA yes - yes + oui @@ -1832,7 +1832,7 @@ Les assertions arrière positives de largeur nulle sont généralement utilisée Remove 'async' modifier - Remove 'async' modifier + Supprimer le modificateur 'async' @@ -1887,7 +1887,7 @@ Les assertions arrière positives de largeur nulle sont généralement utilisée The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. - The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + L'assembly '{0}' contenant le type '{1}' référence le .NET Framework, ce qui n'est pas pris en charge. @@ -2092,22 +2092,22 @@ Les assertions arrière positives de largeur nulle sont généralement utilisée '{0}' cannot be null or empty. - '{0}' ne peut pas être null ou vide. + « {0} » ne peut pas être vide ou avoir la valeur Null. '{0}' cannot be null or whitespace. - '{0}' ne peut pas être null ou un espace. + '{0}' ne peut pas avoir une valeur null ou être un espace blanc. '{0}' is not null here. - '{0}' is not null here. + '{0}' n'a pas une valeur null ici. '{0}' may be null here. - '{0}' may be null here. + '{0}' a peut-être une valeur null ici. @@ -2926,7 +2926,7 @@ Si le spécificateur de format "g" est utilisé sans autres spécificateurs de f generating source for symbols of this type is not supported - La génération de code source pour les symboles de ce type n'est pas prise en charge. + La génération de code source pour les symboles de ce type n'est pas prise en charge diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.it.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.it.xlf index 43c3dc243609f..0ec6e4dc811f5 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.it.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.it.xlf @@ -162,7 +162,7 @@ Assicurarsi di usare l'identificatore "tt" per le lingue per le quali è necessa <infer> - <infer> + <deduci> @@ -347,7 +347,7 @@ Assicurarsi di usare l'identificatore "tt" per le lingue per le quali è necessa Extract base class... - Extract base class... + Estrai classe di base... @@ -502,12 +502,12 @@ Assicurarsi di usare l'identificatore "tt" per le lingue per le quali è necessa Inline '{0}' - Inline '{0}' + Imposta '{0}' come inline Inline and keep '{0}' - Inline and keep '{0}' + Imposta come inline e mantieni '{0}' @@ -542,7 +542,7 @@ Assicurarsi di usare l'identificatore "tt" per le lingue per le quali è necessa Make class 'abstract' - Make class 'abstract' + Rendi la classe 'abstract' @@ -607,17 +607,17 @@ Assicurarsi di usare l'identificatore "tt" per le lingue per le quali è necessa Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. - Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. + Se si modifica il corpo di '{0}', la sessione di debug non potrà continuare perché il corpo contiene troppe istruzioni. Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} - Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} + Se si modifica il corpo di '{0}', la sessione di debug non potrà continuare a causa dell'errore interno {1} Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. - Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. + Se si modifica il file di origine '{0}', la sessione di debug non potrà continuare perché le dimensioni del file sono eccessive. @@ -642,7 +642,7 @@ Assicurarsi di usare l'identificatore "tt" per le lingue per le quali è necessa Modifying source file '{0}' will prevent the debug session from continuing due to internal error: {1} - Se si modifica il file di origine {0}, la sessione di debug non potrà continuare a causa di errore interno: {1}. + Se si modifica il file di origine '{0}', la sessione di debug non potrà continuare a causa dell'errore interno {1} @@ -652,7 +652,7 @@ Assicurarsi di usare l'identificatore "tt" per le lingue per le quali è necessa No valid location to insert method call. - No valid location to insert method call. + Non ci sono posizioni valide per inserire la chiamata a un metodo. @@ -682,7 +682,7 @@ Assicurarsi di usare l'identificatore "tt" per le lingue per le quali è necessa Pull member(s) up to new base class... - Pull member(s) up to new base class... + Esegui pull dei membri fino alla nuova classe di base... @@ -1013,7 +1013,7 @@ L'ancoraggio $ corrisponde a \n, ma non a \r\n (combinazione di ritorno a capo e expression - expression + espressione @@ -1283,7 +1283,7 @@ L'ancoraggio $ corrisponde a \n, ma non a \r\n (combinazione di ritorno a capo e name - name + nome @@ -1383,7 +1383,7 @@ Due o più intervalli di caratteri possono essere concatenati. Ad esempio, per s no - no + no @@ -1766,7 +1766,7 @@ Se viene specificato il comportamento conforme a ECMAScript, \w equivale a [a-zA yes - yes + @@ -1832,7 +1832,7 @@ Le asserzioni lookbehind positive di larghezza zero vengono usate in genere all' Remove 'async' modifier - Remove 'async' modifier + Rimuovi il modificatore 'async' @@ -1887,7 +1887,7 @@ Le asserzioni lookbehind positive di larghezza zero vengono usate in genere all' The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. - The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + L'assembly '{0}' che contiene il tipo '{1}' fa riferimento a .NET Framework, che non è supportato. @@ -2092,22 +2092,22 @@ Le asserzioni lookbehind positive di larghezza zero vengono usate in genere all' '{0}' cannot be null or empty. - '{0}' non può essere Null o vuoto. + '{0}' non può essere null o vuoto. '{0}' cannot be null or whitespace. - '{0}' non può essere Null o uno spazio vuoto. + '{0}' non può essere Null o uno spazio vuoto. '{0}' is not null here. - '{0}' is not null here. + '{0}' non è Null in questo punto. '{0}' may be null here. - '{0}' may be null here. + '{0}' può essere Null in questo punto. @@ -3552,7 +3552,7 @@ Continuare? property - Proprietà. + proprietà diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.ja.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.ja.xlf index f56adf41cfe28..a47c94d9cad0b 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.ja.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.ja.xlf @@ -97,7 +97,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Adding '{0}' into an interface will prevent the debug session from continuing. - {0}' をインターフェイスに追加すると、デバッグ セッションは続行されません。 + '{0}' をインターフェイスに追加すると、デバッグ セッションは続行されません。 @@ -162,7 +162,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma <infer> - <infer> + <推測する> @@ -172,7 +172,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma <omit> - <omit> + <省略> @@ -347,7 +347,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Extract base class... - Extract base class... + 基底クラスの抽出... @@ -372,7 +372,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Fix formatting - 書式設定を修正します。 + 書式設定を修正します @@ -502,12 +502,12 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Inline '{0}' - Inline '{0}' + インライン '{0}' Inline and keep '{0}' - Inline and keep '{0}' + インラインおよび '{0}' の保持 @@ -542,7 +542,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Make class 'abstract' - Make class 'abstract' + クラスを 'abstract' にしてください @@ -607,17 +607,17 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. - Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. + '{0}' の本体を変更すると、本体のステートメントが多くなりすぎるため、デバッグ セッションを続行できなくなります。 Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} - Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} + '{0}' の本体を変更すると、デバッグ セッションが内部エラーのため続行できなくなります: {1} Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. - Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. + ソース ファイル '{0}' を変更すると、ファイルが大きくなりすぎるため、デバッグ セッションを続行できなくなります。 @@ -642,7 +642,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Modifying source file '{0}' will prevent the debug session from continuing due to internal error: {1} - ソース ファイル {0} を変更すると、デバッグ セッションが内部エラーのため続行できなくなります: {1}。 + ソース ファイル '{0}' を変更すると、デバッグ セッションが内部エラーのため続行できなくなります: {1} @@ -652,7 +652,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma No valid location to insert method call. - No valid location to insert method call. + メソッド呼び出しを挿入する有効な場所がありません。 @@ -682,7 +682,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Pull member(s) up to new base class... - Pull member(s) up to new base class... + メンバーを新しい基底クラスに引き上げます... @@ -1013,7 +1013,7 @@ $ アンカーは、\n に一致しますが、\r\n (復帰文字と改行文字 expression - expression + @@ -1283,7 +1283,7 @@ $ アンカーは、\n に一致しますが、\r\n (復帰文字と改行文字 name - name + 名前 @@ -1383,7 +1383,7 @@ Two or more character ranges can be concatenated. For example, to specify the ra no - no + いいえ @@ -1766,7 +1766,7 @@ ECMAScript 準拠の動作が指定されている場合、\w は [a-zA-Z_0-9] yes - yes + はい @@ -1832,7 +1832,7 @@ Zero-width positive lookbehind assertions are typically used at the beginning of Remove 'async' modifier - Remove 'async' modifier + 'async' 修飾子を削除してください @@ -1887,7 +1887,7 @@ Zero-width positive lookbehind assertions are typically used at the beginning of The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. - The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + 型 '{1}' を含むアセンブリ '{0}' が .NET Framework を参照しています。これはサポートされていません。 @@ -2092,22 +2092,22 @@ Zero-width positive lookbehind assertions are typically used at the beginning of '{0}' cannot be null or empty. - '{0}' を null または空にすることはできません。 + '{0}' を NULL または空にすることはできません。 '{0}' cannot be null or whitespace. - '{0}' を null または空白にすることはできません。 + '{0}' を null または空白にすることはできません。 '{0}' is not null here. - '{0}' is not null here. + ここでは、'{0}' は null ではありません。 '{0}' may be null here. - '{0}' may be null here. + ここでは、'{0}' は null である可能性があります。 @@ -2702,7 +2702,7 @@ If the "M" format specifier is used without other custom format specifiers, it's Generate constructor in '{0}' - {0}' にコンストラクターを生成します + '{0}' にコンストラクターを生成します @@ -2767,62 +2767,62 @@ If the "M" format specifier is used without other custom format specifiers, it's Implement interface through '{0}' - {0}' を通じてインターフェイスを実装します + '{0}' を通じてインターフェイスを実装します Implement interface - インターフェイスを実装します。 + インターフェイスを実装します Introduce field for '{0}' - {0}' に対してフィールドを導入します + '{0}' に対してフィールドを導入します Introduce local for '{0}' - {0}' に対してローカルを導入します + '{0}' に対してローカルを導入します Introduce constant for '{0}' - {0}' に対して定数を導入します + '{0}' に対して定数を導入します Introduce local constant for '{0}' - {0}' に対してローカル定数を導入します + '{0}' に対してローカル定数を導入します Introduce field for all occurrences of '{0}' - {0}' のすべての発生に対してフィールドを導入します + '{0}' のすべての発生に対してフィールドを導入します Introduce local for all occurrences of '{0}' - {0}' のすべての発生に対してローカルを導入します + '{0}' のすべての発生に対してローカルを導入します Introduce constant for all occurrences of '{0}' - {0}' のすべての発生に対して定数を導入します + '{0}' のすべての発生に対して定数を導入します Introduce local constant for all occurrences of '{0}' - {0}' のすべての発生に対してローカル定数を導入します + '{0}' のすべての発生に対してローカル定数を導入します Introduce query variable for all occurrences of '{0}' - {0}' のすべての発生に対してクエリ変数を導入します + '{0}' のすべての発生に対してクエリ変数を導入します Introduce query variable for '{0}' - {0}' に対してクエリ変数を導入します + '{0}' に対してクエリ変数を導入します @@ -2941,7 +2941,7 @@ If the "g" format specifier is used without other custom format specifiers, it's Updating '{0}' will prevent the debug session from continuing. - {0}' を更新すると、デバッグ セッションは続行されません。 + '{0}' を更新すると、デバッグ セッションは続行されません。 @@ -2976,17 +2976,17 @@ If the "g" format specifier is used without other custom format specifiers, it's Changing the parameters of '{0}' will prevent the debug session from continuing. - {0}' のパラメーターを変更すると、デバッグ セッションは続行されません。 + '{0}' のパラメーターを変更すると、デバッグ セッションは続行されません。 Changing the return type of '{0}' will prevent the debug session from continuing. - {0}' の戻り値の型を変更すると、デバッグ セッションは続行されません。 + '{0}' の戻り値の型を変更すると、デバッグ セッションは続行されません。 Changing the type of '{0}' will prevent the debug session from continuing. - {0}' の型を変更すると、デバッグ セッションは続行されません。 + '{0}' の型を変更すると、デバッグ セッションは続行されません。 @@ -3016,32 +3016,32 @@ If the "g" format specifier is used without other custom format specifiers, it's Adding '{0}' into a '{1}' will prevent the debug session from continuing. - {0}' を '{1}' に追加すると、デバッグ セッションは続行されません。 + '{0}' を '{1}' に追加すると、デバッグ セッションは続行されません。 Adding '{0}' into a class with explicit or sequential layout will prevent the debug session from continuing. - {0}' を明示的なレイアウトまたはシーケンシャル レイアウトがあるクラスに追加すると、デバッグ セッションは続行されません。 + '{0}' を明示的なレイアウトまたはシーケンシャル レイアウトがあるクラスに追加すると、デバッグ セッションは続行されません。 Updating the modifiers of '{0}' will prevent the debug session from continuing. - {0}' の修飾子を更新すると、デバッグ セッションは続行されません。 + '{0}' の修飾子を更新すると、デバッグ セッションは続行されません。 Updating the Handles clause of '{0}' will prevent the debug session from continuing. - {0}' のHandles 句を更新すると、デバッグ セッションは続行されません。 + '{0}' のHandles 句を更新すると、デバッグ セッションは続行されません。 Adding '{0}' with the Handles clause will prevent the debug session from continuing. - {0}' をハンドル句に追加すると、デバッグ セッションが続行できなくなります。 + '{0}' をハンドル句に追加すると、デバッグ セッションが続行できなくなります。 Updating the Implements clause of a '{0}' will prevent the debug session from continuing. - {0}' の Implements 句を更新すると、デバッグ セッションは続行されません。 + '{0}' の Implements 句を更新すると、デバッグ セッションは続行されません。 @@ -3051,32 +3051,32 @@ If the "g" format specifier is used without other custom format specifiers, it's Updating the variance of '{0}' will prevent the debug session from continuing. - {0}' の変性を更新すると、デバッグ セッションは続行されません。 + '{0}' の変性を更新すると、デバッグ セッションは続行されません。 Updating the type of '{0}' will prevent the debug session from continuing. - {0}' の型を更新すると、デバッグ セッションは続行されません。 + '{0}' の型を更新すると、デバッグ セッションは続行されません。 Updating the initializer of '{0}' will prevent the debug session from continuing. - {0}' の初期化子を更新すると、デバッグ セッションは続行されません。 + '{0}' の初期化子を更新すると、デバッグ セッションは続行されません。 Updating the size of a '{0}' will prevent the debug session from continuing. - {0}' のサイズを更新すると、デバッグ セッションは続行されません。 + '{0}' のサイズを更新すると、デバッグ セッションは続行されません。 Updating the underlying type of '{0}' will prevent the debug session from continuing. - {0}' の基になる型を更新すると、デバッグ セッションは続行されません。 + '{0}' の基になる型を更新すると、デバッグ セッションは続行されません。 Updating the base class and/or base interface(s) of '{0}' will prevent the debug session from continuing. - {0}' の基本クラスおよび基底インターフェイスを更新すると、デバッグ セッションは続行されません。 + '{0}' の基本クラスおよび基底インターフェイスを更新すると、デバッグ セッションは続行されません。 @@ -3111,12 +3111,12 @@ If the "g" format specifier is used without other custom format specifiers, it's Renaming '{0}' will prevent the debug session from continuing. - {0}' の名前を変更すると、デバッグ セッションは続行されません。 + '{0}' の名前を変更すると、デバッグ セッションは続行されません。 Adding '{0}' will prevent the debug session from continuing. - {0}' を追加すると、デバッグ セッションは続行されません。 + '{0}' を追加すると、デバッグ セッションは続行されません。 @@ -3156,12 +3156,12 @@ If the "g" format specifier is used without other custom format specifiers, it's Moving '{0}' will prevent the debug session from continuing. - {0}' を移動すると、デバッグ セッションは続行されません。 + '{0}' を移動すると、デバッグ セッションは続行されません。 Deleting '{0}' will prevent the debug session from continuing. - {0}' を削除すると、デバッグ セッションは続行されません。 + '{0}' を削除すると、デバッグ セッションは続行されません。 @@ -3740,12 +3740,12 @@ UTC 時刻の場合 (DateTime.Kind プロパティ値が DateTimeKind.Utc)、書 Replace '{0}' and '{1}' with property - {0}' および '{1}' をプロパティと置換する + '{0}' および '{1}' をプロパティと置換する Replace '{0}' with property - {0}' をプロパティを置換する + '{0}' をプロパティを置換する @@ -3765,7 +3765,7 @@ UTC 時刻の場合 (DateTime.Kind プロパティ値が DateTimeKind.Utc)、書 Change '{0}' to '{1}'. - {0}' を '{1}' に変更します。 + '{0}' を '{1}' に変更します。 @@ -3795,7 +3795,7 @@ UTC 時刻の場合 (DateTime.Kind プロパティ値が DateTimeKind.Utc)、書 Unable to load Analyzer assembly {0}: {1} - アナライザーのアセンブリ {0}: {1} を読み込むことができません。 + アナライザーのアセンブリ {0}: {1} を読み込むことができません @@ -3827,7 +3827,7 @@ This version used in: {2} Find and install latest version of '{0}' - {0}' の最新バージョンの検索とインストール + '{0}' の最新バージョンの検索とインストール @@ -3932,12 +3932,12 @@ This version used in: {2} Replace '{0}' with method - {0}' をメソッドに置換します + '{0}' をメソッドに置換します Replace '{0}' with methods - {0}' をメソッドに置換します + '{0}' をメソッドに置換します @@ -4017,7 +4017,7 @@ This version used in: {2} Remove reference to '{0}'. - {0}' への参照を削除します。 + '{0}' への参照を削除します。 @@ -4067,7 +4067,7 @@ This version used in: {2} Take '{0}' - {0}' を取る + '{0}' を取る diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.ko.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.ko.xlf index 25635e3214b34..c701e1966e78c 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.ko.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.ko.xlf @@ -162,7 +162,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma <infer> - <infer> + <유추> @@ -172,7 +172,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma <omit> - <omit> + <생략> @@ -347,7 +347,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Extract base class... - Extract base class... + 기본 클래스 추출... @@ -502,12 +502,12 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Inline '{0}' - Inline '{0}' + '{0}'을(를) 인라인으로 지정 Inline and keep '{0}' - Inline and keep '{0}' + '{0}'을(를) 인라인으로 지정 및 유지 @@ -542,7 +542,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Make class 'abstract' - Make class 'abstract' + 'abstract' 클래스 만들기 @@ -607,17 +607,17 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. - Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. + 본문에 문이 너무 많아 '{0}'의 본문을 수정하면 디버그 세션을 계속 진행할 수 없습니다. Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} - Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} + '{0}'의 본문을 수정하면 다음 내부 오류로 인해 디버그 세션을 계속 진행할 수 없습니다. {1} Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. - Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. + '{0}' 소스 파일을 수정하면 파일이 너무 커서 디버그 세션을 계속 진행할 수 없습니다. @@ -642,7 +642,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Modifying source file '{0}' will prevent the debug session from continuing due to internal error: {1} - 소스 파일 {0}을(를) 수정하면 다음 내부 오류로 인해 디버그 세션을 계속 진행할 수 없습니다. {1}. + '{0}' 소스 파일을 수정하면 다음 내부 오류로 인해 디버그 세션을 계속 진행할 수 없습니다. {1} @@ -652,7 +652,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma No valid location to insert method call. - No valid location to insert method call. + 메서드 호출을 삽입할 유효한 위치가 없습니다. @@ -682,7 +682,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Pull member(s) up to new base class... - Pull member(s) up to new base class... + 새 기본 클래스까지 멤버를 풀하세요... @@ -1013,7 +1013,7 @@ $ 앵커는 \n은 일치시키지만 \r\n(캐리지 리턴 및 줄 바꿈 문자 expression - expression + @@ -1283,7 +1283,7 @@ $ 앵커는 \n은 일치시키지만 \r\n(캐리지 리턴 및 줄 바꿈 문자 name - name + 이름 @@ -1383,7 +1383,7 @@ Two or more character ranges can be concatenated. For example, to specify the ra no - no + 아니요 @@ -1766,7 +1766,7 @@ ECMAScript 규격 동작을 지정한 경우 \w는 [a-zA-Z_0-9]와 같습니다. yes - yes + @@ -1832,7 +1832,7 @@ Zero-width positive lookbehind assertions are typically used at the beginning of Remove 'async' modifier - Remove 'async' modifier + 'async' 한정자 제거 @@ -1887,7 +1887,7 @@ Zero-width positive lookbehind assertions are typically used at the beginning of The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. - The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + '{1}' 형식을 포함하는 '{0}' 어셈블리가 지원되지 않는 .NET Framework를 참조합니다. @@ -2092,22 +2092,22 @@ Zero-width positive lookbehind assertions are typically used at the beginning of '{0}' cannot be null or empty. - '{0}'은(는) Null이거나 비워 둘 수 없습니다. + '{0}'은(는) Null이거나 비워 둘 수 없습니다. '{0}' cannot be null or whitespace. - '{0}'은(는) Null이거나 공백일 수 없습니다. + '{0}'은(는) null이거나 공백일 수 없습니다. '{0}' is not null here. - '{0}' is not null here. + '{0}'은(는) 여기에서 null이 아닙니다. '{0}' may be null here. - '{0}' may be null here. + '{0}'은(는) 여기에서 null일 수 있습니다. @@ -2642,7 +2642,7 @@ If the "M" format specifier is used without other custom format specifiers, it's Type parameter '{0}' is hidden by another type parameter '{1}'. - {0}' 형식 매개 변수가 다른 '{1}' 형식 매개 변수에 의해 숨겨집니다. + '{0}' 형식 매개 변수가 다른 '{1}' 형식 매개 변수에 의해 숨겨집니다. @@ -2662,12 +2662,12 @@ If the "M" format specifier is used without other custom format specifiers, it's Add optional parameters to '{0}' - {0}'에 선택적 매개 변수 추가 + '{0}'에 선택적 매개 변수 추가 Add parameters to '{0}' - {0}'에 매개 변수 추가 + '{0}'에 매개 변수 추가 @@ -2702,7 +2702,7 @@ If the "M" format specifier is used without other custom format specifiers, it's Generate constructor in '{0}' - {0}'에서 생성자 생성 + '{0}'에서 생성자 생성 @@ -2742,7 +2742,7 @@ If the "M" format specifier is used without other custom format specifiers, it's Generate local '{0}' - {0}' 로컬을 생성합니다. + '{0}' 로컬을 생성합니다. @@ -2767,7 +2767,7 @@ If the "M" format specifier is used without other custom format specifiers, it's Implement interface through '{0}' - {0}'을(를) 통해 인터페이스 구현 + '{0}'을(를) 통해 인터페이스 구현 @@ -2777,52 +2777,52 @@ If the "M" format specifier is used without other custom format specifiers, it's Introduce field for '{0}' - {0}'에 대한 필드 지정 + '{0}'에 대한 필드 지정 Introduce local for '{0}' - {0}'에 대한 로컬 지정 + '{0}'에 대한 로컬 지정 Introduce constant for '{0}' - {0}'에 대한 상수 지정 + '{0}'에 대한 상수 지정 Introduce local constant for '{0}' - {0}'에 대한 지역 상수 지정 + '{0}'에 대한 지역 상수 지정 Introduce field for all occurrences of '{0}' - {0}'의 모든 항목에 대한 필드 지정 + '{0}'의 모든 항목에 대한 필드 지정 Introduce local for all occurrences of '{0}' - {0}'의 모든 항목에 대한 로컬 지정 + '{0}'의 모든 항목에 대한 로컬 지정 Introduce constant for all occurrences of '{0}' - {0}'의 모든 항목에 대한 상수 지정 + '{0}'의 모든 항목에 대한 상수 지정 Introduce local constant for all occurrences of '{0}' - {0}'의 모든 항목에 대한 지역 상수 지정 + '{0}'의 모든 항목에 대한 지역 상수 지정 Introduce query variable for all occurrences of '{0}' - {0}'의 모든 항목에 대한 쿼리 변수 지정 + '{0}'의 모든 항목에 대한 쿼리 변수 지정 Introduce query variable for '{0}' - {0}'에 대한 쿼리 변수 지정 + '{0}'에 대한 쿼리 변수 지정 @@ -2941,7 +2941,7 @@ If the "g" format specifier is used without other custom format specifiers, it's Updating '{0}' will prevent the debug session from continuing. - {0}'을(를) 업데이트하면 디버그 세션을 계속할 수 없습니다. + '{0}'을(를) 업데이트하면 디버그 세션을 계속할 수 없습니다. @@ -2961,7 +2961,7 @@ If the "g" format specifier is used without other custom format specifiers, it's Ceasing to capture variable '{0}' will prevent the debug session from continuing. - {0}' 변수의 캡처를 중단하면 디버그 세션을 계속할 수 없습니다. + '{0}' 변수의 캡처를 중단하면 디버그 세션을 계속할 수 없습니다. @@ -2976,17 +2976,17 @@ If the "g" format specifier is used without other custom format specifiers, it's Changing the parameters of '{0}' will prevent the debug session from continuing. - {0}' 매개 변수를 변경하면 디버그 세션을 계속할 수 없습니다. + '{0}' 매개 변수를 변경하면 디버그 세션을 계속할 수 없습니다. Changing the return type of '{0}' will prevent the debug session from continuing. - {0}'의 반환 형식을 변경하면 디버그 세션을 계속할 수 없습니다. + '{0}'의 반환 형식을 변경하면 디버그 세션을 계속할 수 없습니다. Changing the type of '{0}' will prevent the debug session from continuing. - {0}'의 형식을 변경하면 디버그 세션을 계속할 수 없습니다. + '{0}'의 형식을 변경하면 디버그 세션을 계속할 수 없습니다. @@ -3016,22 +3016,22 @@ If the "g" format specifier is used without other custom format specifiers, it's Adding '{0}' into a '{1}' will prevent the debug session from continuing. - {0}'을(를) '{1}'에 추가하면 디버그 세션을 계속할 수 없습니다. + '{0}'을(를) '{1}'에 추가하면 디버그 세션을 계속할 수 없습니다. Adding '{0}' into a class with explicit or sequential layout will prevent the debug session from continuing. - {0}'을(를) 명시적 또는 순차적 레이아웃으로 클래스에 추가하면 디버그 세션을 계속할 수 없습니다. + '{0}'을(를) 명시적 또는 순차적 레이아웃으로 클래스에 추가하면 디버그 세션을 계속할 수 없습니다. Updating the modifiers of '{0}' will prevent the debug session from continuing. - {0}'의 한정자를 업데이트하면 디버그 세션을 계속할 수 없습니다. + '{0}'의 한정자를 업데이트하면 디버그 세션을 계속할 수 없습니다. Updating the Handles clause of '{0}' will prevent the debug session from continuing. - {0}'의 Handles 절을 업데이트하면 디버그 세션을 계속할 수 없습니다. + '{0}'의 Handles 절을 업데이트하면 디버그 세션을 계속할 수 없습니다. @@ -3041,37 +3041,37 @@ If the "g" format specifier is used without other custom format specifiers, it's Updating the Implements clause of a '{0}' will prevent the debug session from continuing. - {0}'의 Implements 절을 업데이트하면 디버그 세션을 계속할 수 없습니다. + '{0}'의 Implements 절을 업데이트하면 디버그 세션을 계속할 수 없습니다. Changing the constraint from '{0}' to '{1}' will prevent the debug session from continuing. - {0}'에서 '{1}'(으)로 제약 조건을 변경하면 디버그 세션을 계속할 수 없습니다. + '{0}'에서 '{1}'(으)로 제약 조건을 변경하면 디버그 세션을 계속할 수 없습니다. Updating the variance of '{0}' will prevent the debug session from continuing. - {0}'의 가변성(variance)을 업데이트하면 디버그 세션을 계속할 수 없습니다. + '{0}'의 가변성(variance)을 업데이트하면 디버그 세션을 계속할 수 없습니다. Updating the type of '{0}' will prevent the debug session from continuing. - {0}'의 형식을 업데이트하면 디버그 세션을 계속할 수 없습니다. + '{0}'의 형식을 업데이트하면 디버그 세션을 계속할 수 없습니다. Updating the initializer of '{0}' will prevent the debug session from continuing. - {0}'의 이니셜라이저를 업데이트하면 디버그 세션을 계속할 수 없습니다. + '{0}'의 이니셜라이저를 업데이트하면 디버그 세션을 계속할 수 없습니다. Updating the size of a '{0}' will prevent the debug session from continuing. - {0}'의 크기를 업데이트하면 디버그 세션을 계속할 수 없습니다. + '{0}'의 크기를 업데이트하면 디버그 세션을 계속할 수 없습니다. Updating the underlying type of '{0}' will prevent the debug session from continuing. - {0}'의 기본 형식을 업데이트하면 디버그 세션을 계속할 수 없습니다. + '{0}'의 기본 형식을 업데이트하면 디버그 세션을 계속할 수 없습니다. @@ -3111,12 +3111,12 @@ If the "g" format specifier is used without other custom format specifiers, it's Renaming '{0}' will prevent the debug session from continuing. - {0}'의 이름을 변경하면 디버그 세션을 계속할 수 없습니다. + '{0}'의 이름을 변경하면 디버그 세션을 계속할 수 없습니다. Adding '{0}' will prevent the debug session from continuing. - {0}'을(를) 추가하면 디버그 세션을 계속할 수 없습니다. + '{0}'을(를) 추가하면 디버그 세션을 계속할 수 없습니다. @@ -3156,12 +3156,12 @@ If the "g" format specifier is used without other custom format specifiers, it's Moving '{0}' will prevent the debug session from continuing. - {0}'을(를) 이동하면 디버그 세션을 계속할 수 없습니다. + '{0}'을(를) 이동하면 디버그 세션을 계속할 수 없습니다. Deleting '{0}' will prevent the debug session from continuing. - {0}'을(를) 삭제하면 디버그 세션을 계속할 수 없습니다. + '{0}'을(를) 삭제하면 디버그 세션을 계속할 수 없습니다. @@ -3281,7 +3281,7 @@ If the "g" format specifier is used without other custom format specifiers, it's Attribute '{0}' is missing. Updating an async method or an iterator will prevent the debug session from continuing. - {0}' 특성이 없습니다. 비동기 메서드 또는 반복기를 업데이트하면 디버그 세션을 계속할 수 없습니다. + '{0}' 특성이 없습니다. 비동기 메서드 또는 반복기를 업데이트하면 디버그 세션을 계속할 수 없습니다. @@ -3366,7 +3366,7 @@ Do you want to continue? Analyzer '{0}' threw the following exception: '{1}'. - {0}' 분석기에서 다음 예외를 throw했습니다. + '{0}' 분석기에서 다음 예외를 throw했습니다. '{1}' @@ -3755,7 +3755,7 @@ DateTimeOffset 값의 경우, "K" 형식 지정자는 "zzz" 형식 지정자와 Generate type '{0}' - {0}' 형식 생성 + '{0}' 형식 생성 @@ -3765,7 +3765,7 @@ DateTimeOffset 값의 경우, "K" 형식 지정자는 "zzz" 형식 지정자와 Change '{0}' to '{1}'. - {0}'을(를) '{1}'(으)로 변경합니다. + '{0}'을(를) '{1}'(으)로 변경합니다. @@ -3827,7 +3827,7 @@ This version used in: {2} Find and install latest version of '{0}' - {0}'의 최신 버전 찾기 및 설치 + '{0}'의 최신 버전 찾기 및 설치 @@ -3842,12 +3842,12 @@ This version used in: {2} Install version '{0}' - {0}' 버전 설치 + '{0}' 버전 설치 Generate variable '{0}' - {0}' 변수 생성 + '{0}' 변수 생성 @@ -3932,12 +3932,12 @@ This version used in: {2} Replace '{0}' with method - {0}'을(를) 메서드로 대체 + '{0}'을(를) 메서드로 대체 Replace '{0}' with methods - {0}'을(를) 메서드로 대체 + '{0}'을(를) 메서드로 대체 @@ -4002,7 +4002,7 @@ This version used in: {2} Install package '{0}' - {0}' 패키지 설치 + '{0}' 패키지 설치 @@ -4012,12 +4012,12 @@ This version used in: {2} Fully qualify '{0}' - {0}' 정규화 + '{0}' 정규화 Remove reference to '{0}'. - {0}'에 대한 참조를 제거합니다. + '{0}'에 대한 참조를 제거합니다. @@ -4067,7 +4067,7 @@ This version used in: {2} Take '{0}' - {0}' 사용 + '{0}' 사용 @@ -4127,7 +4127,7 @@ This version used in: {2} Add parameter to '{0}' - {0}'에 매개 변수 추가 + '{0}'에 매개 변수 추가 @@ -4172,12 +4172,12 @@ This version used in: {2} Initialize field '{0}' - {0}' 필드 초기화 + '{0}' 필드 초기화 Initialize property '{0}' - {0}' 속성 초기화 + '{0}' 속성 초기화 diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.pl.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.pl.xlf index 49e442e61185d..0e2551121ac97 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.pl.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.pl.xlf @@ -162,7 +162,7 @@ Pamiętaj, aby nie używać specyfikatora „tt” dla wszystkich języków, w k <infer> - <infer> + <wnioskuj> @@ -347,7 +347,7 @@ Pamiętaj, aby nie używać specyfikatora „tt” dla wszystkich języków, w k Extract base class... - Extract base class... + Wyodrębnij klasę bazową... @@ -502,12 +502,12 @@ Pamiętaj, aby nie używać specyfikatora „tt” dla wszystkich języków, w k Inline '{0}' - Inline '{0}' + Wstaw środwierszowo metodę „{0}” Inline and keep '{0}' - Inline and keep '{0}' + Wstaw środwierszowo i zachowaj metodę „{0}” @@ -542,7 +542,7 @@ Pamiętaj, aby nie używać specyfikatora „tt” dla wszystkich języków, w k Make class 'abstract' - Make class 'abstract' + Ustaw specyfikator „abstract” dla klasy @@ -607,17 +607,17 @@ Pamiętaj, aby nie używać specyfikatora „tt” dla wszystkich języków, w k Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. - Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. + Zmodyfikowanie treści elementu „{0}” uniemożliwi kontynuowanie sesji debugowania, ponieważ treść zawiera zbyt wiele instrukcji. Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} - Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} + Zmodyfikowanie treści elementu „{0}” uniemożliwi kontynuowanie sesji debugowania ze względu na błąd wewnętrzny: {1}. Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. - Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. + Zmodyfikowanie pliku źródłowego „{0}” uniemożliwi kontynuowanie sesji debugowania, ponieważ plik jest zbyt duży. @@ -642,7 +642,7 @@ Pamiętaj, aby nie używać specyfikatora „tt” dla wszystkich języków, w k Modifying source file '{0}' will prevent the debug session from continuing due to internal error: {1} - Zmodyfikowanie pliku źródłowego {0} uniemożliwi kontynuowanie sesji debugowania ze względu na błąd wewnętrzny: {1}. + Zmodyfikowanie pliku źródłowego „{0}” uniemożliwi kontynuowanie sesji debugowania ze względu na błąd wewnętrzny: {1}. @@ -652,7 +652,7 @@ Pamiętaj, aby nie używać specyfikatora „tt” dla wszystkich języków, w k No valid location to insert method call. - No valid location to insert method call. + Brak prawidłowej lokalizacji dla wstawienia wywołania metody. @@ -682,7 +682,7 @@ Pamiętaj, aby nie używać specyfikatora „tt” dla wszystkich języków, w k Pull member(s) up to new base class... - Pull member(s) up to new base class... + Ściągnij skladowe do nowej klasy bazowej... @@ -1013,7 +1013,7 @@ Kotwica $ pasuje do znaku \n, lecz nie do znaków \r\n (kombinacji znaków powro expression - expression + wyrażenie @@ -1283,7 +1283,7 @@ Kotwica $ pasuje do znaku \n, lecz nie do znaków \r\n (kombinacji znaków powro name - name + nazwa @@ -1383,7 +1383,7 @@ Można połączyć dwa lub więcej zakresów znaków. Na przykład aby określi no - no + nie @@ -1766,7 +1766,7 @@ Jeśli określono zachowanie zgodne ze standardem ECMAScript, element \w jest r yes - yes + tak @@ -1832,7 +1832,7 @@ Pozytywne asercje wsteczne o zerowej szerokości są zwykle używane na początk Remove 'async' modifier - Remove 'async' modifier + Usuń modyfikator „async” @@ -1887,7 +1887,7 @@ Pozytywne asercje wsteczne o zerowej szerokości są zwykle używane na początk The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. - The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + Zestaw „{0}” zawierający typ „{1}” odwołuje się do platformy .NET Framework, co nie jest obsługiwane. @@ -2092,22 +2092,22 @@ Pozytywne asercje wsteczne o zerowej szerokości są zwykle używane na początk '{0}' cannot be null or empty. - Element „{0}” nie może mieć wartości null ani być pusty. + Element „{0}” nie może mieć wartości null ani być pusty. '{0}' cannot be null or whitespace. - Element „{0}” nie może mieć wartości null ani składać się ze znaków odstępu. + Element „{0}” nie może mieć wartości null ani składać się ze znaków odstępu. '{0}' is not null here. - '{0}' is not null here. + Element „{0}” nie ma wartości null w tym miejscu. '{0}' may be null here. - '{0}' may be null here. + Element „{0}” może mieć wartość null w tym miejscu. diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.pt-BR.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.pt-BR.xlf index 166107d39d8ad..a9ea8a860d4bd 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.pt-BR.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.pt-BR.xlf @@ -347,7 +347,7 @@ Verifique se o especificador "tt" foi usado para idiomas para os quais é necess Extract base class... - Extract base class... + Extrair a classe base... @@ -502,12 +502,12 @@ Verifique se o especificador "tt" foi usado para idiomas para os quais é necess Inline '{0}' - Inline '{0}' + Embutir '{0}' Inline and keep '{0}' - Inline and keep '{0}' + Embutir e manter '{0}' @@ -542,7 +542,7 @@ Verifique se o especificador "tt" foi usado para idiomas para os quais é necess Make class 'abstract' - Make class 'abstract' + Tornar a classe 'abstract' @@ -607,17 +607,17 @@ Verifique se o especificador "tt" foi usado para idiomas para os quais é necess Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. - Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. + A modificação do corpo de '{0}' impedirá que a sessão de depuração continue porque o corpo tem muitas instruções. Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} - Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} + A modificação do corpo de '{0}' impedirá que a sessão de depuração continue devido a um erro interno: {1} Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. - Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. + A modificação do arquivo de origem '{0}' impedirá que a sessão de depuração continue porque o arquivo é muito grande. @@ -642,7 +642,7 @@ Verifique se o especificador "tt" foi usado para idiomas para os quais é necess Modifying source file '{0}' will prevent the debug session from continuing due to internal error: {1} - Modificar fonte arquivo {0} impedirá a sessão de depuração de continuar devido a erro interno: {1}. + A modificação do arquivo de origem '{0}' impedirá que a sessão de depuração continue devido a um erro interno: {1} @@ -652,7 +652,7 @@ Verifique se o especificador "tt" foi usado para idiomas para os quais é necess No valid location to insert method call. - No valid location to insert method call. + Não há nenhum local válido para inserir a chamada de método. @@ -682,7 +682,7 @@ Verifique se o especificador "tt" foi usado para idiomas para os quais é necess Pull member(s) up to new base class... - Pull member(s) up to new base class... + Efetuar pull de membros até a nova classe base... @@ -1013,7 +1013,7 @@ A âncora $ corresponde a \n, mas não corresponde a \r\n (a combinação dos ca expression - expression + expressão @@ -1283,7 +1283,7 @@ A âncora $ corresponde a \n, mas não corresponde a \r\n (a combinação dos ca name - name + nome @@ -1383,7 +1383,7 @@ Dois ou mais intervalos de caracteres podem ser concatenados. Por exemplo, para no - no + não @@ -1766,7 +1766,7 @@ Se o comportamento em conformidade com o ECMAScript for especificado, \w será e yes - yes + sim @@ -1832,7 +1832,7 @@ As declarações de lookbehind positivas de largura zero normalmente são usadas Remove 'async' modifier - Remove 'async' modifier + Remover o modificador 'async' @@ -1887,7 +1887,7 @@ As declarações de lookbehind positivas de largura zero normalmente são usadas The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. - The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + O assembly '{0}' contendo o tipo '{1}' referencia o .NET Framework, mas não há suporte para isso. @@ -2092,22 +2092,22 @@ As declarações de lookbehind positivas de largura zero normalmente são usadas '{0}' cannot be null or empty. - '{0}' não pode ser nulo ou vazio. + '{0}' não pode ser nulo nem vazio. '{0}' cannot be null or whitespace. - '{0}' não pode ser nulo ou ter espaço em branco. + '{0}' não pode ser nulo nem espaço em branco. '{0}' is not null here. - '{0}' is not null here. + '{0}' não é nulo aqui. '{0}' may be null here. - '{0}' may be null here. + '{0}' pode ser nulo aqui. @@ -3552,7 +3552,7 @@ Deseja continuar? property - Propriedade. + propriedade @@ -3672,7 +3672,7 @@ Quando esse especificador de formato padrão é usado, a operação de análise 'symbol' cannot be a namespace. - '"símbolo" não pode ser um namespace. + "símbolo" não pode ser um namespace. diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.ru.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.ru.xlf index fac78891ca0a9..54a7c66867865 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.ru.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.ru.xlf @@ -162,7 +162,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma <infer> - <infer> + <вывести> @@ -347,7 +347,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Extract base class... - Extract base class... + Извлечь базовый класс... @@ -502,12 +502,12 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Inline '{0}' - Inline '{0}' + Встроенный "{0}" Inline and keep '{0}' - Inline and keep '{0}' + Сделать "{0}" встроенным и сохранить его @@ -542,7 +542,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Make class 'abstract' - Make class 'abstract' + Сделать класс абстрактным @@ -607,17 +607,17 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. - Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. + Изменение тела "{0}" помешает продолжению сеанса отладки из-за того, что тело содержит слишком много операторов. Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} - Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} + Изменение тела "{0}" помешает продолжению сеанса отладки из-за внутренней ошибки: {1} Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. - Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. + Изменение исходного файла "{0}" помешает продолжению сеанса отладки из-за того, что файл имеет слишком большой размер. @@ -642,7 +642,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Modifying source file '{0}' will prevent the debug session from continuing due to internal error: {1} - Изменение исходного файла {0} помешает сеанса отладки продолжения из-за внутренней ошибки: {1}. + Изменение исходного файла "{0}" помешает продолжению сеанса отладки из-за внутренней ошибки: {1} @@ -652,7 +652,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma No valid location to insert method call. - No valid location to insert method call. + Отсутствует допустимое расположение для вставки вызова метода. @@ -682,7 +682,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Pull member(s) up to new base class... - Pull member(s) up to new base class... + Получение элементов для нового базового класса... @@ -1013,7 +1013,7 @@ The $ anchor matches \n but does not match \r\n (the combination of carriage ret expression - expression + выражение @@ -1283,7 +1283,7 @@ The $ anchor matches \n but does not match \r\n (the combination of carriage ret name - name + имя @@ -1383,7 +1383,7 @@ Two or more character ranges can be concatenated. For example, to specify the ra no - no + нет @@ -1766,7 +1766,7 @@ If ECMAScript-compliant behavior is specified, \w is equivalent to [a-zA-Z_0-9]< yes - yes + да @@ -1832,7 +1832,7 @@ Zero-width positive lookbehind assertions are typically used at the beginning of Remove 'async' modifier - Remove 'async' modifier + Удалить модификатор "async" @@ -1887,7 +1887,7 @@ Zero-width positive lookbehind assertions are typically used at the beginning of The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. - The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + Сборка "{0}", содержащая тип "{1}", ссылается на платформу .NET Framework, которая не поддерживается. @@ -2092,22 +2092,22 @@ Zero-width positive lookbehind assertions are typically used at the beginning of '{0}' cannot be null or empty. - "{0}" не может быть пустым или иметь значение null. + "{0}" не может быть неопределенным или пустым. '{0}' cannot be null or whitespace. - "{0}" не может быть пустым или содержать только пробел. + "{0}" не может быть пустым или содержать только пробел. '{0}' is not null here. - '{0}' is not null here. + Здесь "{0}" имеет значение, отличное от NULL. '{0}' may be null here. - '{0}' may be null here. + Здесь "{0}" может иметь значение NULL. diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.tr.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.tr.xlf index 73cbe3412d86b..0a178556dbcc7 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.tr.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.tr.xlf @@ -72,12 +72,12 @@ AM ve PM arasındaki farkın korunmasının gerekli olduğu diller için "tt" be Add project reference to '{0}'. - {0}' üzerine proje başvurusu ekleyin. + '{0}' üzerine proje başvurusu ekleyin. Add reference to '{0}'. - {0}' üzerine başvuru ekleyin. + '{0}' üzerine başvuru ekleyin. @@ -347,7 +347,7 @@ AM ve PM arasındaki farkın korunmasının gerekli olduğu diller için "tt" be Extract base class... - Extract base class... + Temel sınıfı ayıkla... @@ -502,12 +502,12 @@ AM ve PM arasındaki farkın korunmasının gerekli olduğu diller için "tt" be Inline '{0}' - Inline '{0}' + '{0}' öğesini satır içine al Inline and keep '{0}' - Inline and keep '{0}' + '{0}' öğesini satır içine al ve koru @@ -542,7 +542,7 @@ AM ve PM arasındaki farkın korunmasının gerekli olduğu diller için "tt" be Make class 'abstract' - Make class 'abstract' + Sınıfı 'abstract' yap @@ -607,17 +607,17 @@ AM ve PM arasındaki farkın korunmasının gerekli olduğu diller için "tt" be Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. - Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. + '{0}' gövdesinin değiştirilmesi, gövdede çok fazla deyim olduğundan hata ayıklama oturumunun devam etmesini engeller. Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} - Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} + '{0}' gövdesinin değiştirilmesi, {1} iç hatası nedeniyle hata ayıklama oturumunun devam etmesini engeller. Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. - Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. + '{0}' kaynak dosyasının değiştirilmesi, dosya çok büyük olduğundan hata ayıklama oturumunun devam etmesini engeller. @@ -642,7 +642,7 @@ AM ve PM arasındaki farkın korunmasının gerekli olduğu diller için "tt" be Modifying source file '{0}' will prevent the debug session from continuing due to internal error: {1} - {0} kaynak dosyasının değiştirilmesi şu iç hata nedeniyle hata ayıklama oturumunun devam etmesini engeller: {1}. + '{0}' kaynak dosyasının değiştirilmesi, {1} iç hatası nedeniyle hata ayıklama oturumunun devam etmesini engeller. @@ -652,7 +652,7 @@ AM ve PM arasındaki farkın korunmasının gerekli olduğu diller için "tt" be No valid location to insert method call. - No valid location to insert method call. + Metot çağrısının ekleneceği geçerli konum yok. @@ -682,7 +682,7 @@ AM ve PM arasındaki farkın korunmasının gerekli olduğu diller için "tt" be Pull member(s) up to new base class... - Pull member(s) up to new base class... + Üyeleri yeni temel sınıfa çek... @@ -1013,7 +1013,7 @@ $ yer işareti \n ile eşleşir, ancak \r\n (satır başı ve yeni satır karakt expression - expression + ifade @@ -1283,7 +1283,7 @@ $ yer işareti \n ile eşleşir, ancak \r\n (satır başı ve yeni satır karakt name - name + ad @@ -1383,7 +1383,7 @@ Two or more character ranges can be concatenated. For example, to specify the ra no - no + hayır @@ -1766,7 +1766,7 @@ ECMAScript uyumlu davranış belirtilmişse, \w [a-zA-Z_0-9] ile eşdeğerdir yes - yes + evet @@ -1832,7 +1832,7 @@ Sıfır genişlikli pozitif geri yönlü onaylamalar genellikle normal ifadeleri Remove 'async' modifier - Remove 'async' modifier + 'async' değiştiricisini kaldırın @@ -1887,7 +1887,7 @@ Sıfır genişlikli pozitif geri yönlü onaylamalar genellikle normal ifadeleri The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. - The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + '{1}' türünü içeren '{0}' bütünleştirilmiş kodu, desteklenmeyen .NET Framework'e başvuruyor. @@ -2092,22 +2092,22 @@ Sıfır genişlikli pozitif geri yönlü onaylamalar genellikle normal ifadeleri '{0}' cannot be null or empty. - '{0}' null veya boş olamaz. + '{0}' null veya boş olamaz. '{0}' cannot be null or whitespace. - '{0}' null veya boşluk karakteri olamaz. + '{0}' null veya boşluk olamaz. '{0}' is not null here. - '{0}' is not null here. + '{0}' burada null değil. '{0}' may be null here. - '{0}' may be null here. + '{0}' burada null olabilir. @@ -2662,12 +2662,12 @@ If the "M" format specifier is used without other custom format specifiers, it's Add optional parameters to '{0}' - {0}' öğesine isteğe bağlı parametreler ekle + '{0}' öğesine isteğe bağlı parametreler ekle Add parameters to '{0}' - {0}' öğesine parametre ekle + '{0}' öğesine parametre ekle @@ -2702,7 +2702,7 @@ If the "M" format specifier is used without other custom format specifiers, it's Generate constructor in '{0}' - {0}' içinde oluşturucu üretin + '{0}' içinde oluşturucu üretin @@ -2777,22 +2777,22 @@ If the "M" format specifier is used without other custom format specifiers, it's Introduce field for '{0}' - {0}' için alanı ortaya çıkar + '{0}' için alanı ortaya çıkar Introduce local for '{0}' - {0}' için yereli ortaya çıkar + '{0}' için yereli ortaya çıkar Introduce constant for '{0}' - {0}' için sabiti ortaya çıkar + '{0}' için sabiti ortaya çıkar Introduce local constant for '{0}' - {0}' için yerel sabiti ortaya çıkar + '{0}' için yerel sabiti ortaya çıkar @@ -2822,7 +2822,7 @@ If the "M" format specifier is used without other custom format specifiers, it's Introduce query variable for '{0}' - {0}' için sorgu değişkenini ortaya çıkar + '{0}' için sorgu değişkenini ortaya çıkar @@ -2941,7 +2941,7 @@ If the "g" format specifier is used without other custom format specifiers, it's Updating '{0}' will prevent the debug session from continuing. - {0}' öğesini güncelleştirme, hata ayıklama oturumunun devam etmesini engelleyecek. + '{0}' öğesini güncelleştirme, hata ayıklama oturumunun devam etmesini engelleyecek. @@ -2961,12 +2961,12 @@ If the "g" format specifier is used without other custom format specifiers, it's Ceasing to capture variable '{0}' will prevent the debug session from continuing. - {0}' değişkenini yakalamanın durdurulması hata ayıklama oturumunun devam etmesini engeller. + '{0}' değişkenini yakalamanın durdurulması hata ayıklama oturumunun devam etmesini engeller. Deleting captured variable '{0}' will prevent the debug session from continuing. - {0}' yakalanan değişkeninin silinmesi hata ayıklama oturumunun devam etmesini engeller. + '{0}' yakalanan değişkeninin silinmesi hata ayıklama oturumunun devam etmesini engeller. @@ -2976,22 +2976,22 @@ If the "g" format specifier is used without other custom format specifiers, it's Changing the parameters of '{0}' will prevent the debug session from continuing. - {0}' parametrelerinin değiştirilmesi hata ayıklama oturumunun devam etmesini engeller. + '{0}' parametrelerinin değiştirilmesi hata ayıklama oturumunun devam etmesini engeller. Changing the return type of '{0}' will prevent the debug session from continuing. - {0}' dönüş türünün değiştirilmesi hata ayıklama oturumunun devam etmesini engeller. + '{0}' dönüş türünün değiştirilmesi hata ayıklama oturumunun devam etmesini engeller. Changing the type of '{0}' will prevent the debug session from continuing. - {0}' türünün değiştirilmesi hata ayıklama oturumunun devam etmesini engeller. + '{0}' türünün değiştirilmesi hata ayıklama oturumunun devam etmesini engeller. Changing the declaration scope of a captured variable '{0}' will prevent the debug session from continuing. - {0}' yakalanan değişkeninin bildirim kapsamının değiştirilmesi hata ayıklama oturumunun devam etmesini engeller. + '{0}' yakalanan değişkeninin bildirim kapsamının değiştirilmesi hata ayıklama oturumunun devam etmesini engeller. @@ -3016,7 +3016,7 @@ If the "g" format specifier is used without other custom format specifiers, it's Adding '{0}' into a '{1}' will prevent the debug session from continuing. - {1}' içine '{0}' ekleme, hata ayıklama oturumunun devam etmesini engelleyecek. + '{1}' içine '{0}' ekleme, hata ayıklama oturumunun devam etmesini engelleyecek. @@ -3026,17 +3026,17 @@ If the "g" format specifier is used without other custom format specifiers, it's Updating the modifiers of '{0}' will prevent the debug session from continuing. - {0}' öğesinin değiştiricilerini güncelleştirme, hata ayıklama oturumunun devam etmesini engelleyecek. + '{0}' öğesinin değiştiricilerini güncelleştirme, hata ayıklama oturumunun devam etmesini engelleyecek. Updating the Handles clause of '{0}' will prevent the debug session from continuing. - {0}' öğesinin Handles yan tümcesini güncelleştirme, hata ayıklama oturumunun devam etmesini engelleyecek. + '{0}' öğesinin Handles yan tümcesini güncelleştirme, hata ayıklama oturumunun devam etmesini engelleyecek. Adding '{0}' with the Handles clause will prevent the debug session from continuing. - {0}', Handles yan tümcesi ile eklendiğinde hata ayıklama oturumunun devam etmesini engeller. + '{0}', Handles yan tümcesi ile eklendiğinde hata ayıklama oturumunun devam etmesini engeller. @@ -3051,32 +3051,32 @@ If the "g" format specifier is used without other custom format specifiers, it's Updating the variance of '{0}' will prevent the debug session from continuing. - {0}' öğesinin farkını güncelleştirme, hata ayıklama oturumunun devam etmesini engelleyecek. + '{0}' öğesinin farkını güncelleştirme, hata ayıklama oturumunun devam etmesini engelleyecek. Updating the type of '{0}' will prevent the debug session from continuing. - {0}' öğesinin türünü güncelleştirme, hata ayıklama oturumunun devam etmesini engelleyecek. + '{0}' öğesinin türünü güncelleştirme, hata ayıklama oturumunun devam etmesini engelleyecek. Updating the initializer of '{0}' will prevent the debug session from continuing. - {0}' öğesinin başlatıcısını güncelleştirme, hata ayıklama oturumunun devam etmesini engelleyecek. + '{0}' öğesinin başlatıcısını güncelleştirme, hata ayıklama oturumunun devam etmesini engelleyecek. Updating the size of a '{0}' will prevent the debug session from continuing. - {0}' öğesinin boyutunu güncelleştirme, hata ayıklama oturumunun devam etmesini engelleyecek. + '{0}' öğesinin boyutunu güncelleştirme, hata ayıklama oturumunun devam etmesini engelleyecek. Updating the underlying type of '{0}' will prevent the debug session from continuing. - {0}' öğesinin temel alınan türünü güncelleştirme, hata ayıklama oturumunun devam etmesini engelleyecek. + '{0}' öğesinin temel alınan türünü güncelleştirme, hata ayıklama oturumunun devam etmesini engelleyecek. Updating the base class and/or base interface(s) of '{0}' will prevent the debug session from continuing. - {0}' öğesinin temel sınıf ve/veya temel arabirimlerini güncelleştirme, hata ayıklama oturumunun devam etmesini engelleyecek. + '{0}' öğesinin temel sınıf ve/veya temel arabirimlerini güncelleştirme, hata ayıklama oturumunun devam etmesini engelleyecek. @@ -3111,12 +3111,12 @@ If the "g" format specifier is used without other custom format specifiers, it's Renaming '{0}' will prevent the debug session from continuing. - {0}' öğesini yeniden adlandırma, hata ayıklama oturumunun devam etmesini engelleyecek. + '{0}' öğesini yeniden adlandırma, hata ayıklama oturumunun devam etmesini engelleyecek. Adding '{0}' will prevent the debug session from continuing. - {0}' öğesini ekleme, hata ayıklama oturumunun devam etmesini engelleyecek. + '{0}' öğesini ekleme, hata ayıklama oturumunun devam etmesini engelleyecek. @@ -3156,12 +3156,12 @@ If the "g" format specifier is used without other custom format specifiers, it's Moving '{0}' will prevent the debug session from continuing. - {0}' öğesinin taşınması, hata ayıklama oturumunun devam etmesini engelleyecek. + '{0}' öğesinin taşınması, hata ayıklama oturumunun devam etmesini engelleyecek. Deleting '{0}' will prevent the debug session from continuing. - {0}' öğesini silme, hata ayıklama oturumunun devam etmesini engelleyecek. + '{0}' öğesini silme, hata ayıklama oturumunun devam etmesini engelleyecek. @@ -3281,7 +3281,7 @@ If the "g" format specifier is used without other custom format specifiers, it's Attribute '{0}' is missing. Updating an async method or an iterator will prevent the debug session from continuing. - {0}' özniteliği eksik. Zaman uyumsuz bir metodun veya bir yineleyicinin güncelleştirilmesi, hata ayıklama oturumunun devam etmesini engeller. + '{0}' özniteliği eksik. Zaman uyumsuz bir metodun veya bir yineleyicinin güncelleştirilmesi, hata ayıklama oturumunun devam etmesini engeller. @@ -3311,7 +3311,7 @@ If the "g" format specifier is used without other custom format specifiers, it's Requested assembly already loaded from '{0}'. - {0}' kaynağından zaten yüklenmiş olan derleme istendi. + '{0}' kaynağından zaten yüklenmiş olan derleme istendi. @@ -3360,13 +3360,13 @@ Devam etmek istiyor musunuz? Analyzer '{0}' threw an exception of type '{1}' with message '{2}'. - {0}' çözümleyicisi '{2}' iletisiyle '{1}' türünde bir özel durum oluşturdu. + '{0}' çözümleyicisi '{2}' iletisiyle '{1}' türünde bir özel durum oluşturdu. Analyzer '{0}' threw the following exception: '{1}'. - {0}' çözümleyicisi şu özel durumu oluşturdu: + '{0}' çözümleyicisi şu özel durumu oluşturdu: '{1}'. @@ -3467,7 +3467,7 @@ Devam etmek istiyor musunuz? Reported diagnostic with ID '{0}' is not supported by the analyzer. - {0}' kimliği ile bildirilen tanılama, çözümleyici tarafından desteklenmiyor. + '{0}' kimliği ile bildirilen tanılama, çözümleyici tarafından desteklenmiyor. @@ -3740,12 +3740,12 @@ DateTimeOffset değerleri için "K" biçim belirticisi "zzz" biçim belirticisin Replace '{0}' and '{1}' with property - {0}' ve '{1}' öğesini özellikle değiştir + '{0}' ve '{1}' öğesini özellikle değiştir Replace '{0}' with property - {0}' öğesini özellikle değiştir + '{0}' öğesini özellikle değiştir @@ -3755,7 +3755,7 @@ DateTimeOffset değerleri için "K" biçim belirticisi "zzz" biçim belirticisin Generate type '{0}' - {0}' türünü oluştur + '{0}' türünü oluştur @@ -3765,7 +3765,7 @@ DateTimeOffset değerleri için "K" biçim belirticisi "zzz" biçim belirticisin Change '{0}' to '{1}'. - {0}' öğesini '{1}' olarak değiştirin. + '{0}' öğesini '{1}' olarak değiştirin. @@ -3821,7 +3821,7 @@ DateTimeOffset değerleri için "K" biçim belirticisi "zzz" biçim belirticisin Use locally installed '{0}' version '{1}' This version used in: {2} - {0}' uygulamasının yerel olarak yüklü '{1}' sürümünü kullanın + '{0}' uygulamasının yerel olarak yüklü '{1}' sürümünü kullanın Bu sürüm şurada kullanılır: {2} @@ -3842,12 +3842,12 @@ Bu sürüm şurada kullanılır: {2} Install version '{0}' - {0}' sürümünü yükle + '{0}' sürümünü yükle Generate variable '{0}' - {0}' değişkenini oluştur + '{0}' değişkenini oluştur @@ -3932,12 +3932,12 @@ Bu sürüm şurada kullanılır: {2} Replace '{0}' with method - {0}' yerine metot kullan + '{0}' yerine metot kullan Replace '{0}' with methods - {0}' yerine metotlar kullan + '{0}' yerine metotlar kullan @@ -4002,7 +4002,7 @@ Bu sürüm şurada kullanılır: {2} Install package '{0}' - {0}' paketini yükle + '{0}' paketini yükle @@ -4012,12 +4012,12 @@ Bu sürüm şurada kullanılır: {2} Fully qualify '{0}' - {0}' adını tam olarak belirtin + '{0}' adını tam olarak belirtin Remove reference to '{0}'. - {0}' başvurusunu kaldırın. + '{0}' başvurusunu kaldırın. @@ -4052,22 +4052,22 @@ Bu sürüm şurada kullanılır: {2} Remove document '{0}' - {0}' belgesini kaldır + '{0}' belgesini kaldır Add document '{0}' - {0}' belgesini ekle + '{0}' belgesini ekle Add argument name '{0}' - {0}' bağımsız değişken adını ekle + '{0}' bağımsız değişken adını ekle Take '{0}' - {0}' al + '{0}' al @@ -4127,7 +4127,7 @@ Bu sürüm şurada kullanılır: {2} Add parameter to '{0}' - {0}' öğesine parametre ekle + '{0}' öğesine parametre ekle @@ -4172,12 +4172,12 @@ Bu sürüm şurada kullanılır: {2} Initialize field '{0}' - {0}' alanını başlat + '{0}' alanını başlat Initialize property '{0}' - {0}' özelliğini başlat + '{0}' özelliğini başlat @@ -4242,7 +4242,7 @@ Bu sürüm şurada kullanılır: {2} Add argument name '{0}' (including trailing arguments) - {0}' bağımsız değişken adını ekle (sondaki bağımsız değişkenler dahil) + '{0}' bağımsız değişken adını ekle (sondaki bağımsız değişkenler dahil) diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hans.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hans.xlf index 60a854a201fcb..a9cb2f0cbd6c9 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hans.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + AM/PM (abbreviated) @@ -162,7 +162,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma <infer> - <infer> + <推断> @@ -347,7 +347,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Extract base class... - Extract base class... + 提取基类... @@ -502,12 +502,12 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Inline '{0}' - Inline '{0}' + 内联“{0}” Inline and keep '{0}' - Inline and keep '{0}' + 内联并保留“{0}” @@ -607,17 +607,17 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. - Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. + 修改“{0}”的主体将阻止调试会话继续,因为主体包含的语句过多。 Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} - Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} + 修改“{0}”的主体将防止调试会话继续,原因是出现内部错误: {1} Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. - Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. + 修改源文件“{0}”将阻止调试会话继续,因为该文件太大。 @@ -642,7 +642,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Modifying source file '{0}' will prevent the debug session from continuing due to internal error: {1} - 修改源文件 {0} 将防止调试会话因内部错误 {1} 而继续进行。 + 修改源文件“{0}”将防止调试会话继续,原因是出现内部错误: {1} @@ -652,7 +652,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma No valid location to insert method call. - No valid location to insert method call. + 没有插入方法调用的有效位置。 @@ -682,7 +682,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Pull member(s) up to new base class... - Pull member(s) up to new base class... + 将成员拉取到新的基类... @@ -1013,7 +1013,7 @@ $ 定位点匹配 \n,但不匹配 \r\n (回车符和换行符的组合,或 C expression - expression + 表达式 @@ -1283,7 +1283,7 @@ $ 定位点匹配 \n,但不匹配 \r\n (回车符和换行符的组合,或 C name - name + 名称 @@ -1383,7 +1383,7 @@ Two or more character ranges can be concatenated. For example, to specify the ra no - no + @@ -1766,7 +1766,7 @@ If ECMAScript-compliant behavior is specified, \w is equivalent to [a-zA-Z_0-9]< yes - yes + @@ -1887,7 +1887,7 @@ Zero-width positive lookbehind assertions are typically used at the beginning of The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. - The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + 包含类型“{1}”的程序集“{0}”引用了 .NET Framework,而此操作不受支持。 @@ -2092,22 +2092,22 @@ Zero-width positive lookbehind assertions are typically used at the beginning of '{0}' cannot be null or empty. - “{0}”不能是 Null 或为空。 + “{0}”不能为 Null 或空。 '{0}' cannot be null or whitespace. - “{0}”不能为 Null 或空白。 + “{0}”不能为 null 或空白。 '{0}' is not null here. - '{0}' is not null here. + “{0}”在此处不为 null。 '{0}' may be null here. - '{0}' may be null here. + “{0}”可能在此处为 null。 @@ -2926,7 +2926,7 @@ If the "g" format specifier is used without other custom format specifiers, it's generating source for symbols of this type is not supported - 不支持为此类型符号生成源。 + 不支持为此类型符号生成源 diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hant.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hant.xlf index a2c5752c26dfc..1820365b1d9b0 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hant.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + AM/PM (abbreviated) @@ -347,7 +347,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Extract base class... - Extract base class... + 擷取基底類別... @@ -502,12 +502,12 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Inline '{0}' - Inline '{0}' + 內嵌 '{0}' Inline and keep '{0}' - Inline and keep '{0}' + 內嵌並保留 '{0}' @@ -542,7 +542,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Make class 'abstract' - Make class 'abstract' + 將類別設為 'abstract' @@ -607,17 +607,17 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. - Modifying the body of '{0}' will prevent the debug session from continuing because the body has too many statements. + 因為 '{0}' 的主體有過多陳述式,所以修改該主體將導致偵錯工作階段無法繼續進行。 Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} - Modifying the body of '{0}' will prevent the debug session from continuing due to internal error: {1} + 因為內部錯誤,所以修改 '{0}' 的主體將導致偵錯工作階段無法繼續進行: {1} Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. - Modifying source file '{0}' will prevent the debug session from continuing because the file is too big. + 因為來源檔案 '{0}' 過大,所以修改該檔案將導致偵錯工作階段無法繼續進行。 @@ -642,7 +642,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Modifying source file '{0}' will prevent the debug session from continuing due to internal error: {1} - 修改原始檔案 {0} 將防止調試會話由於內部錯誤而繼續進行: {1}。 + 因為內部錯誤,所以修改來源檔案 '{0}' 將導致偵錯工作階段無法繼續進行: {1} @@ -652,7 +652,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma No valid location to insert method call. - No valid location to insert method call. + 沒有可插入方法呼叫的有效位置。 @@ -682,7 +682,7 @@ Make sure to use the "tt" specifier for languages for which it's necessary to ma Pull member(s) up to new base class... - Pull member(s) up to new base class... + 將成員提取至新的基底類別... @@ -1013,7 +1013,7 @@ $ 錨點會比對 \n,但不會比對 \r\n (歸位與新行字元的組合, expression - expression + 運算式 @@ -1283,7 +1283,7 @@ $ 錨點會比對 \n,但不會比對 \r\n (歸位與新行字元的組合, name - name + 名稱 @@ -1383,7 +1383,7 @@ Two or more character ranges can be concatenated. For example, to specify the ra no - no + @@ -1766,7 +1766,7 @@ If ECMAScript-compliant behavior is specified, \w is equivalent to [a-zA-Z_0-9]< yes - yes + @@ -1832,7 +1832,7 @@ Zero-width positive lookbehind assertions are typically used at the beginning of Remove 'async' modifier - Remove 'async' modifier + 移除 'async' 修飾元 @@ -1887,7 +1887,7 @@ Zero-width positive lookbehind assertions are typically used at the beginning of The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. - The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + 包含類型 '{1}' 的組件 '{0}' 參考了 .NET Framework,此情形不受支援。 @@ -2092,22 +2092,22 @@ Zero-width positive lookbehind assertions are typically used at the beginning of '{0}' cannot be null or empty. - {0} 不得為 Null 或空白。 + '{0}' 不可為 Null 或空白。 '{0}' cannot be null or whitespace. - {0} 不得為 Null 或空白字元。 + '{0}' 不得為 Null 或空白字元。 '{0}' is not null here. - '{0}' is not null here. + '{0}' 在此不是 null。 '{0}' may be null here. - '{0}' may be null here. + '{0}' 在此可能為 null。 diff --git a/src/Features/LanguageServer/Protocol/CustomProtocol/FindUsagesLSPContext.cs b/src/Features/LanguageServer/Protocol/CustomProtocol/FindUsagesLSPContext.cs index 5fd3e9d5f6052..a42b1c843aa45 100644 --- a/src/Features/LanguageServer/Protocol/CustomProtocol/FindUsagesLSPContext.cs +++ b/src/Features/LanguageServer/Protocol/CustomProtocol/FindUsagesLSPContext.cs @@ -9,12 +9,15 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; +using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.FindSymbols.Finders; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.MetadataAsSource; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Text.Adornments; using Roslyn.Utilities; @@ -94,7 +97,7 @@ public override async ValueTask OnDefinitionFoundAsync(DefinitionItem definition var definitionItem = await GenerateVSReferenceItemAsync( _id, definitionId: _id, _document, _position, definition.SourceSpans.FirstOrDefault(), definition.DisplayableProperties, _metadataAsSourceFileService, definition.GetClassifiedText(), - definition.Tags.GetFirstGlyph(), symbolUsageInfo: null, CancellationToken).ConfigureAwait(false); + definition.Tags.GetFirstGlyph(), symbolUsageInfo: null, isWrittenTo: false, CancellationToken).ConfigureAwait(false); if (definitionItem != null) { @@ -136,7 +139,7 @@ public override async ValueTask OnReferenceFoundAsync(SourceReferenceItem refere var referenceItem = await GenerateVSReferenceItemAsync( _id, definitionId, _document, _position, reference.SourceSpan, reference.AdditionalProperties, _metadataAsSourceFileService, definitionText: null, - definitionGlyph: Glyph.None, reference.SymbolUsageInfo, CancellationToken).ConfigureAwait(false); + definitionGlyph: Glyph.None, reference.SymbolUsageInfo, reference.IsWrittenTo, CancellationToken).ConfigureAwait(false); if (referenceItem != null) { @@ -156,17 +159,14 @@ public override async ValueTask OnReferenceFoundAsync(SourceReferenceItem refere ClassifiedTextElement? definitionText, Glyph definitionGlyph, SymbolUsageInfo? symbolUsageInfo, + bool isWrittenTo, CancellationToken cancellationToken) { var location = await ComputeLocationAsync(document, position, documentSpan, metadataAsSourceFileService, cancellationToken).ConfigureAwait(false); - if (location == null) - { - return null; - } // Getting the text for the Text property. If we somehow can't compute the text, that means we're probably dealing with a metadata // reference, and those don't show up in the results list in Roslyn FAR anyway. - var text = await ComputeTextAsync(id, definitionId, documentSpan, definitionText, cancellationToken).ConfigureAwait(false); + var text = await ComputeTextAsync(id, definitionId, documentSpan, definitionText, isWrittenTo, cancellationToken).ConfigureAwait(false); if (text == null) { return null; @@ -179,14 +179,19 @@ public override async ValueTask OnReferenceFoundAsync(SourceReferenceItem refere DefinitionId = definitionId, DefinitionText = definitionText, // Only definitions should have a non-null DefinitionText DefinitionIcon = definitionGlyph.GetImageElement(), - DisplayPath = location.Uri.LocalPath, + DisplayPath = location?.Uri.LocalPath, Id = id, Kind = symbolUsageInfo.HasValue ? ProtocolConversions.SymbolUsageInfoToReferenceKinds(symbolUsageInfo.Value) : Array.Empty(), - Location = location, ResolutionStatus = ResolutionStatusKind.ConfirmedAsReference, Text = text, }; + // There are certain items that may not have locations, such as namespace definitions. + if (location != null) + { + result.Location = location; + } + if (documentSpan.Document != null) { result.DocumentName = documentSpan.Document.Name; @@ -201,6 +206,7 @@ public override async ValueTask OnReferenceFoundAsync(SourceReferenceItem refere return result; + // Local functions static async Task ComputeLocationAsync( Document document, int position, @@ -210,15 +216,17 @@ public override async ValueTask OnReferenceFoundAsync(SourceReferenceItem refere { if (documentSpan != default) { - // We do have a source span, so compute location normally. + // We do have a document span, so compute location normally. return await ProtocolConversions.DocumentSpanToLocationAsync(documentSpan, cancellationToken).ConfigureAwait(false); } - // If we have no source span, our location may be in metadata. + // If we have no document span, our location may be in metadata or may be a namespace. var symbol = await SymbolFinder.FindSymbolAtPositionAsync(document, position, cancellationToken).ConfigureAwait(false); - if (symbol == null || symbol.Locations == null || symbol.Locations.IsEmpty || !symbol.Locations.First().IsInMetadata) + if (symbol == null || symbol.Locations.IsEmpty || symbol.Kind == SymbolKind.Namespace) { - // We couldn't find the location in metadata and it's not in any of our known documents. + // Either: + // (1) We couldn't find the location in metadata and it's not in any of our known documents. + // (2) The symbol is a namespace (and therefore has no location). return null; } @@ -247,28 +255,74 @@ public override async ValueTask OnReferenceFoundAsync(SourceReferenceItem refere } } - static async Task ComputeTextAsync( + static async Task ComputeTextAsync( int id, int? definitionId, DocumentSpan documentSpan, ClassifiedTextElement? definitionText, + bool isWrittenTo, CancellationToken cancellationToken) { - if (id == definitionId) - { - return definitionText; - } - else if (documentSpan != default) + // General case + if (documentSpan != default) { var classifiedSpansAndHighlightSpan = await ClassifiedSpansAndHighlightSpanFactory.ClassifyAsync( documentSpan, cancellationToken).ConfigureAwait(false); var classifiedSpans = classifiedSpansAndHighlightSpan.ClassifiedSpans; var docText = await documentSpan.Document.GetTextAsync(cancellationToken).ConfigureAwait(false); + var classifiedTextRuns = GetClassifiedTextRuns(id, definitionId, documentSpan, isWrittenTo, classifiedSpans, docText); - return new ClassifiedTextElement( - classifiedSpans.Select(cspan => new ClassifiedTextRun(cspan.ClassificationType, docText.ToString(cspan.TextSpan)))); + return new ClassifiedTextElement(classifiedTextRuns.ToArray()); + } + // Certain definitions may not have a DocumentSpan, such as namespace and metadata definitions + else if (id == definitionId) + { + return definitionText; } return null; + + // Nested local functions + static ClassifiedTextRun[] GetClassifiedTextRuns( + int id, int? definitionId, + DocumentSpan documentSpan, + bool isWrittenTo, + ImmutableArray classifiedSpans, + SourceText docText) + { + using var _ = ArrayBuilder.GetInstance(out var classifiedTextRuns); + foreach (var span in classifiedSpans) + { + // Default case: Don't highlight. For example, if the user invokes FAR on 'x' in 'var x = 1', then 'var', + // '=', and '1' should not be highlighted. + string? markerTagType = null; + + // Case 1: Highlight this span of text. For example, if the user invokes FAR on 'x' in 'var x = 1', + // then 'x' should be highlighted. + if (span.TextSpan == documentSpan.SourceSpan) + { + // Case 1a: Highlight a definition + if (id == definitionId) + { + markerTagType = DefinitionHighlightTag.TagId; + } + // Case 1b: Highlight a written reference + else if (isWrittenTo) + { + markerTagType = WrittenReferenceHighlightTag.TagId; + } + // Case 1c: Highlight a read reference + else + { + markerTagType = ReferenceHighlightTag.TagId; + } + } + + classifiedTextRuns.Add(new ClassifiedTextRun( + span.ClassificationType, docText.ToString(span.TextSpan), ClassifiedTextRunStyle.Plain, markerTagType)); + } + + return classifiedTextRuns.ToArray(); + } } } diff --git a/src/Features/LanguageServer/Protocol/Extensions/Extensions.cs b/src/Features/LanguageServer/Protocol/Extensions/Extensions.cs index c0df9165e822d..cfe56d9104696 100644 --- a/src/Features/LanguageServer/Protocol/Extensions/Extensions.cs +++ b/src/Features/LanguageServer/Protocol/Extensions/Extensions.cs @@ -105,6 +105,22 @@ private static ImmutableArray GetDocuments(this ILspSolutionProvider solut return null; } + return GetDocument(documentIdentifier, documents); + } + + public static Document? GetDocument(this Solution solution, TextDocumentIdentifier documentIdentifier) + { + var documents = solution.GetDocuments(documentIdentifier.Uri); + if (documents.Length == 0) + { + return null; + } + + return GetDocument(documentIdentifier, documents); + } + + private static T GetDocument(TextDocumentIdentifier documentIdentifier, ImmutableArray documents) where T : TextDocument + { if (documents.Length > 1) { // We have more than one document; try to find the one that matches the right context diff --git a/src/Features/LanguageServer/Protocol/Extensions/ProtocolConversions.cs b/src/Features/LanguageServer/Protocol/Extensions/ProtocolConversions.cs index cad3c1d1e1be7..cf78c0b8f652f 100644 --- a/src/Features/LanguageServer/Protocol/Extensions/ProtocolConversions.cs +++ b/src/Features/LanguageServer/Protocol/Extensions/ProtocolConversions.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -11,11 +12,11 @@ using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.NavigateTo; +using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Tags; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Text.Adornments; -using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; using Logger = Microsoft.CodeAnalysis.Internal.Log.Logger; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; @@ -113,7 +114,10 @@ public static LSP.TextDocumentPositionParams PositionToTextDocumentPositionParam } public static LSP.TextDocumentIdentifier DocumentToTextDocumentIdentifier(Document document) - => new LSP.TextDocumentIdentifier() { Uri = document.GetURI() }; + => new LSP.TextDocumentIdentifier { Uri = document.GetURI() }; + + public static LSP.VersionedTextDocumentIdentifier DocumentToVersionedTextDocumentIdentifier(Document document) + => new LSP.VersionedTextDocumentIdentifier { Uri = document.GetURI() }; public static LinePosition PositionToLinePosition(LSP.Position position) => new LinePosition(position.Line, position.Character); @@ -127,13 +131,13 @@ public static TextSpan RangeToTextSpan(LSP.Range range, SourceText text) return text.Lines.GetTextSpan(linePositionSpan); } - public static LSP.TextEdit TextChangeToTextEdit(TextChange textChange, SourceText text) + public static LSP.TextEdit TextChangeToTextEdit(TextChange textChange, SourceText oldText) { Contract.ThrowIfNull(textChange.NewText); return new LSP.TextEdit { NewText = textChange.NewText, - Range = TextSpanToRange(textChange.Span, text) + Range = TextSpanToRange(textChange.Span, oldText) }; } @@ -167,25 +171,87 @@ public static LSP.Range TextSpanToRange(TextSpan textSpan, SourceText text) }; } - public static async Task TextSpanToLocationAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken) + /// + /// Compute all the for the input list of changed documents. + /// Additionally maps the locations of the changed documents if necessary. + /// + public static async Task ChangedDocumentsToTextDocumentEditsAsync(IEnumerable changedDocuments, Func getNewDocumentFunc, + Func getOldDocumentFunc, IDocumentTextDifferencingService? textDiffService, CancellationToken cancellationToken) where T : TextDocument { - var spanMappingService = document.Services.GetService(); + using var _ = ArrayBuilder<(Uri Uri, LSP.TextEdit TextEdit)>.GetInstance(out var uriToTextEdits); - if (spanMappingService == null) + foreach (var docId in changedDocuments) { - return await ConvertTextSpanToLocation(document, textSpan, cancellationToken).ConfigureAwait(false); + var newDocument = getNewDocumentFunc(docId); + var oldDocument = getOldDocumentFunc(docId); + + var oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); + + ImmutableArray textChanges; + + // Normal documents have a unique service for calculating minimal text edits. If we used the standard 'GetTextChanges' + // method instead, we would get a change that spans the entire document, which we ideally want to avoid. + if (newDocument is Document newDoc && oldDocument is Document oldDoc) + { + Contract.ThrowIfNull(textDiffService); + textChanges = await textDiffService.GetTextChangesAsync(oldDoc, newDoc, cancellationToken).ConfigureAwait(false); + } + else + { + var newText = await newDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); + textChanges = newText.GetTextChanges(oldText).ToImmutableArray(); + } + + // Map all the text changes' spans for this document. + var mappedResults = await GetMappedSpanResultAsync(oldDocument, textChanges.Select(tc => tc.Span).ToImmutableArray(), cancellationToken).ConfigureAwait(false); + if (mappedResults == null) + { + // There's no span mapping available, just create text edits from the original text changes. + foreach (var textChange in textChanges) + { + uriToTextEdits.Add((oldDocument.GetURI(), TextChangeToTextEdit(textChange, oldText))); + } + } + else + { + // We have mapping results, so create text edits from the mapped text change spans. + for (var i = 0; i < textChanges.Length; i++) + { + var mappedSpan = mappedResults.Value[i]; + var textChange = textChanges[i]; + if (!mappedSpan.IsDefault) + { + uriToTextEdits.Add((GetUriFromFilePath(mappedSpan.FilePath), new LSP.TextEdit + { + Range = MappedSpanResultToRange(mappedSpan), + NewText = textChange.NewText ?? string.Empty + })); + } + } + } } - var mappedSpanResult = await spanMappingService.MapSpansAsync(document, SpecializedCollections.SingletonEnumerable(textSpan), cancellationToken).ConfigureAwait(false); - if (mappedSpanResult.IsDefaultOrEmpty) + var documentEdits = uriToTextEdits.GroupBy(uriAndEdit => uriAndEdit.Uri, uriAndEdit => uriAndEdit.TextEdit, (uri, edits) => new TextDocumentEdit + { + TextDocument = new VersionedTextDocumentIdentifier { Uri = uri }, + Edits = edits.ToArray(), + }).ToArray(); + + return documentEdits; + } + + public static async Task TextSpanToLocationAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken) + { + var result = await GetMappedSpanResultAsync(document, ImmutableArray.Create(textSpan), cancellationToken).ConfigureAwait(false); + if (result == null) { return await ConvertTextSpanToLocation(document, textSpan, cancellationToken).ConfigureAwait(false); } - var mappedSpan = mappedSpanResult.Single(); + var mappedSpan = result.Value.Single(); if (mappedSpan.IsDefault) { - return null; + return await ConvertTextSpanToLocation(document, textSpan, cancellationToken).ConfigureAwait(false); } return new LSP.Location @@ -201,15 +267,6 @@ public static LSP.Range TextSpanToRange(TextSpan textSpan, SourceText text) return ConvertTextSpanWithTextToLocation(span, text, document.GetURI()); } - static LSP.Range MappedSpanResultToRange(MappedSpanResult mappedSpanResult) - { - return new LSP.Range - { - Start = LinePositionToPosition(mappedSpanResult.LinePositionSpan.Start), - End = LinePositionToPosition(mappedSpanResult.LinePositionSpan.End) - }; - } - static LSP.Location ConvertTextSpanWithTextToLocation(TextSpan span, SourceText text, Uri documentUri) { var location = new LSP.Location @@ -417,7 +474,7 @@ public static Glyph CompletionItemKindToGlyph(LSP.CompletionItemKind kind) // The mappings here are roughly based off of SymbolUsageInfoExtensions.ToSymbolReferenceKinds. public static LSP.ReferenceKind[] SymbolUsageInfoToReferenceKinds(SymbolUsageInfo symbolUsageInfo) { - var referenceKinds = ArrayBuilder.GetInstance(); + using var _ = ArrayBuilder.GetInstance(out var referenceKinds); if (symbolUsageInfo.ValueUsageInfoOpt.HasValue) { var usageInfo = symbolUsageInfo.ValueUsageInfoOpt.Value; @@ -483,7 +540,7 @@ public static LSP.ReferenceKind[] SymbolUsageInfoToReferenceKinds(SymbolUsageInf } } - return referenceKinds.ToArrayAndFree(); + return referenceKinds.ToArray(); } public static string ProjectIdToProjectContextId(ProjectId id) @@ -499,5 +556,33 @@ public static ProjectId ProjectContextToProjectId(ProjectContext projectContext) Guid.Parse(projectContext.Id.Substring(0, delimiter)), debugName: projectContext.Id.Substring(delimiter + 1)); } + + private static async Task?> GetMappedSpanResultAsync(TextDocument textDocument, ImmutableArray textSpans, CancellationToken cancellationToken) + { + if (textDocument is not Document document) + { + return null; + } + + var spanMappingService = document.Services.GetService(); + if (spanMappingService == null) + { + return null; + } + + var mappedSpanResult = await spanMappingService.MapSpansAsync(document, textSpans, cancellationToken).ConfigureAwait(false); + Contract.ThrowIfFalse(textSpans.Length == mappedSpanResult.Length, + $"The number of input spans {textSpans.Length} should match the number of mapped spans returned {mappedSpanResult.Length}"); + return mappedSpanResult; + } + + private static LSP.Range MappedSpanResultToRange(MappedSpanResult mappedSpanResult) + { + return new LSP.Range + { + Start = LinePositionToPosition(mappedSpanResult.LinePositionSpan.Start), + End = LinePositionToPosition(mappedSpanResult.LinePositionSpan.End) + }; + } } } diff --git a/src/Features/LanguageServer/Protocol/Handler/CodeActions/CodeActionResolveHandler.cs b/src/Features/LanguageServer/Protocol/Handler/CodeActions/CodeActionResolveHandler.cs index 3b4e75d29cf8f..f6c821f1f7675 100644 --- a/src/Features/LanguageServer/Protocol/Handler/CodeActions/CodeActionResolveHandler.cs +++ b/src/Features/LanguageServer/Protocol/Handler/CodeActions/CodeActionResolveHandler.cs @@ -14,6 +14,7 @@ using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer.Handler.CodeActions; using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Newtonsoft.Json.Linq; @@ -130,22 +131,24 @@ public CodeActionResolveHandler( var changedAdditionalDocuments = projectChanges.SelectMany(pc => pc.GetChangedAdditionalDocuments()); // Changed documents - await AddTextDocumentEditsAsync( - textDocumentEdits, changedDocuments, - applyChangesOperation.ChangedSolution.GetDocument, solution.GetDocument, textDiffService, - cancellationToken).ConfigureAwait(false); + var documentEdits = await ProtocolConversions.ChangedDocumentsToTextDocumentEditsAsync( + changedDocuments, applyChangesOperation.ChangedSolution.GetRequiredDocument, solution.GetRequiredDocument, + textDiffService, cancellationToken).ConfigureAwait(false); + textDocumentEdits.AddRange(documentEdits); // Changed analyzer config documents - await AddTextDocumentEditsAsync( - textDocumentEdits, changedAnalyzerConfigDocuments, - applyChangesOperation.ChangedSolution.GetAnalyzerConfigDocument, solution.GetAnalyzerConfigDocument, - textDiffService: null, cancellationToken).ConfigureAwait(false); + var analyzerConfigEdits = await ProtocolConversions.ChangedDocumentsToTextDocumentEditsAsync( + changedAnalyzerConfigDocuments, applyChangesOperation.ChangedSolution.GetRequiredAnalyzerConfigDocument, + solution.GetRequiredAnalyzerConfigDocument, + textDiffService, cancellationToken).ConfigureAwait(false); + textDocumentEdits.AddRange(analyzerConfigEdits); // Changed additional documents - await AddTextDocumentEditsAsync( - textDocumentEdits, changedAdditionalDocuments, - applyChangesOperation.ChangedSolution.GetAdditionalDocument, solution.GetAdditionalDocument, - textDiffService: null, cancellationToken).ConfigureAwait(false); + var additionalDocumentEdits = await ProtocolConversions.ChangedDocumentsToTextDocumentEditsAsync( + changedAdditionalDocuments, applyChangesOperation.ChangedSolution.GetRequiredAdditionalDocument, + solution.GetRequiredAdditionalDocument, + textDiffService, cancellationToken).ConfigureAwait(false); + textDocumentEdits.AddRange(additionalDocumentEdits); } codeAction.Edit = new LSP.WorkspaceEdit { DocumentChanges = textDocumentEdits.ToArray() }; @@ -160,46 +163,6 @@ await AddTextDocumentEditsAsync( Title = title, Arguments = new object[] { data } }; - - static async Task AddTextDocumentEditsAsync( - ArrayBuilder textDocumentEdits, - IEnumerable changedDocuments, - Func getNewDocumentFunc, - Func getOldDocumentFunc, - IDocumentTextDifferencingService? textDiffService, - CancellationToken cancellationToken) - where T : TextDocument - { - foreach (var docId in changedDocuments) - { - var newTextDoc = getNewDocumentFunc(docId); - var oldTextDoc = getOldDocumentFunc(docId); - - Contract.ThrowIfNull(oldTextDoc); - Contract.ThrowIfNull(newTextDoc); - - var oldText = await oldTextDoc.GetTextAsync(cancellationToken).ConfigureAwait(false); - - IEnumerable textChanges; - - // Normal documents have a unique service for calculating minimal text edits. If we used the standard 'GetTextChanges' - // method instead, we would get a change that spans the entire document, which we ideally want to avoid. - if (newTextDoc is Document newDoc && oldTextDoc is Document oldDoc) - { - Contract.ThrowIfNull(textDiffService); - textChanges = await textDiffService.GetTextChangesAsync(oldDoc, newDoc, cancellationToken).ConfigureAwait(false); - } - else - { - var newText = await newTextDoc.GetTextAsync(cancellationToken).ConfigureAwait(false); - textChanges = newText.GetTextChanges(oldText); - } - - var edits = textChanges.Select(tc => ProtocolConversions.TextChangeToTextEdit(tc, oldText)).ToArray(); - var documentIdentifier = new VersionedTextDocumentIdentifier { Uri = newTextDoc.GetURI() }; - textDocumentEdits.Add(new TextDocumentEdit { TextDocument = documentIdentifier, Edits = edits.ToArray() }); - } - } } } } diff --git a/src/Features/LanguageServer/Protocol/Handler/Diagnostics/AbstractPullDiagnosticHandler.cs b/src/Features/LanguageServer/Protocol/Handler/Diagnostics/AbstractPullDiagnosticHandler.cs index e16c490282603..4093cb1babb0b 100644 --- a/src/Features/LanguageServer/Protocol/Handler/Diagnostics/AbstractPullDiagnosticHandler.cs +++ b/src/Features/LanguageServer/Protocol/Handler/Diagnostics/AbstractPullDiagnosticHandler.cs @@ -9,6 +9,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; @@ -23,13 +24,20 @@ namespace Microsoft.CodeAnalysis.LanguageServer.Handler.Diagnostics internal abstract class AbstractPullDiagnosticHandler : IRequestHandler where TReport : DiagnosticReport { - private readonly ILspSolutionProvider _solutionProvider; - private readonly IDiagnosticService _diagnosticService; + /// + /// Special value we use to designate workspace diagnostics vs document diagnostics. Document diagnostics + /// should always a workspace diagnostic as the former are 'live' + /// while the latter are cached and may be stale. + /// + protected const int WorkspaceDiagnosticIdentifier = 1; + protected const int DocumentDiagnosticIdentifier = 2; + + protected readonly IDiagnosticService DiagnosticService; /// /// Lock to protect and . /// - private readonly object _gate = new object(); + private readonly object _gate = new(); /// /// Mapping of a document to the last result id we reported for it. @@ -43,12 +51,10 @@ internal abstract class AbstractPullDiagnosticHandler protected abstract TReport CreateReport(TextDocumentIdentifier? identifier, VSDiagnostic[]? diagnostics, string? resultId); + /// + /// Produce the diagnostics for the specified document. + /// + protected abstract Task> GetDiagnosticsAsync(RequestContext context, Document document, Option2 diagnosticMode, CancellationToken cancellationToken); + + /// + /// Generate the right diagnostic tags for a particular diagnostic. + /// + protected abstract DiagnosticTag[] ConvertTags(DiagnosticData diagnosticData); + private void OnDiagnosticsUpdated(object? sender, DiagnosticsUpdatedArgs updateArgs) { if (updateArgs.DocumentId == null) @@ -100,12 +116,12 @@ private void OnDiagnosticsUpdated(object? sender, DiagnosticsUpdatedArgs updateA // First, let the client know if any workspace documents have gone away. That way it can remove those for // the user from squiggles or error-list. - HandleRemovedDocuments(previousResults, progress); + HandleRemovedDocuments(context, previousResults, progress); // Create a mapping from documents to the previous results the client says it has for them. That way as we // process documents we know if we should tell the client it should stay the same, or we can tell it what // the updated diagnostics are. - var documentToPreviousDiagnosticParams = GetDocumentToPreviousDiagnosticParams(previousResults); + var documentToPreviousDiagnosticParams = GetDocumentToPreviousDiagnosticParams(context, previousResults); // Next process each file in priority order. Determine if diagnostics are changed or unchanged since the // last time we notified the client. Report back either to the client so they can update accordingly. @@ -124,7 +140,7 @@ private void OnDiagnosticsUpdated(object? sender, DiagnosticsUpdatedArgs updateA } else { - await ComputeAndReportCurrentDiagnosticsAsync(progress, document, cancellationToken).ConfigureAwait(false); + await ComputeAndReportCurrentDiagnosticsAsync(context, progress, document, cancellationToken).ConfigureAwait(false); } } @@ -144,14 +160,15 @@ private static bool IncludeDocument(Document document, string? clientName) return wantsRazorDoc == isRazorDoc; } - private Dictionary GetDocumentToPreviousDiagnosticParams(DiagnosticParams[] previousResults) + private static Dictionary GetDocumentToPreviousDiagnosticParams( + RequestContext context, DiagnosticParams[] previousResults) { var result = new Dictionary(); foreach (var diagnosticParams in previousResults) { if (diagnosticParams.TextDocument != null) { - var document = _solutionProvider.GetDocument(diagnosticParams.TextDocument); + var document = context.Solution.GetDocument(diagnosticParams.TextDocument); if (document != null) result[document] = diagnosticParams; } @@ -161,6 +178,7 @@ private Dictionary GetDocumentToPreviousDiagnosticPa } private async Task ComputeAndReportCurrentDiagnosticsAsync( + RequestContext context, BufferedProgress progress, Document document, CancellationToken cancellationToken) @@ -168,22 +186,28 @@ private async Task ComputeAndReportCurrentDiagnosticsAsync( // Being asked about this document for the first time. Or being asked again and we have different // diagnostics. Compute and report the current diagnostics info for this document. - var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); - using var _ = ArrayBuilder.GetInstance(out var result); - // Razor has a separate option for determining if they should be in push or pull mode. - var diagnosticOption = document.IsRazorDocument() + var diagnosticMode = document.IsRazorDocument() ? InternalDiagnosticsOptions.RazorDiagnosticMode : InternalDiagnosticsOptions.NormalDiagnosticMode; - var diagnostics = _diagnosticService.GetPullDiagnostics(document, includeSuppressedDiagnostics: false, diagnosticOption, cancellationToken); - foreach (var diagnostic in diagnostics) - result.Add(ConvertDiagnostic(document, text, diagnostic)); + var workspace = document.Project.Solution.Workspace; + var isPull = workspace.Options.GetOption(diagnosticMode) == DiagnosticMode.Pull; + + using var _ = ArrayBuilder.GetInstance(out var result); + + if (isPull) + { + var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); + var diagnostics = await GetDiagnosticsAsync(context, document, diagnosticMode, cancellationToken).ConfigureAwait(false); + foreach (var diagnostic in diagnostics) + result.Add(ConvertDiagnostic(document, text, diagnostic)); + } progress.Report(RecordDiagnosticReport(document, result.ToArray())); } - private void HandleRemovedDocuments(DiagnosticParams[]? previousResults, BufferedProgress progress) + private void HandleRemovedDocuments(RequestContext context, DiagnosticParams[]? previousResults, BufferedProgress progress) { if (previousResults == null) return; @@ -193,7 +217,7 @@ private void HandleRemovedDocuments(DiagnosticParams[]? previousResults, Buffere var textDocument = previousResult.TextDocument; if (textDocument != null) { - var document = _solutionProvider.GetDocument(textDocument); + var document = context.Solution.GetDocument(textDocument); if (document == null) { // Client is asking server about a document that no longer exists (i.e. was removed/deleted from @@ -222,8 +246,12 @@ private TReport RecordDiagnosticReport(Document document, VSDiagnostic[] diagnos lock (_gate) { // Keep track of the diagnostics we reported here so that we can short-circuit producing diagnostics for - // the same diagnostic set in the future. - var resultId = _nextDocumentResultId++.ToString(); + // the same diagnostic set in the future. Use a custom result-id per type (doc diagnostics or workspace + // diagnostics) so that clients of one don't errantly call into the other. For example, a client + // getting document diagnostics should not ask for workspace diagnostics with the result-ids it got for + // doc-diagnostics. The two systems are different and cannot share results, or do things like report + // what changed between each other. + var resultId = $"{GetType().Name}:{_nextDocumentResultId++}"; _documentIdToLastResultId[(document.Project.Solution.Workspace, document.Id)] = resultId; return CreateReport(ProtocolConversions.DocumentToTextDocumentIdentifier(document), diagnostics, resultId); } @@ -271,7 +299,11 @@ private static LSP.DiagnosticSeverity ConvertDiagnosticSeverity(DiagnosticSeveri _ => throw ExceptionUtilities.UnexpectedValue(severity), }; - private static DiagnosticTag[] ConvertTags(DiagnosticData diagnosticData) + /// + /// If you make change in this method, please also update the corresponding file in + /// src\VisualStudio\Xaml\Impl\Implementation\LanguageServer\Handler\Diagnostics\AbstractPullDiagnosticHandler.cs + /// + protected static DiagnosticTag[] ConvertTags(DiagnosticData diagnosticData, bool potentialDuplicate) { using var _ = ArrayBuilder.GetInstance(out var result); @@ -286,6 +318,9 @@ private static DiagnosticTag[] ConvertTags(DiagnosticData diagnosticData) result.Add(VSDiagnosticTags.VisibleInErrorList); } + if (potentialDuplicate) + result.Add(VSDiagnosticTags.PotentialDuplicate); + result.Add(diagnosticData.CustomTags.Contains(WellKnownDiagnosticTags.Build) ? VSDiagnosticTags.BuildError : VSDiagnosticTags.IntellisenseError); diff --git a/src/Features/LanguageServer/Protocol/Handler/Diagnostics/DocumentPullDiagnosticHandler.cs b/src/Features/LanguageServer/Protocol/Handler/Diagnostics/DocumentPullDiagnosticHandler.cs index 06f4d7bd4b84e..5bc9d591042bd 100644 --- a/src/Features/LanguageServer/Protocol/Handler/Diagnostics/DocumentPullDiagnosticHandler.cs +++ b/src/Features/LanguageServer/Protocol/Handler/Diagnostics/DocumentPullDiagnosticHandler.cs @@ -5,8 +5,11 @@ using System; using System.Collections.Immutable; using System.Composition; +using System.Threading; +using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.Diagnostics @@ -14,20 +17,42 @@ namespace Microsoft.CodeAnalysis.LanguageServer.Handler.Diagnostics [ExportLspMethod(MSLSPMethods.DocumentPullDiagnosticName, mutatesSolutionState: false), Shared] internal class DocumentPullDiagnosticHandler : AbstractPullDiagnosticHandler { + private readonly IDiagnosticAnalyzerService _analyzerService; + [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DocumentPullDiagnosticHandler( - ILspSolutionProvider solutionProvider, - IDiagnosticService diagnosticService) - : base(solutionProvider, diagnosticService) + IDiagnosticService diagnosticService, + IDiagnosticAnalyzerService analyzerService) + : base(diagnosticService) { + _analyzerService = analyzerService; } public override TextDocumentIdentifier? GetTextDocumentIdentifier(DocumentDiagnosticsParams diagnosticsParams) => diagnosticsParams.TextDocument; protected override DiagnosticReport CreateReport(TextDocumentIdentifier? identifier, VSDiagnostic[]? diagnostics, string? resultId) - => new DiagnosticReport { Diagnostics = diagnostics, ResultId = resultId }; + => new DiagnosticReport + { + Diagnostics = diagnostics, + ResultId = resultId, + Identifier = DocumentDiagnosticIdentifier, + // Mark these diagnostics as superseding any diagnostics for the same document from the + // WorkspacePullDiagnosticHandler. We are always getting completely accurate and up to date diagnostic + // values for a particular file, so our results should always be preferred over the workspace-pull + // values which are cached and may be out of date. + Supersedes = WorkspaceDiagnosticIdentifier, + }; + + protected override DiagnosticParams[]? GetPreviousResults(DocumentDiagnosticsParams diagnosticsParams) + => new[] { diagnosticsParams }; + + protected override IProgress? GetProgress(DocumentDiagnosticsParams diagnosticsParams) + => diagnosticsParams.PartialResultToken; + + protected override DiagnosticTag[] ConvertTags(DiagnosticData diagnosticData) + => ConvertTags(diagnosticData, potentialDuplicate: false); protected override ImmutableArray GetOrderedDocuments(RequestContext context) { @@ -36,13 +61,22 @@ protected override ImmutableArray GetOrderedDocuments(RequestContext c // Note: context.Document may be null in the case where the client is asking about a document that we have // since removed from the workspace. In this case, we don't really have anything to process. // GetPreviousResults will be used to properly realize this and notify the client that the doc is gone. - return context.Document == null ? ImmutableArray.Empty : ImmutableArray.Create(context.Document); + // + // Only consider open documents here (and only closed ones in the WorkspacePullDiagnosticHandler). Each + // handler treats those as separate worlds that they are responsible for. + return context.Document != null && context.IsTracking(context.Document.GetURI()) + ? ImmutableArray.Create(context.Document) + : ImmutableArray.Empty; } - protected override DiagnosticParams[]? GetPreviousResults(DocumentDiagnosticsParams diagnosticsParams) - => new[] { diagnosticsParams }; - - protected override IProgress? GetProgress(DocumentDiagnosticsParams diagnosticsParams) - => diagnosticsParams.PartialResultToken; + protected override Task> GetDiagnosticsAsync( + RequestContext context, Document document, Option2 diagnosticMode, CancellationToken cancellationToken) + { + // For open documents, directly use the IDiagnosticAnalyzerService. This will use the actual snapshots + // we're passing in. If information is already cached for that snapshot, it will be returned. Otherwise, + // it will be computed on demand. Because it is always accurate as per this snapshot, all spans are correct + // and do not need to be adjusted. + return _analyzerService.GetDiagnosticsAsync(document.Project.Solution, documentId: document.Id, cancellationToken: cancellationToken); + } } } diff --git a/src/Features/LanguageServer/Protocol/Handler/Diagnostics/WorkspacePullDiagnosticHandler.cs b/src/Features/LanguageServer/Protocol/Handler/Diagnostics/WorkspacePullDiagnosticHandler.cs index f5e18c4c26cbb..1b83b8d890a0d 100644 --- a/src/Features/LanguageServer/Protocol/Handler/Diagnostics/WorkspacePullDiagnosticHandler.cs +++ b/src/Features/LanguageServer/Protocol/Handler/Diagnostics/WorkspacePullDiagnosticHandler.cs @@ -5,9 +5,11 @@ using System; using System.Collections.Immutable; using System.Composition; -using System.Linq; +using System.Threading; +using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.VisualStudio.LanguageServer.Protocol; @@ -19,10 +21,8 @@ internal class WorkspacePullDiagnosticHandler : AbstractPullDiagnosticHandler null; protected override WorkspaceDiagnosticReport CreateReport(TextDocumentIdentifier? identifier, VSDiagnostic[]? diagnostics, string? resultId) - => new WorkspaceDiagnosticReport { TextDocument = identifier, Diagnostics = diagnostics, ResultId = resultId }; + => new WorkspaceDiagnosticReport + { + TextDocument = identifier, + Diagnostics = diagnostics, + ResultId = resultId, + // Mark these diagnostics as having come from us. They will be superseded by any diagnostics for the + // same file produced by the DocumentPullDiagnosticHandler. + Identifier = WorkspaceDiagnosticIdentifier, + }; protected override IProgress? GetProgress(WorkspaceDocumentDiagnosticsParams diagnosticsParams) => diagnosticsParams.PartialResultToken; @@ -38,6 +46,13 @@ protected override WorkspaceDiagnosticReport CreateReport(TextDocumentIdentifier protected override DiagnosticParams[]? GetPreviousResults(WorkspaceDocumentDiagnosticsParams diagnosticsParams) => diagnosticsParams.PreviousResults; + protected override DiagnosticTag[] ConvertTags(DiagnosticData diagnosticData) + { + // All workspace diagnostics are potential duplicates given that they can be overridden by the diagnostics + // produced by document diagnostics. + return ConvertTags(diagnosticData, potentialDuplicate: true); + } + protected override ImmutableArray GetOrderedDocuments(RequestContext context) { // If we're being called from razor, we do not support WorkspaceDiagnostics at all. For razor, workspace @@ -53,19 +68,12 @@ protected override ImmutableArray GetOrderedDocuments(RequestContext c var documentTrackingService = solution.Workspace.Services.GetRequiredService(); // Collect all the documents from the solution in the order we'd like to get diagnostics for. This will - // prioritize the current working files, but then also include all other docs in all projects (depending on - // current FSA settings). When adding the docs, we do so in a simple manner, not worrying about if a - // document is added multiple. That's not a problem though as we do a .Distinct call at the end to ensure - // that a file only ever appears once in the collection. As .Distinct preserves order and discards later - // duplicates it finds, this won't affect important files that we put at the front of the list. + // prioritize the files from currently active projects, but then also include all other docs in all projects + // (depending on current FSA settings). - // The active and visible docs always get priority in terms or results. var activeDocument = documentTrackingService.GetActiveDocument(solution); var visibleDocuments = documentTrackingService.GetVisibleDocuments(solution); - result.AddIfNotNull(activeDocument); - result.AddRange(visibleDocuments); - // Now, prioritize the projects related to the active/visible files. AddDocumentsFromProject(activeDocument?.Project, isOpen: true); foreach (var doc in visibleDocuments) @@ -75,7 +83,9 @@ protected override ImmutableArray GetOrderedDocuments(RequestContext c foreach (var project in solution.Projects) AddDocumentsFromProject(project, isOpen: false); - return result.Distinct().ToImmutableArray(); + // Ensure that we only process documents once. + result.RemoveDuplicates(); + return result.ToImmutable(); void AddDocumentsFromProject(Project? project, bool isOpen) { @@ -93,8 +103,24 @@ void AddDocumentsFromProject(Project? project, bool isOpen) // Otherwise, if the user has an open file from this project, or FSA is on, then include all the // documents from it. - result.AddRange(project.Documents); + foreach (var document in project.Documents) + { + // Only consider closed documents here (and only open ones in the DocumentPullDiagnosticHandler). + // Each handler treats those as separate worlds that they are responsible for. + if (!context.IsTracking(document.GetURI())) + result.Add(document); + } } } + + protected override Task> GetDiagnosticsAsync( + RequestContext context, Document document, Option2 diagnosticMode, CancellationToken cancellationToken) + { + // For closed files, go to the IDiagnosticService for results. These won't necessarily be totally up to + // date. However, that's fine as these are closed files and won't be in the process of being edited. So + // any deviations in the spans of diagnostics shouldn't be impactful for the user. + var diagnostics = this.DiagnosticService.GetPullDiagnostics(document, includeSuppressedDiagnostics: false, diagnosticMode, cancellationToken); + return Task.FromResult(diagnostics); + } } } diff --git a/src/Features/LanguageServer/Protocol/Handler/DocumentChanges/DidOpenHandler.cs b/src/Features/LanguageServer/Protocol/Handler/DocumentChanges/DidOpenHandler.cs index 6bdd79ff217ef..1c393d1c4ff9b 100644 --- a/src/Features/LanguageServer/Protocol/Handler/DocumentChanges/DidOpenHandler.cs +++ b/src/Features/LanguageServer/Protocol/Handler/DocumentChanges/DidOpenHandler.cs @@ -28,7 +28,7 @@ public DidOpenHandler() public Task HandleRequestAsync(LSP.DidOpenTextDocumentParams request, RequestContext context, CancellationToken cancellationToken) { // Add the document and ensure the text we have matches whats on the client - var sourceText = SourceText.From(request.TextDocument.Text); + var sourceText = SourceText.From(request.TextDocument.Text, System.Text.Encoding.UTF8); context.StartTracking(request.TextDocument.Uri, sourceText); diff --git a/src/Features/LanguageServer/Protocol/Handler/FoldingRanges/FoldingRangesHandler.cs b/src/Features/LanguageServer/Protocol/Handler/FoldingRanges/FoldingRangesHandler.cs index 3d5beb3e0bd66..9f2cd86798588 100644 --- a/src/Features/LanguageServer/Protocol/Handler/FoldingRanges/FoldingRangesHandler.cs +++ b/src/Features/LanguageServer/Protocol/Handler/FoldingRanges/FoldingRangesHandler.cs @@ -6,16 +6,19 @@ using System.Composition; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Structure; +using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { [Shared] [ExportLspMethod(Methods.TextDocumentFoldingRangeName, mutatesSolutionState: false)] - internal class FoldingRangesHandler : IRequestHandler + internal sealed class FoldingRangesHandler : IRequestHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] @@ -27,27 +30,54 @@ public FoldingRangesHandler() public async Task HandleRequestAsync(FoldingRangeParams request, RequestContext context, CancellationToken cancellationToken) { - var foldingRanges = ArrayBuilder.GetInstance(); - var document = context.Document; if (document == null) { - return foldingRanges.ToArrayAndFree(); + return Array.Empty(); } var blockStructureService = document.Project.LanguageServices.GetService(); if (blockStructureService == null) { - return foldingRanges.ToArrayAndFree(); + return Array.Empty(); } var blockStructure = await blockStructureService.GetBlockStructureAsync(document, cancellationToken).ConfigureAwait(false); if (blockStructure == null) { - return foldingRanges.ToArrayAndFree(); + return Array.Empty(); } var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); + return GetFoldingRanges(blockStructure, text); + } + + public static FoldingRange[] GetFoldingRanges( + SyntaxTree syntaxTree, + HostLanguageServices languageServices, + OptionSet options, + bool isMetadataAsSource, + CancellationToken cancellationToken) + { + var blockStructureService = (BlockStructureServiceWithProviders)languageServices.GetRequiredService(); + var blockStructure = blockStructureService.GetBlockStructure(syntaxTree, options, isMetadataAsSource, cancellationToken); + if (blockStructure == null) + { + return Array.Empty(); + } + + var text = syntaxTree.GetText(cancellationToken); + return GetFoldingRanges(blockStructure, text); + } + + private static FoldingRange[] GetFoldingRanges(BlockStructure blockStructure, SourceText text) + { + if (blockStructure.Spans.IsEmpty) + { + return Array.Empty(); + } + + using var _ = ArrayBuilder.GetInstance(out var foldingRanges); foreach (var span in blockStructure.Spans) { @@ -84,7 +114,7 @@ public async Task HandleRequestAsync(FoldingRangeParams request, }); } - return foldingRanges.ToArrayAndFree(); + return foldingRanges.ToArray(); } } } diff --git a/src/Features/LanguageServer/Protocol/Handler/Rename/RenameHandler.cs b/src/Features/LanguageServer/Protocol/Handler/Rename/RenameHandler.cs index 4b12b9796cb43..6105f1a9c0e4c 100644 --- a/src/Features/LanguageServer/Protocol/Handler/Rename/RenameHandler.cs +++ b/src/Features/LanguageServer/Protocol/Handler/Rename/RenameHandler.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; @@ -11,6 +12,7 @@ using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; +using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; @@ -30,7 +32,6 @@ public RenameHandler() public async Task HandleRequestAsync(RenameParams request, RequestContext context, CancellationToken cancellationToken) { - WorkspaceEdit? workspaceEdit = null; var document = context.Document; if (document != null) { @@ -41,7 +42,7 @@ public RenameHandler() var renameInfo = await renameService.GetRenameInfoAsync(document, position, cancellationToken).ConfigureAwait(false); if (!renameInfo.CanRename) { - return workspaceEdit; + return null; } var renameLocationSet = await renameInfo.FindRenameLocationsAsync(oldSolution.Workspace.Options, cancellationToken).ConfigureAwait(false); @@ -60,26 +61,14 @@ public RenameHandler() .GroupBy(docId => renamedSolution.GetRequiredDocument(docId).FilePath, StringComparer.OrdinalIgnoreCase).Select(group => group.First()); var textDiffService = renamedSolution.Workspace.Services.GetRequiredService(); - using var _ = ArrayBuilder.GetInstance(out var documentEdits); - foreach (var docId in changedDocuments) - { - var oldDoc = oldSolution.GetRequiredDocument(docId); - var newDoc = renamedSolution.GetRequiredDocument(docId); - var textChanges = await textDiffService.GetTextChangesAsync(oldDoc, newDoc, cancellationToken).ConfigureAwait(false); - var oldText = await oldDoc.GetTextAsync(cancellationToken).ConfigureAwait(false); - var textDocumentEdit = new TextDocumentEdit - { - TextDocument = new VersionedTextDocumentIdentifier { Uri = newDoc.GetURI() }, - Edits = textChanges.Select(tc => ProtocolConversions.TextChangeToTextEdit(tc, oldText)).ToArray() - }; - documentEdits.Add(textDocumentEdit); - } + var documentEdits = await ProtocolConversions.ChangedDocumentsToTextDocumentEditsAsync(changedDocuments, renamedSolution.GetRequiredDocument, oldSolution.GetRequiredDocument, + textDiffService, cancellationToken).ConfigureAwait(false); - workspaceEdit = new WorkspaceEdit { DocumentChanges = documentEdits.ToArray() }; + return new WorkspaceEdit { DocumentChanges = documentEdits }; } - return workspaceEdit; + return null; } } } diff --git a/src/Features/LanguageServer/Protocol/Handler/RequestContext.cs b/src/Features/LanguageServer/Protocol/Handler/RequestContext.cs index 28817ae6544b3..63dc140986f69 100644 --- a/src/Features/LanguageServer/Protocol/Handler/RequestContext.cs +++ b/src/Features/LanguageServer/Protocol/Handler/RequestContext.cs @@ -5,7 +5,6 @@ using System; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Roslyn.Utilities; using static Microsoft.CodeAnalysis.LanguageServer.Handler.RequestExecutionQueue; namespace Microsoft.CodeAnalysis.LanguageServer.Handler @@ -18,7 +17,7 @@ internal readonly struct RequestContext /// /// This will be null for non-mutating requests because they're not allowed to change documents /// - private readonly DocumentChangeTracker? _documentChangeTracker; + private readonly IDocumentChangeTracker _documentChangeTracker; /// /// The solution state that the request should operate on. @@ -40,7 +39,7 @@ internal readonly struct RequestContext /// public readonly Document? Document; - public RequestContext(Solution solution, ClientCapabilities clientCapabilities, string? clientName, Document? document, DocumentChangeTracker? documentChangeTracker) + public RequestContext(Solution solution, ClientCapabilities clientCapabilities, string? clientName, Document? document, IDocumentChangeTracker documentChangeTracker) { Document = document; Solution = solution; @@ -53,30 +52,21 @@ public RequestContext(Solution solution, ClientCapabilities clientCapabilities, /// Allows a mutating request to open a document and start it being tracked. /// public void StartTracking(Uri documentUri, SourceText initialText) - { - Contract.ThrowIfNull(_documentChangeTracker, "Mutating documents not allowed in a non-mutating request handler"); - - _documentChangeTracker.StartTracking(documentUri, initialText); - } + => _documentChangeTracker.StartTracking(documentUri, initialText); /// /// Allows a mutating request to update the contents of a tracked document. /// public void UpdateTrackedDocument(Uri documentUri, SourceText changedText) - { - Contract.ThrowIfNull(_documentChangeTracker, "Mutating documents not allowed in a non-mutating request handler"); - - _documentChangeTracker.UpdateTrackedDocument(documentUri, changedText); - } + => _documentChangeTracker.UpdateTrackedDocument(documentUri, changedText); /// /// Allows a mutating request to close a document and stop it being tracked. /// public void StopTracking(Uri documentUri) - { - Contract.ThrowIfNull(_documentChangeTracker, "Mutating documents not allowed in a non-mutating request handler"); + => _documentChangeTracker.StopTracking(documentUri); - _documentChangeTracker.StopTracking(documentUri); - } + public bool IsTracking(Uri documentUri) + => _documentChangeTracker.IsTracking(documentUri); } } diff --git a/src/Features/LanguageServer/Protocol/Handler/RequestExecutionQueue.DocumentChangeTracker.cs b/src/Features/LanguageServer/Protocol/Handler/RequestExecutionQueue.DocumentChangeTracker.cs index f9bae62eef1af..74f9cf9b6bc90 100644 --- a/src/Features/LanguageServer/Protocol/Handler/RequestExecutionQueue.DocumentChangeTracker.cs +++ b/src/Features/LanguageServer/Protocol/Handler/RequestExecutionQueue.DocumentChangeTracker.cs @@ -15,29 +15,71 @@ namespace Microsoft.CodeAnalysis.LanguageServer.Handler { internal partial class RequestExecutionQueue { + internal interface IDocumentChangeTracker + { + void StartTracking(Uri documentUri, SourceText initialText); + void UpdateTrackedDocument(Uri documentUri, SourceText text); + void StopTracking(Uri documentUri); + bool IsTracking(Uri documentUri); + } + + private class NonMutatingDocumentChangeTracker : IDocumentChangeTracker + { + private readonly DocumentChangeTracker _tracker; + + public NonMutatingDocumentChangeTracker(DocumentChangeTracker tracker) + { + _tracker = tracker; + } + + public bool IsTracking(Uri documentUri) + => _tracker.IsTracking(documentUri); + + public void StartTracking(Uri documentUri, SourceText initialText) + { + Contract.Fail("Mutating documents not allowed in a non-mutating request handler"); + throw new NotImplementedException(); + } + + public void StopTracking(Uri documentUri) + { + Contract.Fail("Mutating documents not allowed in a non-mutating request handler"); + throw new NotImplementedException(); + } + + public void UpdateTrackedDocument(Uri documentUri, SourceText text) + { + Contract.Fail("Mutating documents not allowed in a non-mutating request handler"); + throw new NotImplementedException(); + } + } + /// /// Keeps track of changes to documents that are opened in the LSP client. Calls MUST not overlap, so this /// should be called from a mutating request handler. See for more details. /// - internal class DocumentChangeTracker : IWorkspaceService + internal class DocumentChangeTracker : IWorkspaceService, IDocumentChangeTracker { private readonly Dictionary _trackedDocuments = new(); - internal void StartTracking(Uri documentUri, SourceText initialText) + public bool IsTracking(Uri documentUri) + => _trackedDocuments.ContainsKey(documentUri); + + public void StartTracking(Uri documentUri, SourceText initialText) { Contract.ThrowIfTrue(_trackedDocuments.ContainsKey(documentUri), "didOpen received for an already open document."); _trackedDocuments.Add(documentUri, initialText); } - internal void UpdateTrackedDocument(Uri documentUri, SourceText text) + public void UpdateTrackedDocument(Uri documentUri, SourceText text) { Contract.ThrowIfFalse(_trackedDocuments.ContainsKey(documentUri), "didChange received for a document that isn't open."); _trackedDocuments[documentUri] = text; } - internal void StopTracking(Uri documentUri) + public void StopTracking(Uri documentUri) { Contract.ThrowIfFalse(_trackedDocuments.ContainsKey(documentUri), "didClose received for a document that isn't open."); diff --git a/src/Features/LanguageServer/Protocol/Handler/RequestExecutionQueue.cs b/src/Features/LanguageServer/Protocol/Handler/RequestExecutionQueue.cs index e408e18c5ce9d..81cc32ef674df 100644 --- a/src/Features/LanguageServer/Protocol/Handler/RequestExecutionQueue.cs +++ b/src/Features/LanguageServer/Protocol/Handler/RequestExecutionQueue.cs @@ -5,6 +5,7 @@ #nullable enable using System; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; @@ -26,7 +27,7 @@ namespace Microsoft.CodeAnalysis.LanguageServer.Handler /// /// This class acheives this by distinguishing between mutating and non-mutating requests, and ensuring that /// when a mutating request comes in, its processing blocks all subsequent requests. As each request comes in - /// it is added to a queue, and a queue item will not be retreived while a mutating request is running. Before + /// it is added to a queue, and a queue item will not be retrieved while a mutating request is running. Before /// any request is handled the solution state is created by merging workspace solution state, which could have /// changes from non-LSP means (eg, adding a project reference), with the current "mutated" state. /// When a non-mutating work item is retrieved from the queue, it is given the current solution state, but then @@ -54,6 +55,12 @@ internal partial class RequestExecutionQueue private readonly CancellationTokenSource _cancelSource; private readonly DocumentChangeTracker _documentChangeTracker; + // This dictionary is used to cache our forked LSP solution so we don't have to + // recompute it for each request. We don't need to worry about threading because they are only + // used when preparing to handle a request, which happens in a single thread in the ProcessQueueAsync + // method. + private readonly Dictionary _lspSolutionCache = new(); + public CancellationToken CancellationToken => _cancelSource.Token; /// @@ -180,11 +187,14 @@ private async Task ProcessQueueAsync() // Mutating requests block other requests from starting to ensure an up to date snapshot is used. var ranToCompletion = await work.CallbackAsync(context, cancellationToken).ConfigureAwait(false); - // If the handling of the request failed, the exception will bubble back up to the caller, and we - // request shutdown because we're in an invalid state + // Now that we've mutated our solution, clear out our saved state to ensure it gets recalculated + _lspSolutionCache.Remove(context.Solution.Workspace); + if (!ranToCompletion) { - OnRequestServerShutdown($"An error occured processing a mutating request and the solution is in an invalid state. Check LSP client logs for any error information."); + // If the handling of the request failed, the exception will bubble back up to the caller, and we + // request shutdown because we're in an invalid state + OnRequestServerShutdown($"An error occurred processing a mutating request and the solution is in an invalid state. Check LSP client logs for any error information."); break; } } @@ -204,7 +214,7 @@ private async Task ProcessQueueAsync() } catch (Exception e) when (FatalError.ReportAndCatch(e)) { - OnRequestServerShutdown($"Error occured processing queue: {e.Message}."); + OnRequestServerShutdown($"Error occurred processing queue: {e.Message}."); } } @@ -253,25 +263,41 @@ private RequestContext CreateRequestContext(QueueItem queueItem) // There are multiple possible solutions that we could be interested in, so we need to find the document // first and then get the solution from there. If we're not given a document, this will return the default // solution - var (documentId, solution) = _solutionProvider.GetDocumentAndSolution(queueItem.TextDocument, queueItem.ClientName); + var (documentId, workspaceSolution) = _solutionProvider.GetDocumentAndSolution(queueItem.TextDocument, queueItem.ClientName); - // Now we can update the solution to represent the LSP view of the world, with any text changes we received - solution = GetSolutionWithReplacedDocuments(solution); + var lspSolution = GetLSPSolution(workspaceSolution); // If we got a document id back, we pull it out of our updated solution so the handler is operating on the latest // document text. If document id is null here, this will just return null - var document = solution.GetDocument(documentId); + var document = lspSolution.GetDocument(documentId); + + var trackerToUse = queueItem.MutatesSolutionState + ? (IDocumentChangeTracker)_documentChangeTracker + : new NonMutatingDocumentChangeTracker(_documentChangeTracker); + + return new RequestContext(lspSolution, queueItem.ClientCapabilities, queueItem.ClientName, document, trackerToUse); + } - DocumentChangeTracker? trackerToUse = null; - if (queueItem.MutatesSolutionState) + /// + /// Gets the "LSP view of the world", either by forking the workspace solution and updating the documents we track + /// or by simply returning our cached solution if it is still valid. + /// + private Solution GetLSPSolution(Solution workspaceSolution) + { + var workspace = workspaceSolution.Workspace; + + // If we have a cached solution we can use it, unless the workspace solution it was based on + // is not the current one. + if (!_lspSolutionCache.TryGetValue(workspace, out var cacheInfo) || + workspaceSolution != cacheInfo.workspaceSolution) { - // Logically, if a mutating request fails we don't want to take its mutations, so giving it the "real" tracker - // is a bad idea, but since we tear down the queue for any error anyway, the document tracker will be emptied - // and no future requests will be handled, so we don't need to do anything special here. - trackerToUse = _documentChangeTracker; + var lspSolution = GetSolutionWithReplacedDocuments(workspaceSolution); + _lspSolutionCache[workspace] = (workspaceSolution, lspSolution); + + return lspSolution; } - return new RequestContext(solution, queueItem.ClientCapabilities, queueItem.ClientName, document, trackerToUse); + return cacheInfo.lspSolution; } /// diff --git a/src/Features/LanguageServer/Protocol/Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj b/src/Features/LanguageServer/Protocol/Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj index 7e9540f3512cc..50d54212cd556 100644 --- a/src/Features/LanguageServer/Protocol/Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj +++ b/src/Features/LanguageServer/Protocol/Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj @@ -40,6 +40,7 @@ + diff --git a/src/Features/LanguageServer/ProtocolUnitTests/CodeActions/CodeActionsTests.cs b/src/Features/LanguageServer/ProtocolUnitTests/CodeActions/CodeActionsTests.cs index 1b8072001b903..231d51649403f 100644 --- a/src/Features/LanguageServer/ProtocolUnitTests/CodeActions/CodeActionsTests.cs +++ b/src/Features/LanguageServer/ProtocolUnitTests/CodeActions/CodeActionsTests.cs @@ -144,7 +144,6 @@ void M() var changedSourceText = currentDocText.WithChanges(new TextChange(new TextSpan(0, 0), "class D { } \n")); var docId = workspace.Documents.First().Id; workspace.ChangeDocument(docId, changedSourceText); - UpdateSolutionProvider(workspace, workspace.CurrentSolution); var updatedDocument = GetDocument(workspace, CreateTextDocumentIdentifier(caretLocation.Uri)); await RunCodeActionsAndAssertActionsInCacheAsync(workspace, cache, caretLocation, updatedDocument); diff --git a/src/Features/LanguageServer/ProtocolUnitTests/Completion/CompletionTests.cs b/src/Features/LanguageServer/ProtocolUnitTests/Completion/CompletionTests.cs index a5584dbfcb262..7942859c916de 100644 --- a/src/Features/LanguageServer/ProtocolUnitTests/Completion/CompletionTests.cs +++ b/src/Features/LanguageServer/ProtocolUnitTests/Completion/CompletionTests.cs @@ -97,7 +97,7 @@ void M() using var workspace = CreateTestWorkspace(markup, out var locations); var completionParams = CreateCompletionParams(locations["caret"].Single(), triggerCharacter: "\0", LSP.CompletionTriggerKind.Invoked); var expected = CreateCompletionItem("A", LSP.CompletionItemKind.Class, new string[] { "Class", "Internal" }, - completionParams, preselect: true, commitCharacters: ImmutableArray.Create(' ', '(', '[', '{')); + completionParams, preselect: true, commitCharacters: ImmutableArray.Create(' ', '(', '[', '{', ';')); var results = await RunGetCompletionsAsync(workspace.CurrentSolution, completionParams).ConfigureAwait(false); AssertJsonEquals(expected, results.Items.First()); diff --git a/src/Features/LanguageServer/ProtocolUnitTests/Diagnostics/PullDiagnosticTests.cs b/src/Features/LanguageServer/ProtocolUnitTests/Diagnostics/PullDiagnosticTests.cs index 49d8cada8d073..d51cb6de5e9d4 100644 --- a/src/Features/LanguageServer/ProtocolUnitTests/Diagnostics/PullDiagnosticTests.cs +++ b/src/Features/LanguageServer/ProtocolUnitTests/Diagnostics/PullDiagnosticTests.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable - using System; using System.Linq; using System.Threading; @@ -14,6 +12,7 @@ using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; +using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Test.Utilities; using Xunit; @@ -31,10 +30,15 @@ public async Task TestNoDocumentDiagnosticsForClosedFilesWithFSAOff() var markup = @"class A {"; using var workspace = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); - var results = await RunGetDocumentPullDiagnosticsAsync( - workspace, workspace.CurrentSolution.Projects.Single().Documents.Single()); - Assert.Empty(results.Single().Diagnostics); + var queue = CreateRequestQueue(workspace.CurrentSolution); + var server = GetLanguageServer(workspace.CurrentSolution); + + var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); + + var results = await RunGetDocumentPullDiagnosticsAsync(workspace, queue, server, document); + + Assert.Empty(results); } [Fact] @@ -47,8 +51,15 @@ public async Task TestDocumentDiagnosticsForOpenFilesWithFSAOff() // Calling GetTextBuffer will effectively open the file. workspace.Documents.Single().GetTextBuffer(); + var queue = CreateRequestQueue(workspace.CurrentSolution); + var server = GetLanguageServer(workspace.CurrentSolution); + + var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); + + await OpenDocumentAsync(queue, server, document); + var results = await RunGetDocumentPullDiagnosticsAsync( - workspace, workspace.CurrentSolution.Projects.Single().Documents.Single()); + workspace, queue, server, workspace.CurrentSolution.Projects.Single().Documents.Single()); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); } @@ -63,8 +74,15 @@ public async Task TestNoDocumentDiagnosticsForOpenFilesWithFSAOffIfInPushMode() // Calling GetTextBuffer will effectively open the file. workspace.Documents.Single().GetTextBuffer(); + var queue = CreateRequestQueue(workspace.CurrentSolution); + var server = GetLanguageServer(workspace.CurrentSolution); + + var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); + + await OpenDocumentAsync(queue, server, document); + var results = await RunGetDocumentPullDiagnosticsAsync( - workspace, workspace.CurrentSolution.Projects.Single().Documents.Single()); + workspace, queue, server, document); Assert.Empty(results.Single().Diagnostics); } @@ -86,6 +104,8 @@ public async Task TestDocumentDiagnosticsForRemovedDocument() var queue = CreateRequestQueue(solution); var server = GetLanguageServer(solution); + await OpenDocumentAsync(queue, server, document); + await WaitForDiagnosticsAsync(workspace); var results = await server.ExecuteRequestAsync( queue, @@ -99,7 +119,7 @@ public async Task TestDocumentDiagnosticsForRemovedDocument() // Now remove the doc. workspace.OnDocumentRemoved(workspace.Documents.Single().Id); - UpdateSolutionProvider(workspace, workspace.CurrentSolution); + await CloseDocumentAsync(queue, server, document); // And get diagnostic again, using the same doc-id as before. await WaitForDiagnosticsAsync(workspace); @@ -125,15 +145,21 @@ public async Task TestNoChangeIfDocumentDiagnosticsCalledTwice() // Calling GetTextBuffer will effectively open the file. workspace.Documents.Single().GetTextBuffer(); + var queue = CreateRequestQueue(workspace.CurrentSolution); + var server = GetLanguageServer(workspace.CurrentSolution); + + var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); + + await OpenDocumentAsync(queue, server, document); + var results = await RunGetDocumentPullDiagnosticsAsync( - workspace, workspace.CurrentSolution.Projects.Single().Documents.Single()); + workspace, queue, server, document); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); var resultId = results.Single().ResultId; results = await RunGetDocumentPullDiagnosticsAsync( - workspace, workspace.CurrentSolution.Projects.Single().Documents.Single(), - previousResultId: resultId); + workspace, queue, server, workspace.CurrentSolution.Projects.Single().Documents.Single(), previousResultId: resultId); Assert.Null(results.Single().Diagnostics); Assert.Equal(resultId, results.Single().ResultId); @@ -149,15 +175,22 @@ public async Task TestDocumentDiagnosticsRemovedAfterErrorIsFixed() // Calling GetTextBuffer will effectively open the file. var buffer = workspace.Documents.Single().GetTextBuffer(); + var queue = CreateRequestQueue(workspace.CurrentSolution); + var server = GetLanguageServer(workspace.CurrentSolution); + + var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); + + await OpenDocumentAsync(queue, server, document); + var results = await RunGetDocumentPullDiagnosticsAsync( - workspace, workspace.CurrentSolution.Projects.Single().Documents.Single()); + workspace, queue, server, document); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); - buffer.Insert(buffer.CurrentSnapshot.Length, "}"); + await InsertTextAsync(queue, server, document, buffer.CurrentSnapshot.Length, "}"); results = await RunGetDocumentPullDiagnosticsAsync( - workspace, workspace.CurrentSolution.Projects.Single().Documents.Single()); + workspace, queue, server, workspace.CurrentSolution.Projects.Single().Documents.Single()); Assert.Empty(results[0].Diagnostics); } @@ -172,22 +205,97 @@ public async Task TestDocumentDiagnosticsRemainAfterErrorIsNotFixed() // Calling GetTextBuffer will effectively open the file. var buffer = workspace.Documents.Single().GetTextBuffer(); - var results = await RunGetDocumentPullDiagnosticsAsync( - workspace, workspace.CurrentSolution.Projects.Single().Documents.Single()); + var queue = CreateRequestQueue(workspace.CurrentSolution); + var server = GetLanguageServer(workspace.CurrentSolution); + + var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); + + await OpenDocumentAsync(queue, server, document); + var results = await RunGetDocumentPullDiagnosticsAsync(workspace, queue, server, document); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 9 }, results[0].Diagnostics.Single().Range.Start); buffer.Insert(0, " "); + await InsertTextAsync(queue, server, document, position: 0, text: " "); results = await RunGetDocumentPullDiagnosticsAsync( - workspace, workspace.CurrentSolution.Projects.Single().Documents.Single(), + workspace, queue, server, workspace.CurrentSolution.Projects.Single().Documents.Single(), previousResultId: results[0].ResultId); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 10 }, results[0].Diagnostics.Single().Range.Start); } + private static async Task InsertTextAsync( + RequestExecutionQueue queue, + LanguageServerProtocol server, + Document document, + int position, + string text) + { + var sourceText = await document.GetTextAsync(); + var lineInfo = sourceText.Lines.GetLinePositionSpan(new TextSpan(position, 0)); + + await server.ExecuteRequestAsync( + queue, + Methods.TextDocumentDidChangeName, + new DidChangeTextDocumentParams + { + TextDocument = ProtocolConversions.DocumentToVersionedTextDocumentIdentifier(document), + ContentChanges = new TextDocumentContentChangeEvent[] + { + new TextDocumentContentChangeEvent + { + Range = new LSP.Range + { + Start = ProtocolConversions.LinePositionToPosition(lineInfo.Start), + End =ProtocolConversions.LinePositionToPosition(lineInfo.End), + }, + Text = text, + }, + }, + }, + new LSP.ClientCapabilities(), + clientName: null, + CancellationToken.None); + } + + private static async Task OpenDocumentAsync(RequestExecutionQueue queue, LanguageServerProtocol server, Document document) + { + await server.ExecuteRequestAsync( + queue, + Methods.TextDocumentDidOpenName, + new DidOpenTextDocumentParams + { + TextDocument = new TextDocumentItem + { + Uri = document.GetURI(), + Text = document.GetTextSynchronously(CancellationToken.None).ToString(), + } + }, + new LSP.ClientCapabilities(), + clientName: null, + CancellationToken.None); + } + + private static async Task CloseDocumentAsync(RequestExecutionQueue queue, LanguageServerProtocol server, Document document) + { + await server.ExecuteRequestAsync( + queue, + Methods.TextDocumentDidCloseName, + new DidCloseTextDocumentParams + { + TextDocument = new TextDocumentIdentifier + { + Uri = document.GetURI(), + } + }, + new LSP.ClientCapabilities(), + clientName: null, + CancellationToken.None); + } + [Fact] public async Task TestStreamingDocumentDiagnostics() { @@ -198,9 +306,16 @@ public async Task TestStreamingDocumentDiagnostics() // Calling GetTextBuffer will effectively open the file. workspace.Documents.Single().GetTextBuffer(); + var queue = CreateRequestQueue(workspace.CurrentSolution); + var server = GetLanguageServer(workspace.CurrentSolution); + + var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); + + await OpenDocumentAsync(queue, server, document); + var progress = BufferedProgress.Create(null); var results = await RunGetDocumentPullDiagnosticsAsync( - workspace, workspace.CurrentSolution.Projects.Single().Documents.Single(), progress: progress); + workspace, queue, server, workspace.CurrentSolution.Projects.Single().Documents.Single(), progress: progress); Assert.Null(results); Assert.Equal("CS1513", progress.GetValues()!.Single().Diagnostics.Single().Code); @@ -218,7 +333,11 @@ public async Task TestNoWorkspaceDiagnosticsForClosedFilesWithFSAOff() var markup2 = ""; using var workspace = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.OpenFilesAndProjects); - var results = await RunGetWorkspacePullDiagnosticsAsync(workspace); + + var queue = CreateRequestQueue(workspace.CurrentSolution); + var server = GetLanguageServer(workspace.CurrentSolution); + + var results = await RunGetWorkspacePullDiagnosticsAsync(workspace, queue, server); Assert.Empty(results); } @@ -231,7 +350,11 @@ public async Task TestWorkspaceDiagnosticsForClosedFilesWithFSAOn() var markup2 = ""; using var workspace = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); - var results = await RunGetWorkspacePullDiagnosticsAsync(workspace); + + var queue = CreateRequestQueue(workspace.CurrentSolution); + var server = GetLanguageServer(workspace.CurrentSolution); + + var results = await RunGetWorkspacePullDiagnosticsAsync(workspace, queue, server); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); @@ -246,7 +369,11 @@ public async Task TestNoWorkspaceDiagnosticsForClosedFilesWithFSAOnAndInPushMode var markup2 = ""; using var workspace = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution, pullDiagnostics: false); - var results = await RunGetWorkspacePullDiagnosticsAsync(workspace); + + var queue = CreateRequestQueue(workspace.CurrentSolution); + var server = GetLanguageServer(workspace.CurrentSolution); + + var results = await RunGetWorkspacePullDiagnosticsAsync(workspace, queue, server); Assert.Equal(2, results.Length); Assert.Empty(results[0].Diagnostics); @@ -262,17 +389,19 @@ public async Task TestWorkspaceDiagnosticsForRemovedDocument() using var workspace = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); - var results = await RunGetWorkspacePullDiagnosticsAsync(workspace); + var queue = CreateRequestQueue(workspace.CurrentSolution); + var server = GetLanguageServer(workspace.CurrentSolution); + + var results = await RunGetWorkspacePullDiagnosticsAsync(workspace, queue, server); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Empty(results[1].Diagnostics); workspace.OnDocumentRemoved(workspace.Documents.First().Id); - UpdateSolutionProvider(workspace, workspace.CurrentSolution); var results2 = await RunGetWorkspacePullDiagnosticsAsync( - workspace, previousResults: CreateDiagnosticParamsFromPreviousReports(results)); + workspace, queue, server, previousResults: CreateDiagnosticParamsFromPreviousReports(results)); // First doc should show up as removed. Assert.Equal(2, results2.Length); @@ -298,14 +427,17 @@ public async Task TestNoChangeIfWorkspaceDiagnosticsCalledTwice() using var workspace = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); - var results = await RunGetWorkspacePullDiagnosticsAsync(workspace); + var queue = CreateRequestQueue(workspace.CurrentSolution); + var server = GetLanguageServer(workspace.CurrentSolution); + + var results = await RunGetWorkspacePullDiagnosticsAsync(workspace, queue, server); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Empty(results[1].Diagnostics); var results2 = await RunGetWorkspacePullDiagnosticsAsync( - workspace, previousResults: CreateDiagnosticParamsFromPreviousReports(results)); + workspace, queue, server, previousResults: CreateDiagnosticParamsFromPreviousReports(results)); Assert.Equal(2, results2.Length); Assert.Null(results2[0].Diagnostics); @@ -324,7 +456,10 @@ public async Task TestWorkspaceDiagnosticsRemovedAfterErrorIsFixed() using var workspace = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); - var results = await RunGetWorkspacePullDiagnosticsAsync(workspace); + var queue = CreateRequestQueue(workspace.CurrentSolution); + var server = GetLanguageServer(workspace.CurrentSolution); + + var results = await RunGetWorkspacePullDiagnosticsAsync(workspace, queue, server); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); @@ -334,7 +469,7 @@ public async Task TestWorkspaceDiagnosticsRemovedAfterErrorIsFixed() buffer.Insert(buffer.CurrentSnapshot.Length, "}"); var results2 = await RunGetWorkspacePullDiagnosticsAsync( - workspace, previousResults: CreateDiagnosticParamsFromPreviousReports(results)); + workspace, queue, server, previousResults: CreateDiagnosticParamsFromPreviousReports(results)); Assert.Equal(2, results2.Length); Assert.Empty(results2[0].Diagnostics); @@ -353,7 +488,10 @@ public async Task TestWorkspaceDiagnosticsRemainAfterErrorIsNotFixed() using var workspace = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); - var results = await RunGetWorkspacePullDiagnosticsAsync(workspace); + var queue = CreateRequestQueue(workspace.CurrentSolution); + var server = GetLanguageServer(workspace.CurrentSolution); + + var results = await RunGetWorkspacePullDiagnosticsAsync(workspace, queue, server); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); @@ -364,7 +502,15 @@ public async Task TestWorkspaceDiagnosticsRemainAfterErrorIsNotFixed() var buffer = workspace.Documents.First().GetTextBuffer(); buffer.Insert(0, " "); - var results2 = await RunGetWorkspacePullDiagnosticsAsync(workspace); + var document = workspace.CurrentSolution.Projects.Single().Documents.First(); + var text = await document.GetTextAsync(); + + // Hacky, but we need to close the document manually since editing the text-buffer will open it in the + // test-workspace. + workspace.OnDocumentClosed( + document.Id, TextLoader.From(TextAndVersion.Create(text, VersionStamp.Create()))); + + var results2 = await RunGetWorkspacePullDiagnosticsAsync(workspace, queue, server); Assert.Equal("CS1513", results2[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 10 }, results2[0].Diagnostics.Single().Range.Start); @@ -382,14 +528,17 @@ public async Task TestStreamingWorkspaceDiagnostics() using var workspace = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); - var results = await RunGetWorkspacePullDiagnosticsAsync(workspace); + var queue = CreateRequestQueue(workspace.CurrentSolution); + var server = GetLanguageServer(workspace.CurrentSolution); + + var results = await RunGetWorkspacePullDiagnosticsAsync(workspace, queue, server); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 9 }, results[0].Diagnostics.Single().Range.Start); var progress = BufferedProgress.Create(null); - results = await RunGetWorkspacePullDiagnosticsAsync(workspace, progress: progress); + results = await RunGetWorkspacePullDiagnosticsAsync(workspace, queue, server, progress: progress); Assert.Null(results); Assert.Equal("CS1513", progress.GetValues()![0].Diagnostics![0].Code); @@ -398,14 +547,13 @@ public async Task TestStreamingWorkspaceDiagnostics() #endregion private static async Task RunGetDocumentPullDiagnosticsAsync( - TestWorkspace workspace, Document document, + TestWorkspace workspace, + RequestExecutionQueue queue, + LanguageServerProtocol server, + Document document, string? previousResultId = null, IProgress? progress = null) { - var solution = document.Project.Solution; - var queue = CreateRequestQueue(solution); - var server = GetLanguageServer(solution); - await WaitForDiagnosticsAsync(workspace); var result = await server.ExecuteRequestAsync( @@ -421,13 +569,11 @@ private static async Task RunGetDocumentPullDiagnosticsAsync private static async Task RunGetWorkspacePullDiagnosticsAsync( TestWorkspace workspace, + RequestExecutionQueue queue, + LanguageServerProtocol server, DiagnosticParams[]? previousResults = null, IProgress? progress = null) { - var solution = workspace.CurrentSolution; - var queue = CreateRequestQueue(solution); - var server = GetLanguageServer(solution); - await WaitForDiagnosticsAsync(workspace); var result = await server.ExecuteRequestAsync( diff --git a/src/Features/LanguageServer/ProtocolUnitTests/Ordering/MutatingRequestHandler.cs b/src/Features/LanguageServer/ProtocolUnitTests/Ordering/MutatingRequestHandler.cs index 391177e670fdd..890a43f4bc7b3 100644 --- a/src/Features/LanguageServer/ProtocolUnitTests/Ordering/MutatingRequestHandler.cs +++ b/src/Features/LanguageServer/ProtocolUnitTests/Ordering/MutatingRequestHandler.cs @@ -33,7 +33,6 @@ public async Task HandleRequestAsync(TestRequest request, RequestC var response = new TestResponse { Solution = context.Solution, - RequestOrder = request.RequestOrder, StartTime = DateTime.UtcNow }; diff --git a/src/Features/LanguageServer/ProtocolUnitTests/Ordering/NonMutatingRequestHandler.cs b/src/Features/LanguageServer/ProtocolUnitTests/Ordering/NonMutatingRequestHandler.cs index bd186cda969f0..1036d8b8a907f 100644 --- a/src/Features/LanguageServer/ProtocolUnitTests/Ordering/NonMutatingRequestHandler.cs +++ b/src/Features/LanguageServer/ProtocolUnitTests/Ordering/NonMutatingRequestHandler.cs @@ -32,7 +32,6 @@ public async Task HandleRequestAsync(TestRequest request, RequestC var response = new TestResponse(); response.Solution = context.Solution; - response.RequestOrder = request.RequestOrder; response.StartTime = DateTime.UtcNow; await Task.Delay(Delay, cancellationToken).ConfigureAwait(false); diff --git a/src/Features/LanguageServer/ProtocolUnitTests/Ordering/RequestOrderingTests.cs b/src/Features/LanguageServer/ProtocolUnitTests/Ordering/RequestOrderingTests.cs index cd4ec22942b5b..de2bb92d7fb24 100644 --- a/src/Features/LanguageServer/ProtocolUnitTests/Ordering/RequestOrderingTests.cs +++ b/src/Features/LanguageServer/ProtocolUnitTests/Ordering/RequestOrderingTests.cs @@ -4,15 +4,11 @@ using System; using System.Collections.Generic; -using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; -using Microsoft.CodeAnalysis.Host.Mef; -using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.Test.Utilities; +using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; @@ -143,6 +139,71 @@ public async Task FailingMutableTaskShutsDownQueue() Assert.All(waitables.Skip(1), w => Assert.True(w.IsCanceled)); } + [Fact] + public async Task NonMutatingRequestsOperateOnTheSameSolutionAfterMutation() + { + using var workspace = CreateTestWorkspace("class C { {|caret:|} }", out var locations); + + var queue = CreateRequestQueue(workspace.CurrentSolution); + var languageServer = GetLanguageServer(workspace.CurrentSolution); + + var expectedSolution = workspace.CurrentSolution; + + // solution should be the same because no mutations have happened + var solution = await GetLSPSolution(NonMutatingRequestHandler.MethodName); + Assert.Equal(expectedSolution, solution); + + // Open a document, to get a forked solution + await ExecuteDidOpen(); + + // solution should be different because there has been a mutation + solution = await GetLSPSolution(NonMutatingRequestHandler.MethodName); + Assert.NotEqual(expectedSolution, solution); + + expectedSolution = solution; + + // solution should be the same because no mutations have happened + solution = await GetLSPSolution(NonMutatingRequestHandler.MethodName); + Assert.Equal(expectedSolution, solution); + + // Apply some random change to the workspace that the LSP server doesn't "see" + workspace.SetCurrentSolution(s => s.WithProjectName(s.Projects.First().Id, "NewName"), WorkspaceChangeKind.ProjectChanged); + + expectedSolution = workspace.CurrentSolution; + + // solution should be different because there has been a workspace change + solution = await GetLSPSolution(NonMutatingRequestHandler.MethodName); + Assert.NotEqual(expectedSolution, solution); + + expectedSolution = solution; + + // solution should be the same because no mutations have happened + solution = await GetLSPSolution(NonMutatingRequestHandler.MethodName); + Assert.Equal(expectedSolution, solution); + + return; + + async Task GetLSPSolution(string methodName) + { + var request = new TestRequest(methodName); + var response = await languageServer.ExecuteRequestAsync(queue, request.MethodName, request, new LSP.ClientCapabilities(), null, CancellationToken.None); + return response.Solution; + } + + async Task ExecuteDidOpen() + { + var didOpenParams = new LSP.DidOpenTextDocumentParams + { + TextDocument = new LSP.TextDocumentItem + { + Uri = locations["caret"].First().Uri, + Text = "// hi there" + } + }; + await languageServer.ExecuteRequestAsync(queue, Methods.TextDocumentDidOpenName, didOpenParams, new LSP.ClientCapabilities(), null, CancellationToken.None); + } + } + private async Task TestAsync(TestRequest[] requests) { var waitables = StartTestRun(requests); @@ -166,10 +227,8 @@ private List> StartTestRun(TestRequest[] requests) var clientCapabilities = new LSP.ClientCapabilities(); var waitables = new List>(); - var order = 1; foreach (var request in requests) { - request.RequestOrder = order++; waitables.Add(languageServer.ExecuteRequestAsync(queue, request.MethodName, request, clientCapabilities, null, CancellationToken.None)); } diff --git a/src/Features/LanguageServer/ProtocolUnitTests/Ordering/TestRequest.cs b/src/Features/LanguageServer/ProtocolUnitTests/Ordering/TestRequest.cs index db15c90ff716b..18553d7b59790 100644 --- a/src/Features/LanguageServer/ProtocolUnitTests/Ordering/TestRequest.cs +++ b/src/Features/LanguageServer/ProtocolUnitTests/Ordering/TestRequest.cs @@ -7,7 +7,6 @@ namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.RequestOrdering internal class TestRequest { public string MethodName { get; } - public int RequestOrder { get; set; } public TestRequest(string methodName) { diff --git a/src/Features/LanguageServer/ProtocolUnitTests/Ordering/TestResponse.cs b/src/Features/LanguageServer/ProtocolUnitTests/Ordering/TestResponse.cs index 2525343d091d3..632a509342882 100644 --- a/src/Features/LanguageServer/ProtocolUnitTests/Ordering/TestResponse.cs +++ b/src/Features/LanguageServer/ProtocolUnitTests/Ordering/TestResponse.cs @@ -8,7 +8,6 @@ namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.RequestOrdering { internal class TestResponse { - public int RequestOrder { get; set; } public DateTime StartTime { get; set; } public DateTime EndTime { get; set; } diff --git a/src/Features/LanguageServer/ProtocolUnitTests/References/FindAllReferencesHandlerTests.cs b/src/Features/LanguageServer/ProtocolUnitTests/References/FindAllReferencesHandlerTests.cs index 20e2a15bea2be..75e79699357e3 100644 --- a/src/Features/LanguageServer/ProtocolUnitTests/References/FindAllReferencesHandlerTests.cs +++ b/src/Features/LanguageServer/ProtocolUnitTests/References/FindAllReferencesHandlerTests.cs @@ -5,10 +5,10 @@ #nullable disable using System; -using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.VisualStudio.Text.Adornments; @@ -20,7 +20,7 @@ namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.References { public class FindAllReferencesHandlerTests : AbstractLanguageServerProtocolTests { - [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/43063")] + [WpfFact] public async Task TestFindAllReferencesAsync() { var markup = @@ -45,21 +45,24 @@ void M2() var results = await RunFindAllReferencesAsync(workspace.CurrentSolution, locations["caret"].First()); AssertLocationsEqual(locations["reference"], results.Select(result => result.Location)); - Assert.Equal("A", results[0].ContainingType); - Assert.Equal("B", results[2].ContainingType); - Assert.Equal("M", results[1].ContainingMember); - Assert.Equal("M2", results[3].ContainingMember); + // Results are returned in a non-deterministic order, so we order them by location + var orderedResults = results.OrderBy(r => r.Location, new OrderLocations()).ToArray(); + Assert.Equal("A", orderedResults[0].ContainingType); + Assert.Equal("B", orderedResults[2].ContainingType); + Assert.Equal("M", orderedResults[1].ContainingMember); + Assert.Equal("M2", orderedResults[3].ContainingMember); AssertValidDefinitionProperties(results, 0, Glyph.FieldPublic); + AssertHighlightCount(results, expectedDefinitionCount: 1, expectedWrittenReferenceCount: 0, expectedReferenceCount: 3); } - [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/43063")] + [WpfFact] public async Task TestFindAllReferencesAsync_Streaming() { var markup = @"class A { - public int {|reference:someInt|} = 1; + public static int {|reference:someInt|} = 1; void M() { var i = {|reference:someInt|} + 1; @@ -90,21 +93,24 @@ void M2() AssertLocationsEqual(locations["reference"], results.Select(result => result.Location)); - Assert.Equal("A", results[0].ContainingType); - Assert.Equal("B", results[2].ContainingType); - Assert.Equal("M", results[1].ContainingMember); - Assert.Equal("M2", results[3].ContainingMember); + // Results are returned in a non-deterministic order, so we order them by location + var orderedResults = results.OrderBy(r => r.Location, new OrderLocations()).ToArray(); + Assert.Equal("A", orderedResults[0].ContainingType); + Assert.Equal("B", orderedResults[2].ContainingType); + Assert.Equal("M", orderedResults[1].ContainingMember); + Assert.Equal("M2", orderedResults[3].ContainingMember); AssertValidDefinitionProperties(results, 0, Glyph.FieldPublic); + AssertHighlightCount(results, expectedDefinitionCount: 1, expectedWrittenReferenceCount: 0, expectedReferenceCount: 3); } - [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/43063")] + [WpfFact] public async Task TestFindAllReferencesAsync_Class() { var markup = @"class {|reference:A|} { - public int someInt = 1; + public static int someInt = 1; void M() { var i = someInt + 1; @@ -128,20 +134,24 @@ void M2() var actualText = string.Concat(textElement.Runs.Select(r => r.Text)); Assert.Equal("class A", actualText); - Assert.Equal("B", results[1].ContainingType); - Assert.Equal("B", results[2].ContainingType); - Assert.Equal("M2", results[2].ContainingMember); + + // Results are returned in a non-deterministic order, so we order them by location + var orderedResults = results.OrderBy(r => r.Location, new OrderLocations()).ToArray(); + Assert.Equal("B", orderedResults[1].ContainingType); + Assert.Equal("B", orderedResults[2].ContainingType); + Assert.Equal("M2", orderedResults[2].ContainingMember); AssertValidDefinitionProperties(results, 0, Glyph.ClassInternal); + AssertHighlightCount(results, expectedDefinitionCount: 1, expectedWrittenReferenceCount: 0, expectedReferenceCount: 2); } - [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/43063")] + [WpfFact] public async Task TestFindAllReferencesAsync_MultipleDocuments() { var markups = new string[] { @"class A { - public int {|reference:someInt|} = 1; + public static int {|reference:someInt|} = 1; void M() { var i = {|reference:someInt|} + 1; @@ -162,12 +172,15 @@ void M2() var results = await RunFindAllReferencesAsync(workspace.CurrentSolution, locations["caret"].First()); AssertLocationsEqual(locations["reference"], results.Select(result => result.Location)); - Assert.Equal("A", results[0].ContainingType); - Assert.Equal("B", results[2].ContainingType); - Assert.Equal("M", results[1].ContainingMember); - Assert.Equal("M2", results[3].ContainingMember); + // Results are returned in a non-deterministic order, so we order them by location + var orderedResults = results.OrderBy(r => r.Location, new OrderLocations()).ToArray(); + Assert.Equal("A", orderedResults[0].ContainingType); + Assert.Equal("B", orderedResults[2].ContainingType); + Assert.Equal("M", orderedResults[1].ContainingMember); + Assert.Equal("M2", orderedResults[3].ContainingMember); AssertValidDefinitionProperties(results, 0, Glyph.FieldPublic); + AssertHighlightCount(results, expectedDefinitionCount: 1, expectedWrittenReferenceCount: 0, expectedReferenceCount: 3); } [WpfFact] @@ -184,7 +197,7 @@ public async Task TestFindAllReferencesAsync_InvalidLocation() Assert.Empty(results); } - [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/43063")] + [WpfFact] public async Task TestFindAllReferencesMetadataDefinitionAsync() { var markup = @@ -201,6 +214,73 @@ void M() var results = await RunFindAllReferencesAsync(workspace.CurrentSolution, locations["caret"].First()); Assert.NotNull(results[0].Location.Uri); + AssertHighlightCount(results, expectedDefinitionCount: 0, expectedWrittenReferenceCount: 0, expectedReferenceCount: 1); + } + + [WpfFact, WorkItem(1240061, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1240061/")] + public async Task TestFindAllReferencesAsync_Namespace() + { + var markup = +@"namespace {|caret:|}{|reference:N|} +{ + class C + { + void M() + { + var x = new {|reference:N|}.C(); + } + } +} +"; + using var workspace = CreateTestWorkspace(markup, out var locations); + + var results = await RunFindAllReferencesAsync(workspace.CurrentSolution, locations["caret"].First()); + + // Namespace definitions should not have a location + Assert.True(results.Any(r => r.DefinitionText != null && r.Location == null)); + + // Namespace references should have a location + Assert.True(results.Any(r => r.DefinitionText == null && r.Location != null)); + + AssertValidDefinitionProperties(results, 0, Glyph.Namespace); + AssertHighlightCount(results, expectedDefinitionCount: 0, expectedWrittenReferenceCount: 0, expectedReferenceCount: 2); + } + + [WpfFact, WorkItem(1245616, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1245616/")] + public async Task TestFindAllReferencesAsync_Highlights() + { + var markup = +@"using System; + +class C +{ + void M() + { + var {|caret:|}{|reference:x|} = 1; + Console.WriteLine({|reference:x|}); + {|reference:x|} = 2; + } +} +"; + using var workspace = CreateTestWorkspace(markup, out var locations); + + var results = await RunFindAllReferencesAsync(workspace.CurrentSolution, locations["caret"].First()); + AssertHighlightCount(results, expectedDefinitionCount: 1, expectedWrittenReferenceCount: 1, expectedReferenceCount: 1); + } + + [WpfFact] + public async Task TestFindAllReferencesAsync_StaticClassification() + { + var markup = +@"static class {|caret:|}{|reference:C|} { } +"; + using var workspace = CreateTestWorkspace(markup, out var locations); + + var results = await RunFindAllReferencesAsync(workspace.CurrentSolution, locations["caret"].First()); + + // Ensure static definitions and references are only classified once + var textRuns = ((ClassifiedTextElement)results.First().Text).Runs; + Assert.Equal(9, textRuns.Count()); } private static LSP.ReferenceParams CreateReferenceParams(LSP.Location caret, IProgress progress) => @@ -251,5 +331,23 @@ private static void AssertValidDefinitionProperties(LSP.VSReferenceItem[] refere Assert.NotEqual(definitionId, referenceItems[i].Id); } } + + private static void AssertHighlightCount( + LSP.VSReferenceItem[] referenceItems, + int expectedDefinitionCount, + int expectedWrittenReferenceCount, + int expectedReferenceCount) + { + var actualDefinitionCount = referenceItems.Select( + item => ((ClassifiedTextElement)item.Text).Runs.Where(run => run.MarkerTagType == DefinitionHighlightTag.TagId)).Where(i => i.Any()).Count(); + var actualWrittenReferenceCount = referenceItems.Select( + item => ((ClassifiedTextElement)item.Text).Runs.Where(run => run.MarkerTagType == WrittenReferenceHighlightTag.TagId)).Where(i => i.Any()).Count(); + var actualReferenceCount = referenceItems.Select( + item => ((ClassifiedTextElement)item.Text).Runs.Where(run => run.MarkerTagType == ReferenceHighlightTag.TagId)).Where(i => i.Any()).Count(); + + Assert.Equal(expectedDefinitionCount, actualDefinitionCount); + Assert.Equal(expectedWrittenReferenceCount, actualWrittenReferenceCount); + Assert.Equal(expectedReferenceCount, actualReferenceCount); + } } } diff --git a/src/Features/LanguageServer/ProtocolUnitTests/References/FindImplementationsTests.cs b/src/Features/LanguageServer/ProtocolUnitTests/References/FindImplementationsTests.cs index 0c75972a27aea..7d9871b6ae52c 100644 --- a/src/Features/LanguageServer/ProtocolUnitTests/References/FindImplementationsTests.cs +++ b/src/Features/LanguageServer/ProtocolUnitTests/References/FindImplementationsTests.cs @@ -81,6 +81,7 @@ void IA.M() } }"; using var workspace = CreateTestWorkspace(string.Empty, out var _); + SetSolutionProviderWorkspace(workspace); AddMappedDocument(workspace, markup); diff --git a/src/Features/LanguageServer/ProtocolUnitTests/Rename/RenameTests.cs b/src/Features/LanguageServer/ProtocolUnitTests/Rename/RenameTests.cs index 8d34e233d0f5a..2741467ea09e7 100644 --- a/src/Features/LanguageServer/ProtocolUnitTests/Rename/RenameTests.cs +++ b/src/Features/LanguageServer/ProtocolUnitTests/Rename/RenameTests.cs @@ -4,11 +4,14 @@ #nullable disable +using System; +using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Test.Utilities; +using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Rename @@ -34,7 +37,7 @@ void M2() var renameValue = "RENAME"; var expectedEdits = locations["renamed"].Select(location => new LSP.TextEdit() { NewText = renameValue, Range = location.Range }); - var results = await RunRenameAsync(workspace.CurrentSolution, renameLocation, renameValue); + var results = await RunRenameAsync(workspace.CurrentSolution, CreateRenameParams(renameLocation, renameValue)); AssertJsonEquals(expectedEdits, ((TextDocumentEdit[])results.DocumentChanges).First().Edits); } @@ -68,7 +71,7 @@ void M2() var renameValue = "RENAME"; var expectedEdits = locations["renamed"].Select(location => new LSP.TextEdit() { NewText = renameValue, Range = location.Range }); - var results = await RunRenameAsync(workspace.CurrentSolution, renameLocation, renameValue); + var results = await RunRenameAsync(workspace.CurrentSolution, CreateRenameParams(renameLocation, renameValue)); AssertJsonEquals(expectedEdits, ((TextDocumentEdit[])results.DocumentChanges).First().Edits); } @@ -114,10 +117,50 @@ void M4() var renameValue = "RENAME"; var expectedEdits = locations["renamed"].Select(location => new LSP.TextEdit() { NewText = renameValue, Range = location.Range }); - var results = await RunRenameAsync(workspace.CurrentSolution, renameLocation, renameValue); + var results = await RunRenameAsync(workspace.CurrentSolution, CreateRenameParams(renameLocation, renameValue)); AssertJsonEquals(expectedEdits, ((TextDocumentEdit[])results.DocumentChanges).First().Edits); } + [WpfFact] + public async Task TestRename_WithMappedFileAsync() + { + var markup = +@"class A +{ + void M() + { + } + void M2() + { + M() + } +}"; + using var workspace = CreateTestWorkspace(string.Empty, out _); + SetSolutionProviderWorkspace(workspace); + + AddMappedDocument(workspace, markup); + + var startPosition = new LSP.Position { Line = 2, Character = 9 }; + var endPosition = new LSP.Position { Line = 2, Character = 10 }; + var renameText = "RENAME"; + var renameParams = CreateRenameParams(new LSP.Location + { + Uri = new Uri($"C:\\{TestSpanMapper.GeneratedFileName}"), + Range = new LSP.Range { Start = startPosition, End = endPosition } + }, "RENAME"); + + var results = await RunRenameAsync(workspace.CurrentSolution, renameParams); + + // There are two rename locations, so we expect two mapped locations. + var expectedMappedRanges = ImmutableArray.Create(TestSpanMapper.MappedFileLocation.Range, TestSpanMapper.MappedFileLocation.Range); + var expectedMappedDocument = TestSpanMapper.MappedFileLocation.Uri; + + var documentEdit = results.DocumentChanges.Value.First.Single(); + Assert.Equal(expectedMappedDocument, documentEdit.TextDocument.Uri); + Assert.Equal(expectedMappedRanges, documentEdit.Edits.Select(edit => edit.Range)); + Assert.True(documentEdit.Edits.All(edit => edit.NewText == renameText)); + } + private static LSP.RenameParams CreateRenameParams(LSP.Location location, string newName) => new LSP.RenameParams() { @@ -126,11 +169,11 @@ private static LSP.RenameParams CreateRenameParams(LSP.Location location, string TextDocument = CreateTextDocumentIdentifier(location.Uri) }; - private static async Task RunRenameAsync(Solution solution, LSP.Location renameLocation, string renamevalue) + private static async Task RunRenameAsync(Solution solution, LSP.RenameParams renameParams) { var queue = CreateRequestQueue(solution); return await GetLanguageServer(solution).ExecuteRequestAsync(queue, LSP.Methods.TextDocumentRenameName, - CreateRenameParams(renameLocation, renamevalue), new LSP.ClientCapabilities(), null, CancellationToken.None); + renameParams, new LSP.ClientCapabilities(), null, CancellationToken.None); } } } diff --git a/src/Features/LanguageServer/ProtocolUnitTests/SemanticTokens/AbstractSemanticTokensTests.cs b/src/Features/LanguageServer/ProtocolUnitTests/SemanticTokens/AbstractSemanticTokensTests.cs index 38c7e36771a78..29a8c7b72205c 100644 --- a/src/Features/LanguageServer/ProtocolUnitTests/SemanticTokens/AbstractSemanticTokensTests.cs +++ b/src/Features/LanguageServer/ProtocolUnitTests/SemanticTokens/AbstractSemanticTokensTests.cs @@ -68,7 +68,6 @@ protected static void UpdateDocumentText(string updatedText, Workspace workspace { var docId = ((TestWorkspace)workspace).Documents.First().Id; ((TestWorkspace)workspace).ChangeDocument(docId, SourceText.From(updatedText)); - UpdateSolutionProvider((TestWorkspace)workspace, workspace.CurrentSolution); } } } diff --git a/src/Features/Lsif/Generator/CompilerInvocation.cs b/src/Features/Lsif/Generator/CompilerInvocation.cs index a8083673a21b6..76d342badcc83 100644 --- a/src/Features/Lsif/Generator/CompilerInvocation.cs +++ b/src/Features/Lsif/Generator/CompilerInvocation.cs @@ -8,7 +8,9 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Newtonsoft.Json; @@ -17,14 +19,16 @@ namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator internal class CompilerInvocation { public Compilation Compilation { get; } - public HostLanguageServices LanguageServices { get; internal set; } - public string ProjectFilePath { get; internal set; } + public HostLanguageServices LanguageServices { get; } + public string ProjectFilePath { get; } + public OptionSet Options { get; } - public CompilerInvocation(Compilation compilation, HostLanguageServices languageServices, string projectFilePath) + public CompilerInvocation(Compilation compilation, HostLanguageServices languageServices, string projectFilePath, OptionSet options) { Compilation = compilation; LanguageServices = languageServices; ProjectFilePath = projectFilePath; + Options = options; } public static async Task CreateFromJsonAsync(string jsonContents) @@ -76,6 +80,8 @@ public static async Task CreateFromJsonAsync(string jsonCont var commandLineParserService = languageServices.GetRequiredService(); var parsedCommandLine = commandLineParserService.Parse(splitCommandLine, Path.GetDirectoryName(invocationInfo.ProjectFilePath), isInteractive: false, sdkDirectory: null); + var analyzerLoader = new DefaultAnalyzerAssemblyLoader(); + var projectId = ProjectId.CreateNewId(invocationInfo.ProjectFilePath); var projectInfo = ProjectInfo.Create( @@ -90,14 +96,15 @@ public static async Task CreateFromJsonAsync(string jsonCont parsedCommandLine.ParseOptions, parsedCommandLine.SourceFiles.Select(s => CreateDocumentInfo(unmappedPath: s.Path)), metadataReferences: parsedCommandLine.MetadataReferences.Select(r => MetadataReference.CreateFromFile(mapPath(r.Reference), r.Properties)), - additionalDocuments: parsedCommandLine.AdditionalFiles.Select(f => CreateDocumentInfo(unmappedPath: f.Path))) + additionalDocuments: parsedCommandLine.AdditionalFiles.Select(f => CreateDocumentInfo(unmappedPath: f.Path)), + analyzerReferences: parsedCommandLine.AnalyzerReferences.Select(r => new AnalyzerFileReference(r.FilePath, analyzerLoader))) .WithAnalyzerConfigDocuments(parsedCommandLine.AnalyzerConfigPaths.Select(CreateDocumentInfo)); workspace.AddProject(projectInfo); var compilation = await workspace.CurrentSolution.GetProject(projectId)!.GetRequiredCompilationAsync(CancellationToken.None); - return new CompilerInvocation(compilation, languageServices, invocationInfo.ProjectFilePath); + return new CompilerInvocation(compilation, languageServices, invocationInfo.ProjectFilePath, workspace.CurrentSolution.Options); // Local methods: DocumentInfo CreateDocumentInfo(string unmappedPath) diff --git a/src/Features/Lsif/Generator/Generator.cs b/src/Features/Lsif/Generator/Generator.cs index d8cea83d7df07..75a61d2c4ffd2 100644 --- a/src/Features/Lsif/Generator/Generator.cs +++ b/src/Features/Lsif/Generator/Generator.cs @@ -3,16 +3,20 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections.Concurrent; using System.Collections.Generic; +using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; -using Microsoft.CodeAnalysis.LanguageServices; +using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.ResultSetTracking; using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing; +using Microsoft.CodeAnalysis.LanguageServices; +using Microsoft.CodeAnalysis.Options; +using Roslyn.Utilities; using Methods = Microsoft.VisualStudio.LanguageServer.Protocol.Methods; -using System.Collections.Concurrent; namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator { @@ -26,7 +30,7 @@ public Generator(ILsifJsonWriter lsifJsonWriter) _lsifJsonWriter = lsifJsonWriter; } - public void GenerateForCompilation(Compilation compilation, string projectPath, HostLanguageServices languageServices) + public void GenerateForCompilation(Compilation compilation, string projectPath, HostLanguageServices languageServices, OptionSet options) { var projectVertex = new Graph.LsifProject(kind: GetLanguageKind(compilation.Language), new Uri(projectPath), _idFactory); _lsifJsonWriter.Write(projectVertex); @@ -51,7 +55,7 @@ public void GenerateForCompilation(Compilation compilation, string projectPath, // are allowed and might flush other unrelated stuff at the same time, but there's no harm -- the "causality" ordering // is preserved. var documentWriter = new BatchingLsifJsonWriter(_lsifJsonWriter); - var documentId = GenerateForDocument(semanticModel, languageServices, topLevelSymbolsResultSetTracker, documentWriter, _idFactory); + var documentId = GenerateForDocument(semanticModel, languageServices, options, topLevelSymbolsResultSetTracker, documentWriter, _idFactory); topLevelSymbolsWriter.FlushToUnderlyingAndEmpty(); documentWriter.FlushToUnderlyingAndEmpty(); @@ -77,6 +81,7 @@ public void GenerateForCompilation(Compilation compilation, string projectPath, private static Id GenerateForDocument( SemanticModel semanticModel, HostLanguageServices languageServices, + OptionSet options, IResultSetTracker topLevelSymbolsResultSetTracker, ILsifJsonWriter lsifJsonWriter, IdFactory idFactory) @@ -86,7 +91,21 @@ public void GenerateForCompilation(Compilation compilation, string projectPath, var syntaxFactsService = languageServices.GetRequiredService(); var semanticFactsService = languageServices.GetRequiredService(); - var documentVertex = new Graph.LsifDocument(new Uri(syntaxTree.FilePath), GetLanguageKind(semanticModel.Language), idFactory); + string? contentBase64Encoded = null; + + // TODO: move to checking the enum member mentioned in https://github.com/dotnet/roslyn/issues/49326 when that + // is implemented. In the mean time, we'll use a heuristic of the path being a relative path as a way to indicate + // this is a source generated file. + if (!PathUtilities.IsAbsolute(syntaxTree.FilePath)) + { + var text = semanticModel.SyntaxTree.GetText(); + + // We always use UTF-8 encoding when writing out file contents, as that's expected by LSIF implementations. + // TODO: when we move to .NET Core, is there a way to reduce allocatios here? + contentBase64Encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(text.ToString())); + } + + var documentVertex = new Graph.LsifDocument(new Uri(syntaxTree.FilePath, UriKind.RelativeOrAbsolute), GetLanguageKind(semanticModel.Language), contentBase64Encoded, idFactory); lsifJsonWriter.Write(documentVertex); lsifJsonWriter.Write(new Event(Event.EventKind.Begin, documentVertex.GetId(), idFactory)); @@ -155,7 +174,7 @@ public void GenerateForCompilation(Compilation compilation, string projectPath, // For now, we will link the range to the original definition, preferring the definition, as this is the symbol // that would be used if we invoke a feature on this range. This is analogous to the logic in // SymbolFinder.FindSymbolAtPositionAsync where if a token is both a reference and definition we'll prefer the - // definition. Once we start supporting hover we'll hae to remove the "original defintion" part of this, since + // definition. Once we start supporting hover we'll have to remove the "original definition" part of this, since // since we show different contents for different constructed types there. var symbolForLinkedResultSet = (declaredSymbol ?? referencedSymbol)!.OriginalDefinition; var symbolForLinkedResultSetId = symbolResultsTracker.GetResultSetIdForSymbol(symbolForLinkedResultSet); @@ -180,8 +199,14 @@ public void GenerateForCompilation(Compilation compilation, string projectPath, } lsifJsonWriter.Write(Edge.Create("contains", documentVertex.GetId(), rangeVertices, idFactory)); - lsifJsonWriter.Write(new Event(Event.EventKind.End, documentVertex.GetId(), idFactory)); + // Write the folding ranges for the document. + var foldingRanges = FoldingRangesHandler.GetFoldingRanges(syntaxTree, languageServices, options, isMetadataAsSource: false, CancellationToken.None); + var foldingRangeResult = new FoldingRangeResult(foldingRanges, idFactory); + lsifJsonWriter.Write(foldingRangeResult); + lsifJsonWriter.Write(Edge.Create(Methods.TextDocumentFoldingRangeName, documentVertex.GetId(), foldingRangeResult.GetId(), idFactory)); + + lsifJsonWriter.Write(new Event(Event.EventKind.End, documentVertex.GetId(), idFactory)); return documentVertex.GetId(); } diff --git a/src/Features/Lsif/Generator/Graph/FoldingRangeResult.cs b/src/Features/Lsif/Generator/Graph/FoldingRangeResult.cs new file mode 100644 index 0000000000000..cde2cdaca3597 --- /dev/null +++ b/src/Features/Lsif/Generator/Graph/FoldingRangeResult.cs @@ -0,0 +1,24 @@ +// Licensed to the .NET Foundation under one or more 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.VisualStudio.LanguageServer.Protocol; +using Newtonsoft.Json; + +namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph +{ + /// + /// Represents a foldingRangeResult vertex for serialization. See https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#request-textdocumentfoldingrange for further details. + /// + internal sealed class FoldingRangeResult : Vertex + { + [JsonProperty("result")] + public FoldingRange[] Result { get; } + + public FoldingRangeResult(FoldingRange[] result, IdFactory idFactory) + : base(label: "foldingRangeResult", idFactory) + { + Result = result; + } + } +} diff --git a/src/Features/Lsif/Generator/Graph/LsifDocument.cs b/src/Features/Lsif/Generator/Graph/LsifDocument.cs index db3fcdb45f030..a8f9b8b76bd26 100644 --- a/src/Features/Lsif/Generator/Graph/LsifDocument.cs +++ b/src/Features/Lsif/Generator/Graph/LsifDocument.cs @@ -14,11 +14,20 @@ internal sealed class LsifDocument : Vertex public Uri Uri { get; } public string LanguageId { get; } - public LsifDocument(Uri uri, string languageId, IdFactory idFactory) + /// + /// The base-64 encoded contents of the file. + /// + /// + /// We only include this for generated files. + /// + public string? Contents { get; } + + public LsifDocument(Uri uri, string languageId, string? contents, IdFactory idFactory) : base(label: "document", idFactory) { this.Uri = uri; this.LanguageId = languageId; + this.Contents = contents; } } } diff --git a/src/Features/Lsif/Generator/Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.csproj b/src/Features/Lsif/Generator/Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.csproj index 5d06ce8bddef2..80e7b11f9eaa7 100644 --- a/src/Features/Lsif/Generator/Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.csproj +++ b/src/Features/Lsif/Generator/Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.csproj @@ -43,7 +43,6 @@ - @@ -66,6 +65,9 @@ + + + diff --git a/src/Features/Lsif/Generator/Program.cs b/src/Features/Lsif/Generator/Program.cs index 0a7b47b4508cf..f304c4e3317bf 100644 --- a/src/Features/Lsif/Generator/Program.cs +++ b/src/Features/Lsif/Generator/Program.cs @@ -124,7 +124,7 @@ private static async Task GenerateFromSolutionWithMSBuildLocatedAsync(FileInfo s await logFile.WriteLineAsync($"Fetch of compilation for {project.FilePath} completed in {compilationCreationStopwatch.Elapsed.ToDisplayString()}."); var generationForProjectStopwatch = Stopwatch.StartNew(); - lsifGenerator.GenerateForCompilation(compilation, project.FilePath, project.LanguageServices); + lsifGenerator.GenerateForCompilation(compilation, project.FilePath, project.LanguageServices, project.Solution.Options); generationForProjectStopwatch.Stop(); totalTimeInGenerationPhase += generationForProjectStopwatch.Elapsed; @@ -148,7 +148,7 @@ private static async Task GenerateFromCompilerInvocationAsync(FileInfo compilerI var generationStopwatch = Stopwatch.StartNew(); var lsifGenerator = new Generator(lsifWriter); - lsifGenerator.GenerateForCompilation(compilerInvocation.Compilation, compilerInvocation.ProjectFilePath, compilerInvocation.LanguageServices); + lsifGenerator.GenerateForCompilation(compilerInvocation.Compilation, compilerInvocation.ProjectFilePath, compilerInvocation.LanguageServices, compilerInvocation.Options); await logFile.WriteLineAsync($"Generation for {compilerInvocation.ProjectFilePath} completed in {generationStopwatch.Elapsed.ToDisplayString()}."); } } diff --git a/src/Features/Lsif/GeneratorTest/CompilerInvocationTests.vb b/src/Features/Lsif/GeneratorTest/CompilerInvocationTests.vb index dc38c30bb1658..2d0e433631c41 100644 --- a/src/Features/Lsif/GeneratorTest/CompilerInvocationTests.vb +++ b/src/Features/Lsif/GeneratorTest/CompilerInvocationTests.vb @@ -149,5 +149,22 @@ Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests Assert.Equal(ReportDiagnostic.Warn, compilerInvocation.Compilation.Options.SpecificDiagnosticOptions("CA1001")) End Using End Function + + + Public Async Function TestSourceGeneratorOutputIncludedInCompilation() As Task + Dim sourceGeneratorLocation = GetType(TestSourceGenerator.HelloWorldGenerator).Assembly.Location + + Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync(" + { + ""tool"": ""csc"", + ""arguments"": ""/noconfig /analyzer:\""" + sourceGeneratorLocation.Replace("\", "\\") + "\"" /out:Output.dll"", + ""projectFilePath"": ""F:\\Project.csproj"", + ""sourceRootPath"": ""F:\\"" + }") + + Dim generatedTree = Assert.Single(compilerInvocation.Compilation.SyntaxTrees) + + Assert.EndsWith(TestSourceGenerator.HelloWorldGenerator.GeneratedClassName + ".cs", generatedTree.FilePath) + End Function End Class End Namespace diff --git a/src/Features/Lsif/GeneratorTest/FoldingRangeTests.vb b/src/Features/Lsif/GeneratorTest/FoldingRangeTests.vb new file mode 100644 index 0000000000000..1081fdc11d039 --- /dev/null +++ b/src/Features/Lsif/GeneratorTest/FoldingRangeTests.vb @@ -0,0 +1,78 @@ +' Licensed to the .NET Foundation under one or more agreements. +' The .NET Foundation licenses this file to you under the MIT license. +' See the LICENSE file in the project root for more information. + +Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces +Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.VisualStudio.LanguageServer.Protocol +Imports Roslyn.Test.Utilities +Imports Roslyn.Utilities + +Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests + + Public NotInheritable Class FoldingRangeTests + Private Const TestProjectAssemblyName As String = "TestProject" + + ' Expected 'FoldingRangeKind' argument would likely change for some of the tests when + ' https://github.com/dotnet/roslyn/projects/45#card-20049168 is implemented. + + + + + + + + Public Async Function TestFoldingRanges(code As String, rangeKind As FoldingRangeKind?) As Task + Using workspace = TestWorkspace.CreateWorkspace( + + FilePath="Z:\TestProject.csproj" CommonReferences="true"> + + <%= code %> + + + ) + + Dim annotatedLocations = AbstractLanguageServerProtocolTests.GetAnnotatedLocations(workspace, workspace.CurrentSolution) + Dim expectedRanges = annotatedLocations("foldingRange").Select(Function(location) CreateFoldingRange(rangeKind, location.Range)).OrderBy(Function(range) range.StartLine).ToArray() + + Dim document = workspace.CurrentSolution.Projects.Single().Documents.Single() + Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync(workspace) + Dim actualRanges = lsif.GetFoldingRanges(document) + + AbstractLanguageServerProtocolTests.AssertJsonEquals(expectedRanges, actualRanges) + End Using + End Function + + Private Shared Function CreateFoldingRange(kind As FoldingRangeKind?, range As Range) As FoldingRange + Return New FoldingRange() With + { + .Kind = kind, + .StartCharacter = range.Start.Character, + .EndCharacter = range.End.Character, + .StartLine = range.Start.Line, + .EndLine = range.End.Line + } + End Function + End Class +End Namespace diff --git a/src/Features/Lsif/GeneratorTest/Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests.vbproj b/src/Features/Lsif/GeneratorTest/Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests.vbproj index cc64b6a8db05f..e7c5d2f2dfc45 100644 --- a/src/Features/Lsif/GeneratorTest/Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests.vbproj +++ b/src/Features/Lsif/GeneratorTest/Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests.vbproj @@ -10,6 +10,7 @@ + - x64 - x64 - x64 - Exe - Roslyn.Compilers.CSharp.Internal.CSharpSyntaxGenerator + AnyCPU + AnyCPU + AnyCPU + CSharpSyntaxGenerator True - netcoreapp3.1 + + netcoreapp3.1;netstandard2.0 + Exe $(RoslynPortableRuntimeIdentifiers) false + false - - - - - - - - Syntax.xml - + + + + + + + \ No newline at end of file diff --git a/src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/Grammar/GrammarGenerator.cs b/src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/Grammar/GrammarGenerator.cs index 4c0fd1b4830ed..1f86270b55cbc 100644 --- a/src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/Grammar/GrammarGenerator.cs +++ b/src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/Grammar/GrammarGenerator.cs @@ -4,6 +4,9 @@ #nullable disable +// We only support grammar generation in the command line version for now which is the netcoreapp target +#if NETCOREAPP + using System; using System.Collections.Generic; using System.Collections.Immutable; @@ -174,3 +177,5 @@ internal static class GreenNode internal const int ListKind = 1; // See SyntaxKind. } } + +#endif diff --git a/src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/Program.cs b/src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/Program.cs index 3c869264e283a..829760df35458 100644 --- a/src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/Program.cs +++ b/src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/Program.cs @@ -4,8 +4,10 @@ #nullable disable +// We only include this file in the command line version for now which is the netcoreapp target +#if NETCOREAPP + using System; -using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; @@ -121,7 +123,7 @@ private static int WriteCSharpSourceFiles(string inputFile, bool writeSource, bo // between some fields (i.e. 'only one of these children can be non-null'). To make our // life easier, we just flatten all those nodes, grabbing all the nested `` nodes // and placing into a single linear list that we can then process. - FlattenChildren(tree); + TreeFlattening.FlattenChildren(tree); if (writeSignatures) { @@ -137,69 +139,24 @@ private static int WriteCSharpSourceFiles(string inputFile, bool writeSource, bo var outputInternalFile = Path.Combine(outputPath, $"{prefix}.Internal.Generated.cs"); var outputSyntaxFile = Path.Combine(outputPath, $"{prefix}.Syntax.Generated.cs"); - WriteToFile(tree, SourceWriter.WriteMain, outputMainFile); - WriteToFile(tree, SourceWriter.WriteInternal, outputInternalFile); - WriteToFile(tree, SourceWriter.WriteSyntax, outputSyntaxFile); + WriteToFile(writer => SourceWriter.WriteMain(writer, tree), outputMainFile); + WriteToFile(writer => SourceWriter.WriteInternal(writer, tree), outputInternalFile); + WriteToFile(writer => SourceWriter.WriteSyntax(writer, tree), outputSyntaxFile); } if (writeTests) { - WriteToFile(tree, TestWriter.Write, outputFile); + WriteToFile(writer => TestWriter.Write(writer, tree), outputFile); } } return 0; } - private static void FlattenChildren(Tree tree) - { - foreach (var type in tree.Types) - { - switch (type) - { - case AbstractNode node: - FlattenChildren(node.Children, node.Fields, makeOptional: false); - break; - case Node node: - FlattenChildren(node.Children, node.Fields, makeOptional: false); - break; - } - } - } - - private static void FlattenChildren( - List fieldsAndChoices, List fields, bool makeOptional) - { - foreach (var fieldOrChoice in fieldsAndChoices) - { - switch (fieldOrChoice) - { - case Field field: - if (makeOptional && !AbstractFileWriter.IsAnyNodeList(field.Type)) - { - field.Optional = "true"; - } - - fields.Add(field); - break; - case Choice choice: - // Children of choices are always optional (since the point is to - // chose from one of them and leave out the rest). - FlattenChildren(choice.Children, fields, makeOptional: true); - break; - case Sequence sequence: - FlattenChildren(sequence.Children, fields, makeOptional); - break; - default: - throw new InvalidOperationException("Unknown child type."); - } - } - } - - private static void WriteToFile(Tree tree, Action writeAction, string outputFile) + private static void WriteToFile(Action writeAction, string outputFile) { var stringBuilder = new StringBuilder(); var writer = new StringWriter(stringBuilder); - writeAction(writer, tree); + writeAction(writer); var text = stringBuilder.ToString(); int length; @@ -221,3 +178,5 @@ private static void WriteToFile(Tree tree, Action writeAction, } } } + +#endif diff --git a/src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/SourceGenerator.cs b/src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/SourceGenerator.cs new file mode 100644 index 0000000000000..ece98b05fc4c9 --- /dev/null +++ b/src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/SourceGenerator.cs @@ -0,0 +1,200 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +// We only build the Source Generator in the netstandard target +#if NETSTANDARD + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Text; +using System.Xml; +using System.Xml.Serialization; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Text; + +namespace CSharpSyntaxGenerator +{ + [Generator] + public sealed class SourceGenerator : ISourceGenerator + { + private static readonly DiagnosticDescriptor s_MissingSyntaxXml = new DiagnosticDescriptor( + "CSSG1001", + title: "Syntax.xml is missing", + messageFormat: "The Syntax.xml file was not included in the project, so we are not generating source.", + category: "SyntaxGenerator", + defaultSeverity: DiagnosticSeverity.Warning, + isEnabledByDefault: true); + + private static readonly DiagnosticDescriptor s_UnableToReadSyntaxXml = new DiagnosticDescriptor( + "CSSG1002", + title: "Syntax.xml could not be read", + messageFormat: "The Syntax.xml file could not even be read. Does it exist?", + category: "SyntaxGenerator", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true); + + private static readonly DiagnosticDescriptor s_SyntaxXmlError = new DiagnosticDescriptor( + "CSSG1003", + title: "Syntax.xml has a syntax error", + messageFormat: "{0}", + category: "SyntaxGenerator", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true); + + public void Initialize(GeneratorInitializationContext context) + { + } + + public void Execute(GeneratorExecutionContext context) + { + var syntaxXml = context.AdditionalFiles.SingleOrDefault(a => Path.GetFileName(a.Path) == "Syntax.xml"); + + if (syntaxXml == null) + { + context.ReportDiagnostic(Diagnostic.Create(s_MissingSyntaxXml, location: null)); + return; + } + + var syntaxXmlText = syntaxXml.GetText(); + + if (syntaxXmlText == null) + { + context.ReportDiagnostic(Diagnostic.Create(s_UnableToReadSyntaxXml, location: null)); + return; + } + + Tree tree; + var reader = XmlReader.Create(new SourceTextReader(syntaxXmlText), new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit }); + + try + { + var serializer = new XmlSerializer(typeof(Tree)); + tree = (Tree)serializer.Deserialize(reader); + } + catch (InvalidOperationException ex) when (ex.InnerException is XmlException) + { + var xmlException = (XmlException)ex.InnerException; + + var line = syntaxXmlText.Lines[xmlException.LineNumber - 1]; // LineNumber is one-based. + int offset = xmlException.LinePosition - 1; // LinePosition is one-based + var position = line.Start + offset; + var span = new TextSpan(position, 0); + var lineSpan = syntaxXmlText.Lines.GetLinePositionSpan(span); + + context.ReportDiagnostic( + Diagnostic.Create( + s_SyntaxXmlError, + location: Location.Create(syntaxXml.Path, span, lineSpan), + xmlException.Message)); + + return; + } + + TreeFlattening.FlattenChildren(tree); + + AddResult(writer => SourceWriter.WriteMain(writer, tree, context.CancellationToken), "Syntax.xml.Main.Generated.cs"); + AddResult(writer => SourceWriter.WriteInternal(writer, tree, context.CancellationToken), "Syntax.xml.Internal.Generated.cs"); + AddResult(writer => SourceWriter.WriteSyntax(writer, tree, context.CancellationToken), "Syntax.xml.Syntax.Generated.cs"); + + void AddResult(Action writeFunction, string hintName) + { + // Write out the contents to a StringBuilder to avoid creating a single large string + // in memory + var stringBuilder = new StringBuilder(); + using (var textWriter = new StringWriter(stringBuilder)) + { + writeFunction(textWriter); + } + + // And create a SourceText from the StringBuilder, once again avoiding allocating a single massive string + context.AddSource(hintName, SourceText.From(new StringBuilderReader(stringBuilder), stringBuilder.Length, encoding: Encoding.UTF8)); + } + } + + private sealed class SourceTextReader : TextReader + { + private readonly SourceText _sourceText; + private int _position; + + public SourceTextReader(SourceText sourceText) + { + _sourceText = sourceText; + _position = 0; + } + + public override int Peek() + { + if (_position == _sourceText.Length) + { + return -1; + } + + return _sourceText[_position]; + } + + public override int Read() + { + if (_position == _sourceText.Length) + { + return -1; + } + + return _sourceText[_position++]; + } + + public override int Read(char[] buffer, int index, int count) + { + var charsToCopy = Math.Min(count, _sourceText.Length - _position); + _sourceText.CopyTo(_position, buffer, index, charsToCopy); + _position += charsToCopy; + return charsToCopy; + } + } + + private sealed class StringBuilderReader : TextReader + { + private readonly StringBuilder _stringBuilder; + private int _position; + + public StringBuilderReader(StringBuilder stringBuilder) + { + _stringBuilder = stringBuilder; + _position = 0; + } + + public override int Peek() + { + if (_position == _stringBuilder.Length) + { + return -1; + } + + return _stringBuilder[_position]; + } + + public override int Read() + { + if (_position == _stringBuilder.Length) + { + return -1; + } + + return _stringBuilder[_position++]; + } + + public override int Read(char[] buffer, int index, int count) + { + var charsToCopy = Math.Min(count, _stringBuilder.Length - _position); + _stringBuilder.CopyTo(_position, buffer, index, charsToCopy); + _position += charsToCopy; + return charsToCopy; + } + } + } +} + +#endif diff --git a/src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/SourceWriter.cs b/src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/SourceWriter.cs index 086d0d2d4c6c0..d1a017c1e0a94 100644 --- a/src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/SourceWriter.cs +++ b/src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/SourceWriter.cs @@ -8,22 +8,23 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Threading; using System.Xml; namespace CSharpSyntaxGenerator { internal class SourceWriter : AbstractFileWriter { - private SourceWriter(TextWriter writer, Tree tree) - : base(writer, tree) + private SourceWriter(TextWriter writer, Tree tree, CancellationToken cancellationToken = default) + : base(writer, tree, cancellationToken) { } - public static void WriteMain(TextWriter writer, Tree tree) => new SourceWriter(writer, tree).WriteMain(); + public static void WriteMain(TextWriter writer, Tree tree, CancellationToken cancellationToken = default) => new SourceWriter(writer, tree, cancellationToken).WriteMain(); - public static void WriteInternal(TextWriter writer, Tree tree) => new SourceWriter(writer, tree).WriteInternal(); + public static void WriteInternal(TextWriter writer, Tree tree, CancellationToken cancellationToken = default) => new SourceWriter(writer, tree, cancellationToken).WriteInternal(); - public static void WriteSyntax(TextWriter writer, Tree tree) => new SourceWriter(writer, tree).WriteSyntax(); + public static void WriteSyntax(TextWriter writer, Tree tree, CancellationToken cancellationToken = default) => new SourceWriter(writer, tree, cancellationToken).WriteSyntax(); private void WriteFileHeader() { diff --git a/src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/TestWriter.cs b/src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/TestWriter.cs index acdcc1715858c..b13b8fda21721 100644 --- a/src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/TestWriter.cs +++ b/src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/TestWriter.cs @@ -6,12 +6,13 @@ using System.IO; using System.Linq; +using System.Threading; namespace CSharpSyntaxGenerator { internal class TestWriter : AbstractFileWriter { - private TestWriter(TextWriter writer, Tree tree) : base(writer, tree) + private TestWriter(TextWriter writer, Tree tree, CancellationToken cancellationToken = default) : base(writer, tree, cancellationToken) { } diff --git a/src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/TreeFlattening.cs b/src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/TreeFlattening.cs new file mode 100644 index 0000000000000..a20a9220d027a --- /dev/null +++ b/src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/TreeFlattening.cs @@ -0,0 +1,57 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; + +namespace CSharpSyntaxGenerator +{ + public static class TreeFlattening + { + public static void FlattenChildren(Tree tree) + { + foreach (var type in tree.Types) + { + switch (type) + { + case AbstractNode node: + FlattenChildren(node.Children, node.Fields, makeOptional: false); + break; + case Node node: + FlattenChildren(node.Children, node.Fields, makeOptional: false); + break; + } + } + } + + private static void FlattenChildren( + List fieldsAndChoices, List fields, bool makeOptional) + { + foreach (var fieldOrChoice in fieldsAndChoices) + { + switch (fieldOrChoice) + { + case Field field: + if (makeOptional && !AbstractFileWriter.IsAnyNodeList(field.Type)) + { + field.Optional = "true"; + } + + fields.Add(field); + break; + case Choice choice: + // Children of choices are always optional (since the point is to + // chose from one of them and leave out the rest). + FlattenChildren(choice.Children, fields, makeOptional: true); + break; + case Sequence sequence: + FlattenChildren(sequence.Children, fields, makeOptional); + break; + default: + throw new InvalidOperationException("Unknown child type."); + } + } + } + } +} diff --git a/src/Tools/Source/RunTests/ITestExecutor.cs b/src/Tools/Source/RunTests/ITestExecutor.cs index da56d8cd61509..3f08b497b0e90 100644 --- a/src/Tools/Source/RunTests/ITestExecutor.cs +++ b/src/Tools/Source/RunTests/ITestExecutor.cs @@ -16,10 +16,9 @@ internal readonly struct TestExecutionOptions internal string? Trait { get; } internal string? NoTrait { get; } internal bool IncludeHtml { get; } - internal bool TestVsi { get; } internal bool Retry { get; } - internal TestExecutionOptions(string dotnetFilePath, ProcDumpInfo? procDumpInfo, string testResultsDirectory, string? trait, string? noTrait, bool includeHtml, bool testVsi, bool retry) + internal TestExecutionOptions(string dotnetFilePath, ProcDumpInfo? procDumpInfo, string testResultsDirectory, string? trait, string? noTrait, bool includeHtml, bool retry) { DotnetFilePath = dotnetFilePath; ProcDumpInfo = procDumpInfo; @@ -27,7 +26,6 @@ internal TestExecutionOptions(string dotnetFilePath, ProcDumpInfo? procDumpInfo, Trait = trait; NoTrait = noTrait; IncludeHtml = includeHtml; - TestVsi = testVsi; Retry = retry; } } @@ -50,14 +48,14 @@ internal readonly struct TestResultInfo /// /// Path to the XML results file. /// - internal string ResultsFilePath { get; } + internal string? ResultsFilePath { get; } /// /// Path to the HTML results file if HTML output is enabled, otherwise, . /// internal string? HtmlResultsFilePath { get; } - internal TestResultInfo(int exitCode, string resultsFilePath, string? htmlResultsFilePath, TimeSpan elapsed, string standardOutput, string errorOutput) + internal TestResultInfo(int exitCode, string? resultsFilePath, string? htmlResultsFilePath, TimeSpan elapsed, string standardOutput, string errorOutput) { ExitCode = exitCode; ResultsFilePath = resultsFilePath; @@ -88,7 +86,7 @@ internal readonly struct TestResult internal TimeSpan Elapsed => TestResultInfo.Elapsed; internal string StandardOutput => TestResultInfo.StandardOutput; internal string ErrorOutput => TestResultInfo.ErrorOutput; - internal string ResultsDisplayFilePath => TestResultInfo.HtmlResultsFilePath ?? TestResultInfo.ResultsFilePath; + internal string? ResultsDisplayFilePath => TestResultInfo.HtmlResultsFilePath ?? TestResultInfo.ResultsFilePath; internal TestResult(AssemblyInfo assemblyInfo, TestResultInfo testResultInfo, string commandLine, ImmutableArray processResults = default, string? diagnostics = null) { diff --git a/src/Tools/Source/RunTests/Logger.cs b/src/Tools/Source/RunTests/Logger.cs index 846dfb01d444b..82cad06e7efa0 100644 --- a/src/Tools/Source/RunTests/Logger.cs +++ b/src/Tools/Source/RunTests/Logger.cs @@ -24,7 +24,7 @@ internal static void LogError(Exception ex, string line) { s_hasErrors = true; s_lines.Add($"Error {ex.Message}: {line}"); - s_lines.Add(ex.StackTrace); + s_lines.Add(ex.StackTrace ?? ""); } } @@ -34,7 +34,7 @@ internal static void Log(string message, Exception ex) { s_lines.Add(message); s_lines.Add(ex.Message); - s_lines.Add(ex.StackTrace); + s_lines.Add(ex.StackTrace ?? ""); } } @@ -43,7 +43,7 @@ internal static void Log(Exception ex) lock (s_lines) { s_lines.Add(ex.Message); - s_lines.Add(ex.StackTrace); + s_lines.Add(ex.StackTrace ?? ""); } } diff --git a/src/Tools/Source/RunTests/Options.cs b/src/Tools/Source/RunTests/Options.cs index 24b72dc85b917..91a25571a3382 100644 --- a/src/Tools/Source/RunTests/Options.cs +++ b/src/Tools/Source/RunTests/Options.cs @@ -8,6 +8,7 @@ using System.Diagnostics; using System.IO; using System.Linq; +using System.Runtime.InteropServices; using Mono.Options; namespace RunTests @@ -27,22 +28,6 @@ internal class Options /// public bool IncludeHtml { get; set; } - /// - /// Use the 64 bit test runner. - /// - public bool Test64 { get; set; } - - /// - /// Target framework used to run the tests, e.g. "net472". - /// This is currently only used to name the test result files. - /// - public string TargetFramework { get; set; } - - /// - /// Use the open integration test runner. - /// - public bool TestVsi { get; set; } - /// /// Display the results files. /// @@ -58,10 +43,18 @@ internal class Options /// public string? NoTrait { get; set; } + public string Configuration { get; set; } + /// - /// Set of assemblies to test. + /// The set of target frameworks that should be probed for test assemblies. /// - public List Assemblies { get; set; } = new List(); + public List TargetFrameworks { get; set; } = new List(); + + public List IncludeFilter { get; set; } = new List(); + + public List ExcludeFilter { get; set; } = new List(); + + public string ArtifactsDirectory { get; } /// /// Time after which the runner should kill the xunit process and exit with a failure. @@ -107,15 +100,17 @@ internal class Options public Options( string dotnetFilePath, + string artifactsDirectory, + string configuration, string testResultsDirectory, string logFilesDirectory, - string targetFramework, string platform) { DotnetFilePath = dotnetFilePath; + ArtifactsDirectory = artifactsDirectory; + Configuration = configuration; TestResultsDirectory = testResultsDirectory; LogFilesDirectory = logFilesDirectory; - TargetFramework = targetFramework; Platform = platform; } @@ -123,25 +118,30 @@ public Options( { string? dotnetFilePath = null; var platform = "x64"; - var testVsi = false; var includeHtml = false; - var targetFramework = "net472"; + var targetFrameworks = new List(); + var configuration = "Debug"; + var includeFilter = new List(); + var excludeFilter = new List(); var sequential = false; var retry = false; string? traits = null; string? noTraits = null; int? timeout = null; - string resultFileDirectory = Path.Combine(Directory.GetCurrentDirectory(), "TestResults"); + string? resultFileDirectory = null; string? logFileDirectory = null; var display = Display.None; var collectDumps = false; string? procDumpFilePath = null; + string? artifactsPath = null; var optionSet = new OptionSet() { { "dotnet=", "Path to dotnet", (string s) => dotnetFilePath = s }, + { "configuration=", "Configuration to test: Debug or Release", (string s) => configuration = s }, + { "tfm=", "Target framework to test", (string s) => targetFrameworks.Add(s) }, + { "include=", "Expression for including unit test dlls: default *.UnitTests.dll", (string s) => includeFilter.Add(s) }, + { "exclude=", "Expression for excluding unit test dlls: default is empty", (string s) => excludeFilter.Add(s) }, { "platform=", "Platform to test: x86 or x64", (string s) => platform = s }, - { "tfm=", "Target framework to test", (string s) => targetFramework = s }, - { "testvsi", "Test Visual Studio", o => testVsi = o is object }, { "html", "Include HTML file output", o => includeHtml = o is object }, { "sequential", "Run tests sequentially", o => sequential = o is object }, { "traits=", "xUnit traits to include (semicolon delimited)", (string s) => traits = s }, @@ -150,6 +150,7 @@ public Options( { "out=", "Test result file directory", (string s) => resultFileDirectory = s }, { "logs=", "Log file directory", (string s) => logFileDirectory = s }, { "display=", "Display", (Display d) => display = d }, + { "artifactspath=", "Path to the artifacts directory", (string s) => artifactsPath = s }, { "procdumppath=", "Path to procdump", (string s) => procDumpFilePath = s }, { "collectdumps", "Whether or not to gather dumps on timeouts and crashes", o => collectDumps = o is object }, { "retry", "Retry failed test a few times", o => retry = o is object }, @@ -167,6 +168,25 @@ public Options( return null; } + artifactsPath ??= TryGetArtifactsPath(); + dotnetFilePath ??= TryGetDotNetPath(); + if (includeFilter.Count == 0) + { + includeFilter.Add(".*UnitTests.*"); + } + + if (targetFrameworks.Count == 0) + { + targetFrameworks.Add("net472"); + } + + if (artifactsPath is null || !Directory.Exists(artifactsPath)) + { + Console.WriteLine($"Did not find artifacts directory at {artifactsPath}"); + return null; + } + resultFileDirectory ??= Path.Combine(artifactsPath, "TestResults"); + if (dotnetFilePath is null || !File.Exists(dotnetFilePath)) { Console.WriteLine($"Did not find 'dotnet' at {dotnetFilePath}"); @@ -191,13 +211,15 @@ public Options( return new Options( dotnetFilePath: dotnetFilePath, + artifactsDirectory: artifactsPath, + configuration: configuration, testResultsDirectory: resultFileDirectory, logFilesDirectory: logFileDirectory, - targetFramework: targetFramework, platform: platform) { - Assemblies = assemblyList, - TestVsi = testVsi, + TargetFrameworks = targetFrameworks, + IncludeFilter = includeFilter, + ExcludeFilter = excludeFilter, Display = display, ProcDumpFilePath = procDumpFilePath, CollectDumps = collectDumps, @@ -208,6 +230,30 @@ public Options( Timeout = timeout is { } t ? TimeSpan.FromMinutes(t) : null, Retry = retry, }; + + static string? TryGetArtifactsPath() + { + var path = AppContext.BaseDirectory; + while (path is object && Path.GetFileName(path) != "artifacts") + { + path = Path.GetDirectoryName(path); + } + + return path; + } + + static string? TryGetDotNetPath() + { + var dir = RuntimeEnvironment.GetRuntimeDirectory(); + var programName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "dotnet.exe" : "dotnet"; + + while (dir != null && !File.Exists(Path.Combine(dir, programName))) + { + dir = Path.GetDirectoryName(dir); + } + + return dir == null ? null : Path.Combine(dir, programName); + } } } } diff --git a/src/Tools/Source/RunTests/ProcDumpUtil.cs b/src/Tools/Source/RunTests/ProcDumpUtil.cs index 8dcc6babdc238..04f74da202a8f 100644 --- a/src/Tools/Source/RunTests/ProcDumpUtil.cs +++ b/src/Tools/Source/RunTests/ProcDumpUtil.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security.Principal; using Microsoft.Win32; @@ -35,7 +36,7 @@ internal void WriteEnvironmentVariables(Dictionary environment) internal static ProcDumpInfo? ReadFromEnvironment() { - bool validate(string s) => !string.IsNullOrEmpty(s) && Path.IsPathRooted(s); + bool validate([NotNullWhen(true)] string? s) => !string.IsNullOrEmpty(s) && Path.IsPathRooted(s); var procDumpFilePath = Environment.GetEnvironmentVariable(KeyProcDumpFilePath); var dumpDirectory = Environment.GetEnvironmentVariable(KeyProcDumpDirectory); diff --git a/src/Tools/Source/RunTests/ProcessTestExecutor.cs b/src/Tools/Source/RunTests/ProcessTestExecutor.cs index 693d5aae7c572..beea2ab3bc66c 100644 --- a/src/Tools/Source/RunTests/ProcessTestExecutor.cs +++ b/src/Tools/Source/RunTests/ProcessTestExecutor.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable +#nullable enable using System; using System.Collections.Generic; @@ -110,6 +110,7 @@ private async Task RunTestAsyncInternal(AssemblyInfo assemblyInfo, b var commandLineArguments = GetCommandLineArguments(assemblyInfo); var resultsFilePath = GetResultsFilePath(assemblyInfo); var resultsDir = Path.GetDirectoryName(resultsFilePath); + var htmlResultsFilePath = Options.IncludeHtml ? GetResultsFilePath(assemblyInfo, "html") : null; var processResultList = new List(); ProcessInfo? procDumpProcessInfo = null; @@ -194,6 +195,7 @@ private async Task RunTestAsyncInternal(AssemblyInfo assemblyInfo, b // Delete the output file. File.Delete(resultsFilePath); resultsFilePath = null; + htmlResultsFilePath = null; } } @@ -201,7 +203,6 @@ private async Task RunTestAsyncInternal(AssemblyInfo assemblyInfo, b var standardOutput = string.Join(Environment.NewLine, xunitProcessResult.OutputLines) ?? ""; var errorOutput = string.Join(Environment.NewLine, xunitProcessResult.ErrorLines) ?? ""; - var htmlResultsFilePath = Options.IncludeHtml ? GetResultsFilePath(assemblyInfo, "html") : null; var testResultInfo = new TestResultInfo( exitCode: xunitProcessResult.ExitCode, resultsFilePath: resultsFilePath, diff --git a/src/Tools/Source/RunTests/Program.cs b/src/Tools/Source/RunTests/Program.cs index 250b2a8c509f3..d3dba579a7b10 100644 --- a/src/Tools/Source/RunTests/Program.cs +++ b/src/Tools/Source/RunTests/Program.cs @@ -10,10 +10,9 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using RestSharp; using System.Collections.Immutable; -using Newtonsoft.Json; using System.Diagnostics; +using System.Text.RegularExpressions; namespace RunTests { @@ -123,18 +122,19 @@ private static async Task RunAsync(Options options, TimeSpan timeout, Cance private static async Task RunAsync(Options options, CancellationToken cancellationToken) { - if (!CheckAssemblyList(options)) - { - return ExitFailure; - } - var testExecutor = CreateTestExecutor(options); var testRunner = new TestRunner(options, testExecutor); var start = DateTime.Now; var assemblyInfoList = GetAssemblyList(options); + if (assemblyInfoList.Count == 0) + { + ConsoleUtil.WriteLine(ConsoleColor.Red, "No assemblies to test"); + return ExitFailure; + } + var assemblyCount = assemblyInfoList.GroupBy(x => x.AssemblyPath).Count(); ConsoleUtil.WriteLine($"Proc dump location: {options.ProcDumpFilePath}"); - ConsoleUtil.WriteLine($"Running {options.Assemblies.Count} test assemblies in {assemblyInfoList.Count} partitions"); + ConsoleUtil.WriteLine($"Running {assemblyCount} test assemblies in {assemblyInfoList.Count} partitions"); var result = await testRunner.RunAllAsync(assemblyInfoList, cancellationToken).ConfigureAwait(true); var elapsed = DateTime.Now - start; @@ -273,44 +273,58 @@ async Task DumpProcess(Process targetProcess, string procDumpExeFilePath, string return null; } - /// - /// Quick sanity check to look over the set of assemblies to make sure they are valid and something was - /// specified. - /// - private static bool CheckAssemblyList(Options options) + private static List GetAssemblyList(Options options) { - var anyMissing = false; - foreach (var assemblyPath in options.Assemblies) - { - if (!File.Exists(assemblyPath)) - { - ConsoleUtil.WriteLine(ConsoleColor.Red, $"The file '{assemblyPath}' does not exist, is an invalid file name, or you do not have sufficient permissions to read the specified file."); - anyMissing = true; - } - } - - if (anyMissing) - { - return false; - } + var scheduler = new AssemblyScheduler(options); + var list = new List(); + var assemblyPaths = GetAssemblyFilePaths(options); - if (options.Assemblies.Count == 0) + foreach (var assemblyPath in assemblyPaths.OrderByDescending(x => new FileInfo(x.FilePath).Length)) { - ConsoleUtil.WriteLine("No test assemblies specified."); - return false; + list.AddRange(scheduler.Schedule(assemblyPath.FilePath).Select(x => new AssemblyInfo(x, assemblyPath.TargetFramework, options.Platform))); } - return true; + return list; } - private static List GetAssemblyList(Options options) + private static List<(string FilePath, string TargetFramework)> GetAssemblyFilePaths(Options options) { - var scheduler = new AssemblyScheduler(options); - var list = new List(); - - foreach (var assemblyPath in options.Assemblies.OrderByDescending(x => new FileInfo(x).Length)) + var list = new List<(string, string)>(); + var binDirectory = Path.Combine(options.ArtifactsDirectory, "bin"); + foreach (var project in Directory.EnumerateDirectories(binDirectory, "*", SearchOption.TopDirectoryOnly)) { - list.AddRange(scheduler.Schedule(assemblyPath).Select(x => new AssemblyInfo(x, options.TargetFramework, options.Platform))); + var name = Path.GetFileName(project); + var include = false; + foreach (var pattern in options.IncludeFilter) + { + if (Regex.IsMatch(name, pattern.Trim('\'', '"'))) + { + include = true; + } + } + + if (!include) + { + continue; + } + + foreach (var pattern in options.ExcludeFilter) + { + if (Regex.IsMatch(name, pattern.Trim('\'', '"'))) + { + continue; + } + } + + var fileName = $"{name}.dll"; + foreach (var targetFramework in options.TargetFrameworks) + { + var filePath = Path.Combine(project, options.Configuration, targetFramework, fileName); + if (File.Exists(filePath)) + { + list.Add((filePath, targetFramework)); + } + } } return list; @@ -353,7 +367,6 @@ private static ProcessTestExecutor CreateTestExecutor(Options options) trait: options.Trait, noTrait: options.NoTrait, includeHtml: options.IncludeHtml, - testVsi: options.TestVsi, retry: options.Retry); return new ProcessTestExecutor(testExecutionOptions); } diff --git a/src/Tools/Source/RunTests/RunTests.csproj b/src/Tools/Source/RunTests/RunTests.csproj index 11d81724169ad..d3168625a17ab 100644 --- a/src/Tools/Source/RunTests/RunTests.csproj +++ b/src/Tools/Source/RunTests/RunTests.csproj @@ -3,21 +3,17 @@ Exe - net472 + netcoreapp3.1 true false false - - - - - - - + + + \ No newline at end of file diff --git a/src/Tools/Source/RunTests/TestRunner.cs b/src/Tools/Source/RunTests/TestRunner.cs index a7d32ddb9f261..f95b7376e6218 100644 --- a/src/Tools/Source/RunTests/TestRunner.cs +++ b/src/Tools/Source/RunTests/TestRunner.cs @@ -45,7 +45,7 @@ internal async Task RunAllAsync(IEnumerable assembly // Use 1.5 times the number of processors for unit tests, but only 1 processor for the open integration tests // since they perform actual UI operations (such as mouse clicks and sending keystrokes) and we don't want two // tests to conflict with one-another. - var max = (_options.TestVsi || _options.Sequential) ? 1 : (int)(Environment.ProcessorCount * 1.5); + var max = _options.Sequential ? 1 : (int)(Environment.ProcessorCount * 1.5); var waiting = new Stack(assemblyInfoList); var running = new List>(); var completed = new List(); @@ -67,7 +67,20 @@ internal async Task RunAllAsync(IEnumerable assembly if (!testResult.Succeeded) { failures++; - ConsoleUtil.WriteLine(ConsoleColor.Red, "Test failure log: " + testResult.ResultsDisplayFilePath); + if (testResult.ResultsDisplayFilePath is string resultsPath) + { + ConsoleUtil.WriteLine(ConsoleColor.Red, resultsPath); + } + else + { + foreach (var result in testResult.ProcessResults) + { + foreach (var line in result.ErrorLines) + { + ConsoleUtil.WriteLine(ConsoleColor.Red, line); + } + } + } } completed.Add(testResult); @@ -178,7 +191,8 @@ private void PrintFailedTestResult(TestResult testResult) var htmlResultsFilePath = testResult.TestResultInfo.HtmlResultsFilePath; if (!string.IsNullOrEmpty(htmlResultsFilePath)) { - Process.Start(htmlResultsFilePath); + var startInfo = new ProcessStartInfo() { FileName = htmlResultsFilePath, UseShellExecute = true }; + Process.Start(startInfo); } } } diff --git a/src/VisualStudio/CSharp/Impl/CSharpVSResources.resx b/src/VisualStudio/CSharp/Impl/CSharpVSResources.resx index 885f35be54a5f..4cf5fd6b8a91a 100644 --- a/src/VisualStudio/CSharp/Impl/CSharpVSResources.resx +++ b/src/VisualStudio/CSharp/Impl/CSharpVSResources.resx @@ -539,9 +539,6 @@ Show name s_uggestions - - Generate Event Subscription - Remove unnecessary usings @@ -629,4 +626,8 @@ Show hints for 'new' expressions + + Add missing using directives on paste + 'using' is a C# keyword and should not be localized + \ No newline at end of file diff --git a/src/VisualStudio/CSharp/Impl/Interactive/xlf/Commands.vsct.zh-Hans.xlf b/src/VisualStudio/CSharp/Impl/Interactive/xlf/Commands.vsct.zh-Hans.xlf index 0e96e8e59b988..62aa991fd9ee3 100644 --- a/src/VisualStudio/CSharp/Impl/Interactive/xlf/Commands.vsct.zh-Hans.xlf +++ b/src/VisualStudio/CSharp/Impl/Interactive/xlf/Commands.vsct.zh-Hans.xlf @@ -1,6 +1,6 @@  - + C# Interactive diff --git a/src/VisualStudio/CSharp/Impl/Interactive/xlf/Commands.vsct.zh-Hant.xlf b/src/VisualStudio/CSharp/Impl/Interactive/xlf/Commands.vsct.zh-Hant.xlf index 8ffcebe6e1215..264f2d7d65972 100644 --- a/src/VisualStudio/CSharp/Impl/Interactive/xlf/Commands.vsct.zh-Hant.xlf +++ b/src/VisualStudio/CSharp/Impl/Interactive/xlf/Commands.vsct.zh-Hant.xlf @@ -1,6 +1,6 @@  - + C# Interactive diff --git a/src/VisualStudio/CSharp/Impl/Options/AdvancedOptionPageControl.xaml b/src/VisualStudio/CSharp/Impl/Options/AdvancedOptionPageControl.xaml index d07a1231563e8..a5584495dfdb9 100644 --- a/src/VisualStudio/CSharp/Impl/Options/AdvancedOptionPageControl.xaml +++ b/src/VisualStudio/CSharp/Impl/Options/AdvancedOptionPageControl.xaml @@ -59,6 +59,9 @@ + - \ No newline at end of file + diff --git a/src/VisualStudio/CSharp/Impl/Options/AdvancedOptionPageControl.xaml.cs b/src/VisualStudio/CSharp/Impl/Options/AdvancedOptionPageControl.xaml.cs index 2cd232ae16a81..d6416acf26aac 100644 --- a/src/VisualStudio/CSharp/Impl/Options/AdvancedOptionPageControl.xaml.cs +++ b/src/VisualStudio/CSharp/Impl/Options/AdvancedOptionPageControl.xaml.cs @@ -49,6 +49,7 @@ public AdvancedOptionPageControl(OptionStore optionStore, IComponentModel compon BindToOption(SeparateImportGroups, GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.CSharp); BindToOption(SuggestForTypesInReferenceAssemblies, SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, LanguageNames.CSharp); BindToOption(SuggestForTypesInNuGetPackages, SymbolSearchOptions.SuggestForTypesInNuGetPackages, LanguageNames.CSharp); + BindToOption(AddUsingsOnPaste, FeatureOnOffOptions.AddImportsOnPaste, LanguageNames.CSharp); BindToOption(Split_string_literals_on_enter, SplitStringLiteralOptions.Enabled, LanguageNames.CSharp); BindToOption(EnterOutliningMode, FeatureOnOffOptions.Outlining, LanguageNames.CSharp); diff --git a/src/VisualStudio/CSharp/Impl/Options/AdvancedOptionPageStrings.cs b/src/VisualStudio/CSharp/Impl/Options/AdvancedOptionPageStrings.cs index 9d6e7c4e10972..0eac23ba5bdaa 100644 --- a/src/VisualStudio/CSharp/Impl/Options/AdvancedOptionPageStrings.cs +++ b/src/VisualStudio/CSharp/Impl/Options/AdvancedOptionPageStrings.cs @@ -217,6 +217,9 @@ public static string Option_Suggest_usings_for_types_in_reference_assemblies public static string Option_Suggest_usings_for_types_in_NuGet_packages => CSharpVSResources.Suggest_usings_for_types_in_NuGet_packages; + public static string Option_Add_missing_using_directives_on_paste + => CSharpVSResources.Add_missing_using_directives_on_paste; + public static string Option_Report_invalid_placeholders_in_string_dot_format_calls => CSharpVSResources.Report_invalid_placeholders_in_string_dot_format_calls; diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.cs.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.cs.xlf index 78aebc327fcac..60de24b32bf95 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.cs.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.cs.xlf @@ -2,6 +2,11 @@ + + Add missing using directives on paste + Add missing using directives on paste + 'using' is a C# keyword and should not be localized + Apply all C# formatting rules (indentation, wrapping, spacing) Použít všechna formátovací pravidla jazyka C# (odsazení, zabalení, mezery) @@ -9,7 +14,7 @@ Automatically show completion list in argument lists (experimental) - Automaticky zobrazovat seznam dokončení v seznamech argumentů (experimentální) + Automaticky zobrazovat seznam dokončení v seznamech argumentů (experimentální) @@ -34,12 +39,12 @@ Edit color scheme - Edit color scheme + Upravit barevné schéma Format document - Format document + Formátovat dokument @@ -52,11 +57,6 @@ Obecné Title of the control group on the General Formatting options page - - Generate Event Subscription - Generovat odběr událostí - - In relational operators: < > <= >= is as == != V relačních operátorech: < > <= >= is as == != @@ -64,7 +64,7 @@ Insert // at the start of new lines when writing // comments - Insert // at the start of new lines when writing // comments + Při psaní komentářů // na začátek řádku vkládat // @@ -79,7 +79,7 @@ Pattern matching preferences: - Pattern matching preferences: + Předvolby porovnávání vzorů: @@ -89,7 +89,7 @@ Prefer implicit object creation when type is apparent - Prefer implicit object creation when type is apparent + Upřednostňovat implicitní vytvoření objektu, pokud je typ zřejmý @@ -104,7 +104,7 @@ Prefer pattern matching over mixed type check - Prefer pattern matching over mixed type check + Upřednostňovat porovnávání vzorů nad kontrolou kombinovaných typů @@ -124,12 +124,12 @@ Show hints for 'new' expressions - Show hints for 'new' expressions + Zobrazit nápovědy pro výrazy new Show items from unimported namespaces - Zobrazit položky z neimportovaných oborů názvů (experimentální) + Zobrazit položky z neimportovaných oborů názvů diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.de.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.de.xlf index a7e899fd66344..847bf5bade520 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.de.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.de.xlf @@ -2,6 +2,11 @@ + + Add missing using directives on paste + Add missing using directives on paste + 'using' is a C# keyword and should not be localized + Apply all C# formatting rules (indentation, wrapping, spacing) Alle C#-Formatierungsregeln anwenden (Einzug, Umbruch, Abstand) @@ -9,7 +14,7 @@ Automatically show completion list in argument lists (experimental) - Vervollständigungsliste in Argumentlisten automatisch anzeigen (experimentell) + Vervollständigungsliste in Argumentlisten automatisch anzeigen (experimentell) @@ -34,12 +39,12 @@ Edit color scheme - Edit color scheme + Farbschema bearbeiten Format document - Format document + Dokument formatieren @@ -52,11 +57,6 @@ Allgemein Title of the control group on the General Formatting options page - - Generate Event Subscription - Ereignisabonnement generieren - - In relational operators: < > <= >= is as == != In relationalen Operatoren: < > <= >= is as == != @@ -64,7 +64,7 @@ Insert // at the start of new lines when writing // comments - Insert // at the start of new lines when writing // comments + Fügen Sie beim Schreiben von //-Kommentaren zwei Schrägstriche (//) am Anfang der neuen Zeilen ein. @@ -79,7 +79,7 @@ Pattern matching preferences: - Pattern matching preferences: + Einstellungen für den Musterabgleich: @@ -89,7 +89,7 @@ Prefer implicit object creation when type is apparent - Prefer implicit object creation when type is apparent + Implizite Objekterstellung bevorzugen, wenn der Typ offensichtlich ist @@ -99,12 +99,12 @@ Prefer pattern matching - Prefer pattern matching + Musterabgleich bevorzugen Prefer pattern matching over mixed type check - Prefer pattern matching over mixed type check + Musterabgleich gegenüber der Überprüfung gemischter Typen bevorzugen @@ -124,12 +124,12 @@ Show hints for 'new' expressions - Show hints for 'new' expressions + Hinweise für new-Ausdrücke anzeigen Show items from unimported namespaces - Elemente aus nicht importierten Namespaces anzeigen (experimentell) + Elemente aus nicht importierten Namespaces anzeigen @@ -554,7 +554,7 @@ _Place 'System' directives first when sorting usings - "System"-Direktiven beim Sortieren von Using-Direktiven zuerst anordnen + System-Anweisungen beim Sortieren von using-Anweisungen an erster Stelle _platzieren diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.es.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.es.xlf index e83793f12929d..19a0741011e12 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.es.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.es.xlf @@ -2,6 +2,11 @@ + + Add missing using directives on paste + Add missing using directives on paste + 'using' is a C# keyword and should not be localized + Apply all C# formatting rules (indentation, wrapping, spacing) Aplicar todas las reglas de formato de C# (sangría, ajuste, espaciado) @@ -9,7 +14,7 @@ Automatically show completion list in argument lists (experimental) - Mostrar automáticamente la lista de finalización en las listas de argumentos (experimental) + Mostrar automáticamente la lista de finalización en las listas de argumentos (experimental) @@ -34,12 +39,12 @@ Edit color scheme - Edit color scheme + Editar esquema de color Format document - Format document + Dar formato al documento @@ -52,11 +57,6 @@ General Title of the control group on the General Formatting options page - - Generate Event Subscription - Generar suscripción de eventos - - In relational operators: < > <= >= is as == != En los operadores relacionales: < > <= >= is as == != @@ -64,7 +64,7 @@ Insert // at the start of new lines when writing // comments - Insert // at the start of new lines when writing // comments + Insertar // al comienzo de las líneas nuevas al escribir comentarios // @@ -79,7 +79,7 @@ Pattern matching preferences: - Pattern matching preferences: + Preferencias de coincidencia de patrón: @@ -89,7 +89,7 @@ Prefer implicit object creation when type is apparent - Prefer implicit object creation when type is apparent + Preferir la creación implícita de objetos cuando el tipo sea aparente @@ -99,12 +99,12 @@ Prefer pattern matching - Prefer pattern matching + Preferir coincidencia de patrones Prefer pattern matching over mixed type check - Prefer pattern matching over mixed type check + Anteponer coincidencia de patrón a la comprobación de tipo mixto @@ -124,12 +124,12 @@ Show hints for 'new' expressions - Show hints for 'new' expressions + Mostrar sugerencias para las expresiones "new" Show items from unimported namespaces - Mostrar elementos de espacios de nombres no importados (experimental) + Mostrar elementos de espacios de nombres no importados diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.fr.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.fr.xlf index 212f41ab16b3f..e57e9d199f829 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.fr.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.fr.xlf @@ -2,6 +2,11 @@ + + Add missing using directives on paste + Add missing using directives on paste + 'using' is a C# keyword and should not be localized + Apply all C# formatting rules (indentation, wrapping, spacing) Appliquer toutes les règles de mise en forme de C# (indentation, enveloppement, espacement) @@ -9,7 +14,7 @@ Automatically show completion list in argument lists (experimental) - Afficher automatiquement la liste de complétion dans les listes d'arguments (expérimental) + Afficher automatiquement la liste de complétion dans les listes d'arguments (expérimental) @@ -34,12 +39,12 @@ Edit color scheme - Edit color scheme + Modifier le modèle de couleurs Format document - Format document + Mettre en forme le document @@ -52,11 +57,6 @@ Général Title of the control group on the General Formatting options page - - Generate Event Subscription - Générer un abonnement à des événements - - In relational operators: < > <= >= is as == != Dans les opérateurs relationnels : < > <= >= is as == != @@ -64,7 +64,7 @@ Insert // at the start of new lines when writing // comments - Insert // at the start of new lines when writing // comments + Insérer // au début des nouvelles lignes pour l'écriture de commentaires // @@ -79,7 +79,7 @@ Pattern matching preferences: - Pattern matching preferences: + Préférences relatives aux critères spéciaux : @@ -89,7 +89,7 @@ Prefer implicit object creation when type is apparent - Prefer implicit object creation when type is apparent + Préférer la création d'objets implicites quand le type est apparent @@ -99,12 +99,12 @@ Prefer pattern matching - Prefer pattern matching + Préférer les critères spéciaux Prefer pattern matching over mixed type check - Prefer pattern matching over mixed type check + Préférer les critères spéciaux à la vérification de type mixte @@ -124,12 +124,12 @@ Show hints for 'new' expressions - Show hints for 'new' expressions + Afficher les indicateurs pour les expressions 'new' Show items from unimported namespaces - Afficher les éléments des espaces de noms qui ne sont pas importés (expérimental) + Afficher les éléments des espaces de noms qui ne sont pas importés diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.it.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.it.xlf index e796a13e1623a..21aa9369879eb 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.it.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.it.xlf @@ -2,6 +2,11 @@ + + Add missing using directives on paste + Add missing using directives on paste + 'using' is a C# keyword and should not be localized + Apply all C# formatting rules (indentation, wrapping, spacing) Applica tutte le regole di formattazione di C# (rientro, ritorno a capo, spaziatura) @@ -9,7 +14,7 @@ Automatically show completion list in argument lists (experimental) - Mostra automaticamente l'elenco di completamento negli elenchi di argomenti (sperimentale) + Mostra automaticamente l'elenco di completamento negli elenchi di argomenti (sperimentale) @@ -34,12 +39,12 @@ Edit color scheme - Edit color scheme + Modifica combinazione colori Format document - Format document + Formatta documento @@ -52,11 +57,6 @@ Generale Title of the control group on the General Formatting options page - - Generate Event Subscription - Genera sottoscrizione di eventi - - In relational operators: < > <= >= is as == != In operatori relazionali: < > <= >= is as == != @@ -64,7 +64,7 @@ Insert // at the start of new lines when writing // comments - Insert // at the start of new lines when writing // comments + Inserisci * all'inizio di nuove righe quando si scrivono commenti // @@ -79,7 +79,7 @@ Pattern matching preferences: - Pattern matching preferences: + Preferenze per criteri di ricerca: @@ -89,7 +89,7 @@ Prefer implicit object creation when type is apparent - Prefer implicit object creation when type is apparent + Preferisci la creazione implicita di oggetti quando il tipo è apparente @@ -99,12 +99,12 @@ Prefer pattern matching - Prefer pattern matching + Preferisci i criteri di ricerca Prefer pattern matching over mixed type check - Prefer pattern matching over mixed type check + Preferisci criteri di ricerca al controllo dei tipi misti @@ -124,12 +124,12 @@ Show hints for 'new' expressions - Show hints for 'new' expressions + Mostra suggerimenti per le espressioni 'new' Show items from unimported namespaces - Mostra elementi da spazi dei nomi non importati (sperimentale) + Mostra elementi da spazi dei nomi non importati diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.ja.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.ja.xlf index 2d95b3fe9d967..36d7fd7607d0b 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.ja.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.ja.xlf @@ -2,6 +2,11 @@ + + Add missing using directives on paste + Add missing using directives on paste + 'using' is a C# keyword and should not be localized + Apply all C# formatting rules (indentation, wrapping, spacing) C# のすべての書式ルール (インデント、折り返し、スペース) を適用します @@ -9,7 +14,7 @@ Automatically show completion list in argument lists (experimental) - 入力候補一覧を引数リストに自動的に表示する (試験段階) + 入力候補一覧を引数リストに自動的に表示する (試験段階) @@ -34,12 +39,12 @@ Edit color scheme - Edit color scheme + 配色の編集 Format document - Format document + ドキュメントのフォーマット @@ -52,11 +57,6 @@ 全般 Title of the control group on the General Formatting options page - - Generate Event Subscription - イベント サブスクリプションの生成 - - In relational operators: < > <= >= is as == != 関係演算子: < > <= >= is as == != @@ -64,7 +64,7 @@ Insert // at the start of new lines when writing // comments - Insert // at the start of new lines when writing // comments + // コメントの記述時に // を新しい行の先頭に挿入する @@ -79,7 +79,7 @@ Pattern matching preferences: - Pattern matching preferences: + パターン マッチング設定: @@ -89,7 +89,7 @@ Prefer implicit object creation when type is apparent - Prefer implicit object creation when type is apparent + 型が明白な場合に暗黙的なオブジェクトの作成を優先する @@ -99,12 +99,12 @@ Prefer pattern matching - Prefer pattern matching + パターン マッチングを優先する Prefer pattern matching over mixed type check - Prefer pattern matching over mixed type check + 混合型チェックよりパターン マッチングを優先する @@ -124,12 +124,12 @@ Show hints for 'new' expressions - Show hints for 'new' expressions + 'new' 式のヒントを表示する Show items from unimported namespaces - インポートされていない名前空間の項目を表示する (試験段階) + インポートされていない名前空間の項目を表示する diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.ko.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.ko.xlf index 4fa4148d45414..67dd3bcbde98a 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.ko.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.ko.xlf @@ -2,6 +2,11 @@ + + Add missing using directives on paste + Add missing using directives on paste + 'using' is a C# keyword and should not be localized + Apply all C# formatting rules (indentation, wrapping, spacing) 모든 C# 서식 규칙 적용(들여쓰기, 래핑, 간격 조정) @@ -9,7 +14,7 @@ Automatically show completion list in argument lists (experimental) - 인수 목록에 자동으로 완성 목록 표시(실험적) + 인수 목록에 자동으로 완성 목록 표시(실험적) @@ -34,12 +39,12 @@ Edit color scheme - Edit color scheme + 색 구성표 편집 Format document - Format document + 문서 서식 @@ -52,11 +57,6 @@ 일반 Title of the control group on the General Formatting options page - - Generate Event Subscription - 이벤트 구독 생성 - - In relational operators: < > <= >= is as == != 관계 연산자: < > <= >= is as == != @@ -64,7 +64,7 @@ Insert // at the start of new lines when writing // comments - Insert // at the start of new lines when writing // comments + // 주석을 작성할 때 새 줄의 시작 부분에 // 삽입 @@ -79,7 +79,7 @@ Pattern matching preferences: - Pattern matching preferences: + 패턴 일치 기본 설정: @@ -89,7 +89,7 @@ Prefer implicit object creation when type is apparent - Prefer implicit object creation when type is apparent + 형식이 명백한 경우 암시적 개체 만들기 선호 @@ -99,12 +99,12 @@ Prefer pattern matching - Prefer pattern matching + 패턴 일치 선호 Prefer pattern matching over mixed type check - Prefer pattern matching over mixed type check + 혼합 형식 검사 대신 패턴 일치 사용 @@ -124,12 +124,12 @@ Show hints for 'new' expressions - Show hints for 'new' expressions + 'new' 식에 대한 힌트 표시 Show items from unimported namespaces - 가져오지 않은 네임스페이스의 항목 표시(실험적) + 가져오지 않은 네임스페이스의 항목 표시 diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.pl.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.pl.xlf index c576960e0ec53..6a86d0dad335d 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.pl.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.pl.xlf @@ -2,6 +2,11 @@ + + Add missing using directives on paste + Add missing using directives on paste + 'using' is a C# keyword and should not be localized + Apply all C# formatting rules (indentation, wrapping, spacing) Zastosuj wszystkie reguły formatowania kodu C# (wcięcia, zawijanie, odstępy) @@ -9,7 +14,7 @@ Automatically show completion list in argument lists (experimental) - Automatycznie pokaż listę uzupełniania na listach argumentów (eksperymentalne) + Automatycznie pokaż listę uzupełniania na listach argumentów (eksperymentalne) @@ -34,12 +39,12 @@ Edit color scheme - Edit color scheme + Edytuj schemat kolorów Format document - Format document + Formatuj dokument @@ -52,11 +57,6 @@ Ogólne Title of the control group on the General Formatting options page - - Generate Event Subscription - Generuj subskrypcję zdarzenia - - In relational operators: < > <= >= is as == != W operatorach relacyjnych: < > <= >= is as == != @@ -64,7 +64,7 @@ Insert // at the start of new lines when writing // comments - Insert // at the start of new lines when writing // comments + Wstaw znaki // na początku nowych wierszy podczas pisania komentarzy ze znakami // @@ -79,7 +79,7 @@ Pattern matching preferences: - Pattern matching preferences: + Preferencje dopasowywania wzorca: @@ -89,7 +89,7 @@ Prefer implicit object creation when type is apparent - Prefer implicit object creation when type is apparent + Preferuj niejawne tworzenie obiektu, gdy typ jest oczywisty @@ -99,12 +99,12 @@ Prefer pattern matching - Prefer pattern matching + Preferuj dopasowywanie do wzorca Prefer pattern matching over mixed type check - Prefer pattern matching over mixed type check + Preferuj sprawdzanie dopasowania wzorca do typów mieszanych @@ -124,12 +124,12 @@ Show hints for 'new' expressions - Show hints for 'new' expressions + Pokaż wskazówki dla wyrażeń „new” Show items from unimported namespaces - Pokaż elementy z nieimportowanych przestrzeni nazw (eksperymentalne) + Pokaż elementy z nieimportowanych przestrzeni nazw diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.pt-BR.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.pt-BR.xlf index fd7c62d0d95e7..9cb6278f7f2b8 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.pt-BR.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.pt-BR.xlf @@ -2,6 +2,11 @@ + + Add missing using directives on paste + Add missing using directives on paste + 'using' is a C# keyword and should not be localized + Apply all C# formatting rules (indentation, wrapping, spacing) Aplicar todas as regras de formatação de C# (recuo, quebra de linha, espaçamento) @@ -9,7 +14,7 @@ Automatically show completion list in argument lists (experimental) - Mostrar automaticamente a lista de conclusão nas listas de argumentos (experimental) + Mostrar automaticamente a lista de conclusão nas listas de argumentos (experimental) @@ -34,12 +39,12 @@ Edit color scheme - Edit color scheme + Editar o esquema de cores Format document - Format document + Formatar o documento @@ -52,11 +57,6 @@ Geral Title of the control group on the General Formatting options page - - Generate Event Subscription - Gerar Assinatura de Evento - - In relational operators: < > <= >= is as == != Em operadores relacionais: < > <= >= is as == != @@ -64,7 +64,7 @@ Insert // at the start of new lines when writing // comments - Insert // at the start of new lines when writing // comments + Inserir // no início de novas linhas ao escrever comentários de // @@ -79,7 +79,7 @@ Pattern matching preferences: - Pattern matching preferences: + Preferências de correspondência de padrões: @@ -89,7 +89,7 @@ Prefer implicit object creation when type is apparent - Prefer implicit object creation when type is apparent + Preferir a criação de objeto implícito quando o tipo for aparente @@ -99,12 +99,12 @@ Prefer pattern matching - Prefer pattern matching + Preferir a correspondência de padrões Prefer pattern matching over mixed type check - Prefer pattern matching over mixed type check + Preferir a correspondência de padrões em vez da verificação de tipo misto @@ -124,12 +124,12 @@ Show hints for 'new' expressions - Show hints for 'new' expressions + Mostrar as dicas para as expressões 'new' Show items from unimported namespaces - Mostrar itens de namespaces não importados (experimental) + Mostrar os itens de namespaces não importados diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.ru.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.ru.xlf index 4e4ae15d032ea..188602e635f06 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.ru.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.ru.xlf @@ -2,6 +2,11 @@ + + Add missing using directives on paste + Add missing using directives on paste + 'using' is a C# keyword and should not be localized + Apply all C# formatting rules (indentation, wrapping, spacing) Применять все правила форматирования C# (отступ, перенос по словам, задание интервала) @@ -9,7 +14,7 @@ Automatically show completion list in argument lists (experimental) - Автоматически показывать список завершения в списках аргументов (экспериментальная функция) + Автоматически показывать список завершения в списках аргументов (экспериментальная функция) @@ -34,12 +39,12 @@ Edit color scheme - Edit color scheme + Изменить цветовую схему Format document - Format document + Форматировать документ @@ -52,11 +57,6 @@ Общие Title of the control group on the General Formatting options page - - Generate Event Subscription - Создать подписку на события - - In relational operators: < > <= >= is as == != В реляционных операторах: < > <= >= is as == != @@ -64,7 +64,7 @@ Insert // at the start of new lines when writing // comments - Insert // at the start of new lines when writing // comments + Вставлять "//" в начале новых строк при написании комментариев "//". @@ -79,7 +79,7 @@ Pattern matching preferences: - Pattern matching preferences: + Параметры сопоставления шаблонов: @@ -89,7 +89,7 @@ Prefer implicit object creation when type is apparent - Prefer implicit object creation when type is apparent + Предпочитать неявное создание объекта, когда тип очевиден. @@ -99,12 +99,12 @@ Prefer pattern matching - Prefer pattern matching + Предпочитать соответствие шаблону Prefer pattern matching over mixed type check - Prefer pattern matching over mixed type check + Предпочитать сопоставление шаблонов проверке смешанных типов @@ -124,12 +124,12 @@ Show hints for 'new' expressions - Show hints for 'new' expressions + Отображать подсказки для выражений "new" Show items from unimported namespaces - Показать элементы из неимпортированных пространств имен (экспериментальная функция) + Отображать элементы из неимпортированных пространств имен diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.tr.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.tr.xlf index 7f2e235362856..8c645fee383a5 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.tr.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.tr.xlf @@ -2,6 +2,11 @@ + + Add missing using directives on paste + Add missing using directives on paste + 'using' is a C# keyword and should not be localized + Apply all C# formatting rules (indentation, wrapping, spacing) Tüm C# biçimlendirme kurallarını (girinti, kaydırma, boşluklar) uygula @@ -9,7 +14,7 @@ Automatically show completion list in argument lists (experimental) - Bağımsız değişken listelerinde tamamlama listesini otomatik olarak göster (deneysel) + Bağımsız değişken listelerinde tamamlama listesini otomatik olarak göster (deneysel) @@ -34,12 +39,12 @@ Edit color scheme - Edit color scheme + Renk düzenini düzenle Format document - Format document + Belgeyi biçimlendir @@ -52,11 +57,6 @@ Genel Title of the control group on the General Formatting options page - - Generate Event Subscription - Olay Aboneliği Oluştur - - In relational operators: < > <= >= is as == != İlişkisel işleçleri içinde: <> = < > = == gibi! = @@ -64,7 +64,7 @@ Insert // at the start of new lines when writing // comments - Insert // at the start of new lines when writing // comments + // açıklamaları yazılırken yeni satırların başlangıcına // ekle @@ -79,7 +79,7 @@ Pattern matching preferences: - Pattern matching preferences: + Desen eşleştirme tercihleri: @@ -89,7 +89,7 @@ Prefer implicit object creation when type is apparent - Prefer implicit object creation when type is apparent + Tür görünür olduğunda örtük nesne oluşturmayı tercih et @@ -99,12 +99,12 @@ Prefer pattern matching - Prefer pattern matching + Desen eşleştirmeyi tercih et Prefer pattern matching over mixed type check - Prefer pattern matching over mixed type check + Karışık tür denetimi yerine desen eşleştirmeyi tercih edin @@ -124,12 +124,12 @@ Show hints for 'new' expressions - Show hints for 'new' expressions + 'new' ifadeleri için ipuçlarını göster Show items from unimported namespaces - İçeri aktarılmayan ad alanlarındaki öğeleri göster (deneysel) + İçeri aktarılmayan ad alanlarındaki öğeleri göster diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.zh-Hans.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.zh-Hans.xlf index 5b39d0b3ad730..49ac2e89bb2dd 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.zh-Hans.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.zh-Hans.xlf @@ -1,7 +1,12 @@  - + + + Add missing using directives on paste + Add missing using directives on paste + 'using' is a C# keyword and should not be localized + Apply all C# formatting rules (indentation, wrapping, spacing) 应用所有 C# 格式规则(缩进、换行、间隔) @@ -9,7 +14,7 @@ Automatically show completion list in argument lists (experimental) - 自动显示参数列表中的完成列表(实验性) + 自动显示参数列表中的完成列表(实验性) @@ -34,12 +39,12 @@ Edit color scheme - Edit color scheme + 编辑配色方案 Format document - Format document + 设置文档的格式 @@ -52,11 +57,6 @@ 常规 Title of the control group on the General Formatting options page - - Generate Event Subscription - 生成事件订阅 - - In relational operators: < > <= >= is as == != 在关系运算符中: < > <= >= 等同于 == != @@ -64,7 +64,7 @@ Insert // at the start of new lines when writing // comments - Insert // at the start of new lines when writing // comments + 编写 // 注释时,在新行开头插入 // @@ -79,7 +79,7 @@ Pattern matching preferences: - Pattern matching preferences: + 模式匹配首选项: @@ -89,7 +89,7 @@ Prefer implicit object creation when type is apparent - Prefer implicit object creation when type is apparent + 类型明显时首选隐式对象创建 @@ -104,7 +104,7 @@ Prefer pattern matching over mixed type check - Prefer pattern matching over mixed type check + 首选模式匹配而不是混合类型检查 @@ -124,12 +124,12 @@ Show hints for 'new' expressions - Show hints for 'new' expressions + 显示 "new" 表达式的提示 Show items from unimported namespaces - 显示 unimported 命名空间中的项(实验) + 显示 unimported 命名空间中的项 diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.zh-Hant.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.zh-Hant.xlf index 1423ee23659d4..43b9429afb12e 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.zh-Hant.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.zh-Hant.xlf @@ -1,7 +1,12 @@  - + + + Add missing using directives on paste + Add missing using directives on paste + 'using' is a C# keyword and should not be localized + Apply all C# formatting rules (indentation, wrapping, spacing) 套用所有 C# 格式化規則 (縮排、換行、間距) @@ -9,7 +14,7 @@ Automatically show completion list in argument lists (experimental) - 自動在引數清單中顯示自動完成清單 (實驗性) + 自動在引數清單中顯示自動完成清單 (實驗性) @@ -34,12 +39,12 @@ Edit color scheme - Edit color scheme + 編輯色彩配置 Format document - Format document + 格式化文件 @@ -52,11 +57,6 @@ 一般 Title of the control group on the General Formatting options page - - Generate Event Subscription - 產生事件訂閱 - - In relational operators: < > <= >= is as == != 在關係運算子中: < > <= >= 如同 == != @@ -64,7 +64,7 @@ Insert // at the start of new lines when writing // comments - Insert // at the start of new lines when writing // comments + 撰寫 // 註解時,於新行開頭插入 // @@ -79,7 +79,7 @@ Pattern matching preferences: - Pattern matching preferences: + 模式比對喜好設定: @@ -89,7 +89,7 @@ Prefer implicit object creation when type is apparent - Prefer implicit object creation when type is apparent + 當類型為實際型態時,建議建立隱含物件 @@ -99,12 +99,12 @@ Prefer pattern matching - Prefer pattern matching + 建議使用模式比對 Prefer pattern matching over mixed type check - Prefer pattern matching over mixed type check + 建議使用模式比對而非混合類型檢查 @@ -124,12 +124,12 @@ Show hints for 'new' expressions - Show hints for 'new' expressions + 顯示 'new' 運算式的提示 Show items from unimported namespaces - 顯示來自未匯入命名空間的項目 (實驗性) + 顯示來自未匯入命名空間的項目 @@ -519,7 +519,7 @@ _Insert * at the start of new lines when writing /* */ comments - _在寫入 /* */ 時,於新行開頭插入 *(_I) + 在寫入 /* */ 時,於新行開頭插入 *(_I) diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.cs.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.cs.xlf index 83163b35b7f88..626d86190ab87 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.cs.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.cs.xlf @@ -81,7 +81,7 @@ regex; regular expression; Use enhanced colors; Editor Color Scheme; - Zobrazovat nápovědy k názvům vložených parametrů; + Zobrazovat vložené nápovědy; Zobrazit diagnostiku pro zavřené soubory; Vybarvit regulární výraz; Zvýrazňovat související komponenty pod kurzorem; diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.de.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.de.xlf index 9d0849c20149b..063d5420d9d49 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.de.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.de.xlf @@ -81,54 +81,54 @@ regex; regular expression; Use enhanced colors; Editor Color Scheme; - Display inline hints; -Show diagnostics for closed files; -Colorize regular expression; -Highlight related components under cursor; -Report invalid regular expressions; -Enable full solution analysis; -Perform editor feature analysis in external process; -Enable navigation to decompiled sources; -Using directives; -Place system directives first when sorting usings; -Separate using directive groups; -Suggest usings for types in reference assemblies; -Suggest usings for types in NuGet packages; -Highlighting; -Highlight references to symbol under cursor; -Highlight related keywords under cursor; -Outlining; -Enter outlining mode when files open; -Show procedure line separators; -Show outlining for declaration level constructs; -Show outlining for code level constructs; -Show outlining for comments and preprocessor regions; -Collapse regions when collapsing to definitions; -Fading; -Fade out unused usings; -Fade out unreachable code; -Block Structure Guides; -Show guides for declaration level constructs; -Show guides for code level constructs; -Editor Help; -Generate XML documentation comments for ///; -Insert * at the start of new lines when writing /* */ comments; -Show preview for rename tracking; -Split string literals on Enter; -Report invalid placeholders in string.Format calls; -Extract Method; -Don't put ref or out on custom struct; -Implement Interface or Abstract Class; -When inserting properties, events and methods, place them; -with other members of the same kind; -at the end; -When generating property; -prefer throwing properties; -prefer auto properties; + Inlinehinweise anzeigen; +Diagnoseinformationen für geschlossene Dateien anzeigen; +Reguläre Ausdrücke farbig hervorheben; +Zugehörige Komponenten unter dem Cursor markieren; +Ungültige reguläre Ausdrücke melden; +Vollständige Lösungsanalyse aktivieren; +Editor-Funktionsanalyse in externem Prozess ausführen ; +Navigation zu dekompilierten Quellen aktivieren; +using-Anweisungen; +Systemanweisungen beim Sortieren von using-Anweisungen an erster Stelle platzieren; +Gruppen von using-Anweisungen trennen; +using-Anweisungen für Typen in Verweisassemblys vorschlagen; +using-Anweisungen für Typen in NuGet-Paketen vorschlagen; +Hervorhebung; +Verweise auf Symbol unter Cursor hervorheben; +Verwandte Schlüsselbegriffe unter Cursor anzeigen; +Gliederung; +Gliederungsmodus beim Öffnen von Dateien starten; +Zeilentrennzeichen in Prozeduren anzeigen; +Gliederung für Konstrukte auf Deklarationsebene anzeigen; +Gliederung für Konstrukte auf Codeebene anzeigen; +Gliederung für Kommentare und Präprozessorregionen anzeigen; +Regionen beim Reduzieren auf Definitionen zuklappen; +Ausblenden; +Nicht verwendete using-Anweisungen ausblenden; +Unerreichbaren Code ausblenden; +Führungslinien für Struktur blockieren; +Führungslinien für Konstrukte auf Deklarationsebene anzeigen; +Führungslinien für Konstrukte auf Codeebene anzeigen; +Editor-Hilfe; +XML-Dokumentationskommentare für /// generieren; +Beim Schreiben von Kommentaren (/* */) * am Beginn neuer Zeilen einfügen; +Vorschau für Nachverfolgung beim Umbenennen anzeigen; +Zeichenfolgenliterale bei Eingabe teilen; +Ungültige Platzhalter in string.Format-Aufrufen melden; +Methode extrahieren; +ref oder out nicht in benutzerdefinierte Struktur platzieren; +Schnittstellen- oder abstrakte Klasse implementieren; +Eigenschaften, Ereignisse und Methoden beim Einfügen; +bei anderen Membern derselben Art platzieren; +am Ende platzieren; +Beim Generieren von Eigenschaften; +ausgelöste Eigenschaften bevorzugen; +automatische Eigenschaften bevorzugen; regex; -regular expression; -Use enhanced colors; -Editor Color Scheme; +regulärer Ausdruck; +Erweiterte Farben verwenden; +Editor-Farbschema; C# Advanced options page keywords diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.es.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.es.xlf index e6ea6e5edbd9a..5632620d9cf34 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.es.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.es.xlf @@ -81,54 +81,54 @@ regex; regular expression; Use enhanced colors; Editor Color Scheme; - Display inline hints; -Show diagnostics for closed files; -Colorize regular expression; -Highlight related components under cursor; -Report invalid regular expressions; -Enable full solution analysis; -Perform editor feature analysis in external process; -Enable navigation to decompiled sources; -Using directives; -Place system directives first when sorting usings; -Separate using directive groups; -Suggest usings for types in reference assemblies; -Suggest usings for types in NuGet packages; -Highlighting; -Highlight references to symbol under cursor; -Highlight related keywords under cursor; -Outlining; -Enter outlining mode when files open; -Show procedure line separators; -Show outlining for declaration level constructs; -Show outlining for code level constructs; -Show outlining for comments and preprocessor regions; -Collapse regions when collapsing to definitions; -Fading; -Fade out unused usings; -Fade out unreachable code; -Block Structure Guides; -Show guides for declaration level constructs; -Show guides for code level constructs; -Editor Help; -Generate XML documentation comments for ///; -Insert * at the start of new lines when writing /* */ comments; -Show preview for rename tracking; -Split string literals on Enter; -Report invalid placeholders in string.Format calls; -Extract Method; -Don't put ref or out on custom struct; -Implement Interface or Abstract Class; -When inserting properties, events and methods, place them; -with other members of the same kind; -at the end; -When generating property; -prefer throwing properties; -prefer auto properties; + Mostrar sugerencias insertadas; +Mostrar diagnóstico para archivos cerrados; +Colorear expresión regular; +Resaltar componentes relacionados bajo el cursor; +Informar sobre expresiones regulares no válidas; +Habilitar análisis de la solución completa; +Realizar el análisis de características del editor en proceso externo; +Habilitar la navegación a orígenes descompilados; +Directivas Using; +Poner directivas del sistema primero cuando se organicen instrucciones Using; +Separar grupos de directivas using; +Sugerir directivas using para los tipos en los ensamblados de referencia; +Sugerir directivas using para los tipos en los paquetes NuGet; +Resaltar; +Resaltar referencias al símbolo bajo el cursor; +Resaltar palabras clave relacionadas bajo el cursor; +Esquematización; +Especificar el modo de esquematización al abrir los archivos; +Mostrar separadores de líneas de procedimientos; +Mostrar esquematización para construcciones a nivel de declaración; +Mostrar esquematización para construcciones a nivel de código; +Mostrar esquematización para regiones de preprocesador y comentarios; +Contraer regiones cuando se contraiga a las definiciones; +Atenuación; +Atenuar directivas using no usadas; +Atenuar código inaccesible; +Guías de estructura de bloque; +Mostrar guías para construcciones a nivel de declaración; +Mostrar guías para construcciones a nivel de código; +Ayuda del editor; +Generar comentarios de documentación XML para ///; +Insertar * al comienzo de las nuevas líneas al escribir comentarios /* */; +Mostrar vista previa para seguimiento de cambio de nombre; +Dividir literales de cadena al presionar Entrar; +Informar sobre marcadores de posición no válidos en llamadas a string.Format; +Extraer método; +No colocar "out" o "ref" en estructura personalizada; +Implementar interfaz o clase abstracta; +Al insertar propiedades, eventos y métodos, colóquelos; +con otros miembros de la misma clase; +al final; +Al generar una propiedad; +preferir propiedades de lanzamiento; +preferir propiedades automáticas; regex; -regular expression; -Use enhanced colors; -Editor Color Scheme; +expresión regular; +Usar colores mejorados; +Combinación de colores del editor; C# Advanced options page keywords diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.fr.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.fr.xlf index 8c5d2a7686a42..2e234183d395e 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.fr.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.fr.xlf @@ -81,54 +81,54 @@ regex; regular expression; Use enhanced colors; Editor Color Scheme; - Display inline hints; -Show diagnostics for closed files; -Colorize regular expression; -Highlight related components under cursor; -Report invalid regular expressions; -Enable full solution analysis; -Perform editor feature analysis in external process; -Enable navigation to decompiled sources; -Using directives; -Place system directives first when sorting usings; -Separate using directive groups; -Suggest usings for types in reference assemblies; -Suggest usings for types in NuGet packages; -Highlighting; -Highlight references to symbol under cursor; -Highlight related keywords under cursor; -Outlining; -Enter outlining mode when files open; -Show procedure line separators; -Show outlining for declaration level constructs; -Show outlining for code level constructs; -Show outlining for comments and preprocessor regions; -Collapse regions when collapsing to definitions; -Fading; -Fade out unused usings; -Fade out unreachable code; -Block Structure Guides; -Show guides for declaration level constructs; -Show guides for code level constructs; -Editor Help; -Generate XML documentation comments for ///; -Insert * at the start of new lines when writing /* */ comments; -Show preview for rename tracking; -Split string literals on Enter; -Report invalid placeholders in string.Format calls; -Extract Method; -Don't put ref or out on custom struct; -Implement Interface or Abstract Class; -When inserting properties, events and methods, place them; -with other members of the same kind; -at the end; -When generating property; -prefer throwing properties; -prefer auto properties; -regex; -regular expression; -Use enhanced colors; -Editor Color Scheme; + Afficher les indicateurs inline ; +Afficher les diagnostics pour les fichiers fermés ; +Mettre en couleurs l'expression régulière ; +Surligner les composants liés sous le curseur ; +Signaler les expressions régulières non valides ; +Activer l'analyse complète de la solution ; +Effectuer l'analyse des fonctionnalités de l'éditeur dans un processus externe ; +Activer la navigation vers les sources décompilées ; +Directives using ; +Placer en premier les directives system au moment du tri des using ; +Séparer les groupes de directives using ; +Suggérer des using pour les types dans les assemblys de référence ; +Suggérer des using pour les types dans les packages NuGet ; +Mise en surbrillance ; +Mettre en surbrillance les références au symbole sous le curseur ; +Mettre en surbrillance les mots clés liés sous le curseur ; +Mode Plan ; +Passer en mode Plan à l'ouverture des fichiers ; +Afficher les séparateurs de ligne de procédure ; +Afficher le mode Plan pour les constructions au niveau des déclarations ; +Afficher le mode Plan pour les constructions au niveau du code ; +Afficher le mode Plan pour les commentaires et les régions du préprocesseur ; +Réduire les régions au moment de la réduction aux définitions ; +Atténuation ; +Atténuer les using inutilisés ; +Atténuer le code inaccessible ; +Repères de structure de bloc ; +Afficher les repères pour les constructions au niveau des déclarations ; +Afficher les repères pour les constructions au niveau du code ; +Aide de l'éditeur ; +Générer des commentaires de documentation XML pour /// ; +Insérer * au début des nouvelles lignes pour l'écriture de commentaires /* */ ; +Afficher un aperçu pour le suivi des renommages ; +Diviser les littéraux de chaîne avec Entrée ; +Signaler les espaces réservés non valides dans les appels de string.Format ; +Extraire la méthode ; +Ne pas placer ref ou out dans un struct personnalisé ; +Implémenter une interface ou une classe abstraite ; +Au moment d'insérer des propriétés, des événements et des méthodes, les placer ; +avec d'autres membres du même genre ; +à la fin ; +Durant la génération de propriétés ; +préférer les propriétés de levée d'exceptions ; +préférer les propriétés automatiques ; +regex ; +expression régulière ; +Utiliser des couleurs améliorées ; +Modèle de couleurs de l'éditeur ; C# Advanced options page keywords diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.it.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.it.xlf index 37870cd22824e..c304cde5e99dd 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.it.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.it.xlf @@ -81,54 +81,54 @@ regex; regular expression; Use enhanced colors; Editor Color Scheme; - Display inline hints; -Show diagnostics for closed files; -Colorize regular expression; -Highlight related components under cursor; -Report invalid regular expressions; -Enable full solution analysis; -Perform editor feature analysis in external process; -Enable navigation to decompiled sources; -Using directives; -Place system directives first when sorting usings; -Separate using directive groups; -Suggest usings for types in reference assemblies; -Suggest usings for types in NuGet packages; -Highlighting; -Highlight references to symbol under cursor; -Highlight related keywords under cursor; -Outlining; -Enter outlining mode when files open; -Show procedure line separators; -Show outlining for declaration level constructs; -Show outlining for code level constructs; -Show outlining for comments and preprocessor regions; -Collapse regions when collapsing to definitions; -Fading; -Fade out unused usings; -Fade out unreachable code; -Block Structure Guides; -Show guides for declaration level constructs; -Show guides for code level constructs; -Editor Help; -Generate XML documentation comments for ///; -Insert * at the start of new lines when writing /* */ comments; -Show preview for rename tracking; -Split string literals on Enter; -Report invalid placeholders in string.Format calls; -Extract Method; -Don't put ref or out on custom struct; -Implement Interface or Abstract Class; -When inserting properties, events and methods, place them; -with other members of the same kind; -at the end; -When generating property; -prefer throwing properties; -prefer auto properties; + Visualizza suggerimenti inline; +Mostra diagnostica per file chiusi; +Colora espressione regolare; +Evidenzia i componenti correlati sotto il cursore; +Segnala espressioni regolari non valide; +Abilita analisi della soluzione completa; +Esegui analisi delle funzionalità dell'editor in processo esterno; +Abilita spostamento a origini decompilate; +Direttive using; +Inserisci prima le direttive System durante l'ordinamento delle direttive using; +Separa gruppi di direttive using; +Suggerisci le direttive using per i tipi in assembly di riferimento; +Suggerisci le direttive using per i tipi in pacchetti NuGet; +Evidenziazione; +Evidenzia riferimenti a simbolo sotto il cursore; +Evidenzia parole chiave correlate sotto il cursore; +Struttura; +Attiva modalità struttura all'apertura del file; +Mostra separatori di riga routine; +Mostra la struttura per i costrutti a livello di dichiarazione; +Mostra la struttura per i costrutti a livello di codice; +Mostra la struttura per i commenti e le aree del preprocessore; +Comprimi regions durante la compressione delle definizioni; +Dissolvenza; +Applica dissolvenza a direttive using non usate; +Applica dissolvenza a codice non eseguibile; +Guide per strutture a blocchi; +Mostra le guide per i costrutti a livello di dichiarazione; +Mostra le guide per i costrutti a livello di codice; +Guida dell'editor; +Genera commenti relativi alla documentazione XML per ///; +Inserisci * all'inizio di nuove righe quando si scrivono commenti /* */; +Mostra anteprima per verifica ridenominazione; +Dividi valori letterali stringa dopo INVIO; +Segnala segnaposto non validi in chiamate string.Format; +Estrai metodo; +Non inserire out o ref in struct personalizzato; +Implementa interfaccia o classe astratta; +Posiziona proprietà, eventi e metodi inseriti; +con altri membri dello stesso tipo; +alla fine; +Durante la generazione della proprietà; +preferisci proprietà generate; +preferisci proprietà automatiche; regex; -regular expression; -Use enhanced colors; -Editor Color Scheme; +espressione regolare; +Usa colori migliorati; +Combinazione colori editor; C# Advanced options page keywords diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.ja.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.ja.xlf index 7d6a85e7ada9f..0dcfd97e5707c 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.ja.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.ja.xlf @@ -81,54 +81,54 @@ regex; regular expression; Use enhanced colors; Editor Color Scheme; - Display inline hints; -Show diagnostics for closed files; -Colorize regular expression; -Highlight related components under cursor; -Report invalid regular expressions; -Enable full solution analysis; -Perform editor feature analysis in external process; -Enable navigation to decompiled sources; -Using directives; -Place system directives first when sorting usings; -Separate using directive groups; -Suggest usings for types in reference assemblies; -Suggest usings for types in NuGet packages; -Highlighting; -Highlight references to symbol under cursor; -Highlight related keywords under cursor; -Outlining; -Enter outlining mode when files open; -Show procedure line separators; -Show outlining for declaration level constructs; -Show outlining for code level constructs; -Show outlining for comments and preprocessor regions; -Collapse regions when collapsing to definitions; -Fading; -Fade out unused usings; -Fade out unreachable code; -Block Structure Guides; -Show guides for declaration level constructs; -Show guides for code level constructs; -Editor Help; -Generate XML documentation comments for ///; -Insert * at the start of new lines when writing /* */ comments; -Show preview for rename tracking; -Split string literals on Enter; -Report invalid placeholders in string.Format calls; -Extract Method; -Don't put ref or out on custom struct; -Implement Interface or Abstract Class; -When inserting properties, events and methods, place them; -with other members of the same kind; -at the end; -When generating property; -prefer throwing properties; -prefer auto properties; -regex; -regular expression; -Use enhanced colors; -Editor Color Scheme; + インラインのヒントを表示する; +閉じているファイルの診断結果を表示する; +正規表現をカラー化する; +カーソルの下にある関連コンポーネントを強調表示する; +無効な正規表現を報告する; +完全ソリューション解析を有効にする; +外部プロセスでエディター機能解析を実行する; +逆コンパイルされたソースへのナビゲーションを有効にする; +ディレクティブを使用する; +using を並べ替える際に、system ディレクティブを先頭に配置する; +using ディレクティブ グループを分離する; +参照アセンブリの型に using を提案する; +NuGet パッケージの型に using を提案する; +強調表示; +カーソルの下にあるシンボルへの参照を強調表示する; +カーソルの下にある関連キーワードを強調表示する; +アウトライン; +ファイルを開くときにアウトライン モードに入る; +プロシージャ行の区切り記号を表示する; +宣言レベルのコンストラクトのアウトラインを表示する; +コード レベルのコンストラクトのアウトラインを表示する; +コメントとプリプロセッサ領域のアウトラインを表示する; +定義を折りたたむときに regions を折りたたむ; +フェード; +未使用の using をフェードアウトする; +到達できないコードをフェードアウトする; +ブロック構造のガイド; +宣言レベルのコンストラクトのガイドを表示する; +コード レベルのコンストラクトのガイドを表示する; +エディターのヘルプ; +/// が入力されたとき、XML ドキュメント コメントを生成する; +/* */ コメントを記述する際、新しい行の先頭に * を挿入する; +名前変更追跡のプレビューを表示する; +Enter で文字列リテラルを分割する; +string.Format の呼び出しで無効なプレースホルダーをレポートする; +メソッドを抽出する; +カスタム構造体に ref または out を設定しない; +インターフェイスまたは抽象クラスを実装する; +プロパティ、イベント、メソッドを挿入する際には、次の場所に挿入する; +同じ種類の他のメンバーと共に; +末尾; +プロパティの生成時; +スロー プロパティを優先する; +自動プロパティを優先する; +正規表現; +正規表現; +拡張された色を使用する; +エディターの配色; C# Advanced options page keywords diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.ko.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.ko.xlf index 6cc8a8443bfa1..ba1cfb69cf73b 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.ko.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.ko.xlf @@ -81,54 +81,54 @@ regex; regular expression; Use enhanced colors; Editor Color Scheme; - Display inline hints; -Show diagnostics for closed files; -Colorize regular expression; -Highlight related components under cursor; -Report invalid regular expressions; -Enable full solution analysis; -Perform editor feature analysis in external process; -Enable navigation to decompiled sources; -Using directives; -Place system directives first when sorting usings; -Separate using directive groups; -Suggest usings for types in reference assemblies; -Suggest usings for types in NuGet packages; -Highlighting; -Highlight references to symbol under cursor; -Highlight related keywords under cursor; -Outlining; -Enter outlining mode when files open; -Show procedure line separators; -Show outlining for declaration level constructs; -Show outlining for code level constructs; -Show outlining for comments and preprocessor regions; -Collapse regions when collapsing to definitions; -Fading; -Fade out unused usings; -Fade out unreachable code; -Block Structure Guides; -Show guides for declaration level constructs; -Show guides for code level constructs; -Editor Help; -Generate XML documentation comments for ///; -Insert * at the start of new lines when writing /* */ comments; -Show preview for rename tracking; -Split string literals on Enter; -Report invalid placeholders in string.Format calls; -Extract Method; -Don't put ref or out on custom struct; -Implement Interface or Abstract Class; -When inserting properties, events and methods, place them; -with other members of the same kind; -at the end; -When generating property; -prefer throwing properties; -prefer auto properties; -regex; -regular expression; -Use enhanced colors; -Editor Color Scheme; + 인라인 힌트 표시, +닫힌 파일에 대한 진단 표시, +정규식 색 지정, +커서 아래의 관련 구성 요소 강조 표시, +잘못된 정규식 보고, +전체 솔루션 분석 사용, +외부기 프로세스에서 편집기 기능 분석 수행, +디컴파일된 소스 탐색 사용, +Using 지시문, +nusing 정렬 시 system 지시문 먼저 배치, +nusing 지시문 그룹 구분, +참조 어셈블리의 형식에 using 제안, +NuGet 패키지의 형식에 using 제안, +강조 표시, +커서 아래의 기호에 대한 참조 강조 표시, +커서 아래의 관련 키워드 강조 표시, +개요, +개요 모드로 파일 열기, +프로시저 줄 구분선 표시, +선언 수준 구문에 대한 개요 표시, +코드 수준 구문에 대한 개요 표시, +설명 및 전처리기 영역에 대한 개요 표시, +정의로 축소할 때 영역 축소, +페이딩, +사용하지 않는 using 페이드 아웃, +접근할 수 없는 코드 페이드 아웃, +블록 구조 가이드, +선언 수준 구조에 대한 가이드 표시, +코드 수준 구조에 대한 가이드 표시, +편집기 도움말, +///에 대해 XML 문서 주석 생성, +/* */ 주석을 작성할 때 새 줄의 시작 부분에 * 삽입, +이름 바꾸기 추적 미리 보기 표시, +&lt;Enter&gt; 키를 누르면 문자열 리터럴 분할, +string.Format 호출에서 잘못된 자리 표시자 보고, +메서드 추출, +사용자 지정 구조체에 ref 또는 out 추가 안 함, +인터페이스 또는 추상 클래스 구현, +속성, 이벤트 및 메서드 삽입 시 다음과 같이 배치, +같은 종류의 다른 멤버와 함께, +끝에, +속성 생성 시, +throw되는 속성 선호, +자동 속성 선호, +regex, +정규식, +향상된 색 사용, +편집기 색 구성표, C# Advanced options page keywords diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.pl.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.pl.xlf index 4ec9e1473f742..c2184146cfb5f 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.pl.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.pl.xlf @@ -81,54 +81,54 @@ regex; regular expression; Use enhanced colors; Editor Color Scheme; - Display inline hints; -Show diagnostics for closed files; -Colorize regular expression; -Highlight related components under cursor; -Report invalid regular expressions; -Enable full solution analysis; -Perform editor feature analysis in external process; -Enable navigation to decompiled sources; -Using directives; -Place system directives first when sorting usings; -Separate using directive groups; -Suggest usings for types in reference assemblies; -Suggest usings for types in NuGet packages; -Highlighting; -Highlight references to symbol under cursor; -Highlight related keywords under cursor; -Outlining; -Enter outlining mode when files open; -Show procedure line separators; -Show outlining for declaration level constructs; -Show outlining for code level constructs; -Show outlining for comments and preprocessor regions; -Collapse regions when collapsing to definitions; -Fading; -Fade out unused usings; -Fade out unreachable code; -Block Structure Guides; -Show guides for declaration level constructs; -Show guides for code level constructs; -Editor Help; -Generate XML documentation comments for ///; -Insert * at the start of new lines when writing /* */ comments; -Show preview for rename tracking; -Split string literals on Enter; -Report invalid placeholders in string.Format calls; -Extract Method; -Don't put ref or out on custom struct; -Implement Interface or Abstract Class; -When inserting properties, events and methods, place them; -with other members of the same kind; -at the end; -When generating property; -prefer throwing properties; -prefer auto properties; -regex; -regular expression; -Use enhanced colors; -Editor Color Scheme; + Wyświetlaj wskazówki w tekście; +Pokaż dane diagnostyczne dla zamkniętych plików; +Koloruj wyrażenia regularne; +Wyróżnij powiązane składniki pod kursorem; +Raportuj nieprawidłowe wyrażenia regularne; +Włącz pełną analizę rozwiązania; +Wykonaj analizę funkcji edytora w procesie zewnętrznym; +Włącz nawigowanie do dekompilowanych źródeł; +Dyrektywy using; +Umieść najpierw dyrektywy system podczas sortowania deklaracji using; +Oddziel grupy dyrektywy using; +Sugeruj dyrektywy using dla typów w zestawach odwołania; +Sugeruj dyrektywy using dla typów w pakietach NuGet; +Wyróżnianie; +Wyróżnij odwołania do symbolu pod kursorem; +Wyróżnij pokrewne słowa kluczowe pod kursorem; +Konspekt; +Przejdź do trybu konspektu przy otwieraniu plików; +Pokaż separatory wierszy procedury; +Pokaż konspekt dla konstrukcji na poziomie deklaracji; +Pokaż konspekt dla konstrukcji na poziomie kodu; +Pokaż konspekt dla regionów komentarzy i preprocesora; +Zwiń regiony podczas zwijania do definicji; +Zanikanie; +Zanikanie nieużywanych dyrektyw using; +Zanikanie nieosiągalnego kodu; +Prowadnice struktury blokowej; +Pokaż prowadnice dla konstrukcji na poziomie deklaracji; +Pokaż prowadnice dla konstrukcji na poziomie kodu; +Pomoc edytora; +Generuj komentarze dokumentacji XML dla elementów ///; +Wstaw znak * na początku nowych wierszy podczas pisania komentarzy typu /* */; +Pokaż podgląd śledzenia zmian nazw; +Dziel literały ciągów po naciśnięciu klawisza Enter; +Zgłaszaj nieprawidłowe symbole zastępcze w wywołaniach metody string.Format; +Wyodrębnianie metody; +Nie umieszczaj parametrów ref i out w strukturze niestandardowej; +Implementuj interfejs lub klasę abstrakcyjną; +W przypadku wstawiania właściwości, zdarzeń i metod umieszczaj je; +razem z innymi składowymi tego samego rodzaju; +na końcu; +Podczas generowania właściwości; +preferuj zgłaszanie właściwości; +preferuj właściwości automatyczne; +wyrażenie regularne; +wyrażenie regularne; +Użyj ulepszonych kolorów; +Schemat kolorów edytora; C# Advanced options page keywords @@ -292,7 +292,7 @@ Show items from unimported namespaces (experimental); Zmień ustawienia listy uzupełniania;Wybierz wstępnie ostatnio używaną składową; Listy uzupełniania; Pokaż listę uzupełniania po wpisaniu znaku; Pokaż listę uzupełniania po usunięciu znaku; -Automatycznie pokazuj listę uzupełniania na liście argumentów (wersja eksperymentalna); +Automatycznie pokazuj listę uzupełniania na liście argumentów (funkcja eksperymentalna); Wyróżnij pasujące fragmenty elementów listy uzupełniania; Pokaż filtry elementów uzupełniania; Zachowanie fragmentów kodu; @@ -303,7 +303,8 @@ Zachowanie klawisza Enter; Nigdy nie dodawaj nowego wiersza po naciśnięciu klawisza Enter; Dodaj nowy wiersz po naciśnięciu klawisza Enter tylko po zakończeniu pełnego wpisanego wyrazu; Zawsze dodawaj nowy wiersz po naciśnięciu klawisza Enter; -Pokaż sugestie dotyczące nazwy; +Pokaż sugestie dotyczące nazwy; +Pokaż elementy z niezaimportowanych przestrzeni nazw (funkcja eksperymentalna); C# IntelliSense options page keywords diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.pt-BR.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.pt-BR.xlf index ef6768e3c6900..36ef3f1776f4c 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.pt-BR.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.pt-BR.xlf @@ -81,54 +81,54 @@ regex; regular expression; Use enhanced colors; Editor Color Scheme; - Display inline hints; -Show diagnostics for closed files; -Colorize regular expression; -Highlight related components under cursor; -Report invalid regular expressions; -Enable full solution analysis; -Perform editor feature analysis in external process; -Enable navigation to decompiled sources; -Using directives; -Place system directives first when sorting usings; -Separate using directive groups; -Suggest usings for types in reference assemblies; -Suggest usings for types in NuGet packages; -Highlighting; -Highlight references to symbol under cursor; -Highlight related keywords under cursor; -Outlining; -Enter outlining mode when files open; -Show procedure line separators; -Show outlining for declaration level constructs; -Show outlining for code level constructs; -Show outlining for comments and preprocessor regions; -Collapse regions when collapsing to definitions; -Fading; -Fade out unused usings; -Fade out unreachable code; -Block Structure Guides; -Show guides for declaration level constructs; -Show guides for code level constructs; -Editor Help; -Generate XML documentation comments for ///; -Insert * at the start of new lines when writing /* */ comments; -Show preview for rename tracking; -Split string literals on Enter; -Report invalid placeholders in string.Format calls; -Extract Method; -Don't put ref or out on custom struct; -Implement Interface or Abstract Class; -When inserting properties, events and methods, place them; -with other members of the same kind; -at the end; -When generating property; -prefer throwing properties; -prefer auto properties; + Exibir as dicas embutidas; +Mostrar os diagnósticos de arquivos fechados; +Colorir a expressão regular; +Realçar os componentes relacionados sob o cursor; +Relatar as expressões regulares inválidas; +Habilitar a análise completa da solução; +Executar a análise de recurso do editor em processo externo; +Habilitar a navegação para fontes decompiladas; +Diretivas using; +Colocar as diretivas do sistema primeiro ao classificar usings; +Separar grupos de diretivas using; +Sugerir usings para tipos em assemblies de referência; +Sugerir usings para tipos em pacotes NuGet; +Realce; +Realçar as referências ao símbolo sob o cursor; +Realçar as palavras-chave relacionadas sob o cursor; +Estrutura de tópicos; +Entrar no modo de estrutura de tópicos quando os arquivos são abertos; +Mostrar separadores de linha de procedimento; +Mostrar a estrutura de tópicos para constructos no nível da declaração; +Mostrar a estrutura de tópicos para constructos no nível do código; +Mostrar a estrutura de tópicos para comentários e regiões de pré-processador; +Recolher as regiões ao recolher as definições; +Esmaecimento; +Esmaecer as usings não usadas; +Esmaecer o código inacessível; +Bloquear as Guias de Estrutura; +Mostrar as guias de constructos no nível da declaração; +Mostrar as guias de constructos no nível do código; +Ajuda do Editor; +Gerar comentários da documentação XML para ///; +Inserir * no início de novas linhas ao escrever comentários de /* */; +Mostrar a visualização para acompanhamento de renomeação; +Dividir os literais de cadeia de caracteres ao pressionar Enter; +Relatar os espaços reservados inválidos nas chamadas a string.Format; +Extrair o Método; +Não colocar ref nem out no struct personalizado; +Implementar a Classe de Interface ou Abstrata; +Ao inserir propriedades, eventos e métodos, colocá-los; +com outros membros do mesmo tipo; +no fim; +Ao gerar uma propriedade; +preferir propriedades de lançamento; +preferir propriedades automáticas; regex; -regular expression; -Use enhanced colors; -Editor Color Scheme; +expressão regular; +Usar cores avançadas; +Esquema de Cores do Editor; C# Advanced options page keywords diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.ru.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.ru.xlf index c4e1d0e8930b3..88e61474f346a 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.ru.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.ru.xlf @@ -81,54 +81,54 @@ regex; regular expression; Use enhanced colors; Editor Color Scheme; - Display inline hints; -Show diagnostics for closed files; -Colorize regular expression; -Highlight related components under cursor; -Report invalid regular expressions; -Enable full solution analysis; -Perform editor feature analysis in external process; -Enable navigation to decompiled sources; -Using directives; -Place system directives first when sorting usings; -Separate using directive groups; -Suggest usings for types in reference assemblies; -Suggest usings for types in NuGet packages; -Highlighting; -Highlight references to symbol under cursor; -Highlight related keywords under cursor; -Outlining; -Enter outlining mode when files open; -Show procedure line separators; -Show outlining for declaration level constructs; -Show outlining for code level constructs; -Show outlining for comments and preprocessor regions; -Collapse regions when collapsing to definitions; -Fading; -Fade out unused usings; -Fade out unreachable code; -Block Structure Guides; -Show guides for declaration level constructs; -Show guides for code level constructs; -Editor Help; -Generate XML documentation comments for ///; -Insert * at the start of new lines when writing /* */ comments; -Show preview for rename tracking; -Split string literals on Enter; -Report invalid placeholders in string.Format calls; -Extract Method; -Don't put ref or out on custom struct; -Implement Interface or Abstract Class; -When inserting properties, events and methods, place them; -with other members of the same kind; -at the end; -When generating property; -prefer throwing properties; -prefer auto properties; -regex; -regular expression; -Use enhanced colors; -Editor Color Scheme; + Отображать встроенные подсказки; +Отображать диагностику для закрытых файлов; +Выделять регулярные выражения цветом; +Выделять связанные компоненты под курсором; +Сообщать о недопустимых регулярных выражениях; +Включить полный анализ решения; +Выполнять анализ функций редактора во внешнем процессе; +Включить переход к декомпилированным источникам; +Директивы using; +Располагать директивы system первыми при сортировке using; +Разделять группы директив using; +Предлагать директивы using для типов в базовых сборках; +Предлагать директивы using для типов в пакетах NuGet; +Выделение; +Выделять ссылки на символ под курсором; +Выделить связанные ключевые слова под курсором; +Структурирование; +Включать режим редактирования структуры при открытии файлов; +Показывать разделители строк процедур; +Показывать структуру для конструкций уровня объявления; +Показывать структуру для конструкций уровня кода; +Показывать структуру для комментариев и областей препроцессора; +Сворачивать области при сворачивании в определения; +Скрытие; +Скрывать неиспользуемые директивы using; +Скрывать недостижимый код; +Направляющие для структуры блоков; +Показывать направляющие для конструкций уровня объявления; +Показывать направляющие для конструкций уровня кода; +Справка по редактору; +Создавать комментарии XML-документации для ///; +Вставлять "*" в начале новой строки при написании комментариев "/* */"; +Отображать предварительный просмотр для отслеживания переименований; +Разделять строковые литералы при нажатии клавиши ВВОД; +Сообщать о недопустимых заполнителях в вызовах string.Format; +Извлечение метода; +Не помещать ref или out в настраиваемую структуру; +Реализовать интерфейс или абстрактный класс; +При вставке свойств, методов и событий помещать их; +вместе с другими элементами того же типа; +в конец; +При создании свойства; +предпочитать свойства, создающие исключения; +предпочитать автоматические свойства; +регулярное выражение; +регулярное выражение; +Использовать расширенные цвета; +Цветовая схема редактора; C# Advanced options page keywords diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.tr.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.tr.xlf index 98f51608bf14b..4dccdb36766ad 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.tr.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.tr.xlf @@ -81,54 +81,54 @@ regex; regular expression; Use enhanced colors; Editor Color Scheme; - Display inline hints; -Show diagnostics for closed files; -Colorize regular expression; -Highlight related components under cursor; -Report invalid regular expressions; -Enable full solution analysis; -Perform editor feature analysis in external process; -Enable navigation to decompiled sources; -Using directives; -Place system directives first when sorting usings; -Separate using directive groups; -Suggest usings for types in reference assemblies; -Suggest usings for types in NuGet packages; -Highlighting; -Highlight references to symbol under cursor; -Highlight related keywords under cursor; -Outlining; -Enter outlining mode when files open; -Show procedure line separators; -Show outlining for declaration level constructs; -Show outlining for code level constructs; -Show outlining for comments and preprocessor regions; -Collapse regions when collapsing to definitions; -Fading; -Fade out unused usings; -Fade out unreachable code; -Block Structure Guides; -Show guides for declaration level constructs; -Show guides for code level constructs; -Editor Help; -Generate XML documentation comments for ///; -Insert * at the start of new lines when writing /* */ comments; -Show preview for rename tracking; -Split string literals on Enter; -Report invalid placeholders in string.Format calls; -Extract Method; -Don't put ref or out on custom struct; -Implement Interface or Abstract Class; -When inserting properties, events and methods, place them; -with other members of the same kind; -at the end; -When generating property; -prefer throwing properties; -prefer auto properties; -regex; -regular expression; -Use enhanced colors; -Editor Color Scheme; + Satır içi ipuçlarını göster; +Kapatılan dosyalara ilişkin tanılamaları göster; +Normal ifadeyi renklendir; +İmlecin altındaki ilgili bileşenleri vurgula; +Geçersiz normal ifadeleri bildir; +Tam çözüm analizini etkinleştir; +Dış işlemde düzenleyici özellik analizi gerçekleştir; +Kaynak koda dönüştürülen kaynaklar için gezintiyi etkinleştir; +Using yönergeleri; +Using yönergelerini sıralarken sistem yönergelerini en başa yerleştir; +Using yönerge gruplarını ayır; +Başvuru bütünleştirilmiş kodlarında türler için using yönergeleri öner; +NuGet paketlerinde türler için using yönergeleri öner; +Vurgulama; +İmlecin altındaki sembole yönelik başvuruları vurgula; +İmlecin altındaki ilgili anahtar sözcükleri vurgula; +Ana Hat Oluşturma; +Dosyalar açılırken ana hat oluşturma moduna gir; +Yordam satır ayırıcılarını göster; +Bildirim düzeyinde yapılar için ana hattı göster; +Kod düzeyinde yapılar için ana hattı göster; +Açıklamalar ve ön işlemci bölgeleri için ana hattı göster; +Tanımlara daraltırken bölgeleri daralt; +Soluklaştırma; +Kullanılmayan using deyimlerini soluklaştır; +Erişilemeyen kodu soluklaştır; +Blok Yapısı Kılavuzları; +Bildirim düzeyinde yapılar için kılavuzları göster; +Kod düzeyinde yapılar için kılavuzları göster; +Düzenleyici Yardımı; +/// için XML belge açıklamaları oluştur; +/* */ açıklamaları yazılırken her yeni satırın başına * ekle; +Yeniden adlandırma izlemesi için önizleme göster; +Enter tuşuna basıldığında dize sabit değerlerini böl; +string.Format çağrılarındaki geçersiz yer tutucuları bildir; +Ayıklama Metodu; +Özel yapıya ref veya out koyma; +Arabirim veya Soyut Sınıfı uygula; +Özellik, olay ve metot eklerken bunları; +aynı türdeki başka üyelerle birlikte; +sona yerleştir; +Özellik oluştururken; +özel durum oluşturan özellikleri tercih et; +otomatik özellikleri tercih et; +normal ifade; +normal ifade; +Gelişmiş renkleri kullan; +Düzenleyici Renk Düzeni; C# Advanced options page keywords diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.zh-Hans.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.zh-Hans.xlf index cdef2b2edd32c..bfb50f7ca355f 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.zh-Hans.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.zh-Hans.xlf @@ -1,6 +1,6 @@  - + C# @@ -81,7 +81,7 @@ regex; regular expression; Use enhanced colors; Editor Color Scheme; - 显示内联参数名称提示; + 显示内联提示; 显示对已关闭文件的诊断; 对正则表达式着色; 突出显示游标下的相关组件; diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.zh-Hant.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.zh-Hant.xlf index 82fe530845fde..efad5d6f3a9bc 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.zh-Hant.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.zh-Hant.xlf @@ -1,6 +1,6 @@  - + C# @@ -81,54 +81,54 @@ regex; regular expression; Use enhanced colors; Editor Color Scheme; - Display inline hints; -Show diagnostics for closed files; -Colorize regular expression; -Highlight related components under cursor; -Report invalid regular expressions; -Enable full solution analysis; -Perform editor feature analysis in external process; -Enable navigation to decompiled sources; -Using directives; -Place system directives first when sorting usings; -Separate using directive groups; -Suggest usings for types in reference assemblies; -Suggest usings for types in NuGet packages; -Highlighting; -Highlight references to symbol under cursor; -Highlight related keywords under cursor; -Outlining; -Enter outlining mode when files open; -Show procedure line separators; -Show outlining for declaration level constructs; -Show outlining for code level constructs; -Show outlining for comments and preprocessor regions; -Collapse regions when collapsing to definitions; -Fading; -Fade out unused usings; -Fade out unreachable code; -Block Structure Guides; -Show guides for declaration level constructs; -Show guides for code level constructs; -Editor Help; -Generate XML documentation comments for ///; -Insert * at the start of new lines when writing /* */ comments; -Show preview for rename tracking; -Split string literals on Enter; -Report invalid placeholders in string.Format calls; -Extract Method; -Don't put ref or out on custom struct; -Implement Interface or Abstract Class; -When inserting properties, events and methods, place them; -with other members of the same kind; -at the end; -When generating property; -prefer throwing properties; -prefer auto properties; + 顯示內嵌提示; +顯示已關閉檔案的診斷; +為規則運算式著色; +醒目提示游標下的相關元件; +回報無效的規則運算式; +啟用完整解決方案分析; +在外部處理序中執行編輯器功能分析; +啟用瀏覽至反向組譯的來源; +using 指示詞; +排序 using 時先放置系統指示詞; +分隔 using 指示詞群組; +為參考組件中的類型建議 using; +為 NuGet 套件中的類型建議 using; +醒目提示; +醒目提示游標下的符號參考; +醒目提示游標下的相關關鍵字; +大綱; +在檔案開啟時進入大綱模式; +顯示程序行分隔符號; +顯示宣告層級建構的大綱; +顯示程式碼層級建構的大綱; +顯示註解與前置處理器區域的大綱; +在摺疊到定義時摺疊區域; +漸層; +淡出未使用的 using; +淡出無法執行到的程式碼; +區塊結構輔助線; +顯示宣告層級建構的輔助線; +顯示程式碼層級建構的輔助線; +編輯器說明; +產生 /// 的 XML 文件註解; +在撰寫 /* */ 註解時,於新行開頭插入 *; +顯示重新命名追蹤的預覽; +在按 Enter 鍵時分割字串常值; +回報 string.Format 呼叫中無效的預留位置; +擷取方法; +不要在自訂結構上放置 ref 或 out; +實作介面或抽象類別; +在插入屬性、事件和方法時,予以放置; +隨同其他同種類的成員; +結尾處; +產生屬性時; +建議使用擲回屬性; +建議使用自動屬性; regex; -regular expression; -Use enhanced colors; -Editor Color Scheme; +規則運算式; +使用進階色彩; +編輯器色彩配置; C# Advanced options page keywords diff --git a/src/VisualStudio/CSharp/Test/F1Help/F1HelpTests.cs b/src/VisualStudio/CSharp/Test/F1Help/F1HelpTests.cs index 9e7d5abfee2f1..8cbd257f2f9d5 100644 --- a/src/VisualStudio/CSharp/Test/F1Help/F1HelpTests.cs +++ b/src/VisualStudio/CSharp/Test/F1Help/F1HelpTests.cs @@ -8,11 +8,11 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService; using Microsoft.VisualStudio.LanguageServices.Implementation.F1Help; +using Microsoft.VisualStudio.LanguageServices.UnitTests; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; @@ -24,9 +24,7 @@ public class F1HelpTests { private static async Task TestAsync(string markup, string expectedText) { - // TODO: Using VisualStudioTestComposition.LanguageServices fails with "Failed to clean up listeners in a timely manner. WorkspaceChanged TaskQueue.cs 38" - // https://github.com/dotnet/roslyn/issues/46250 - using var workspace = TestWorkspace.CreateCSharp(markup, composition: EditorTestCompositions.EditorFeatures.AddParts(typeof(CSharpHelpContextService))); + using var workspace = TestWorkspace.CreateCSharp(markup, composition: VisualStudioTestCompositions.LanguageServices); var caret = workspace.Documents.First().CursorPosition; var service = Assert.IsType(workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetService()); @@ -1165,5 +1163,22 @@ static class C sta[||]tic void Method() {} }", "static"); } + + [Fact, Trait(Traits.Feature, Traits.Features.F1Help)] + public async Task TestWithKeyword() + { + await Test_KeywordAsync( +@" +public record Point(int X, int Y); + +public static class Program +{ + public static void Main() + { + var p1 = new Point(0, 0); + var p2 = p1 w[||]ith { X = 5 }; + } +}", "with"); + } } } diff --git a/src/VisualStudio/CodeLens/xlf/CodeLensVSResources.de.xlf b/src/VisualStudio/CodeLens/xlf/CodeLensVSResources.de.xlf index d74d376ff1a91..8e4d59857521e 100644 --- a/src/VisualStudio/CodeLens/xlf/CodeLensVSResources.de.xlf +++ b/src/VisualStudio/CodeLens/xlf/CodeLensVSResources.de.xlf @@ -14,7 +14,7 @@ {0} reference - {0}-Verweis + {0} Verweis diff --git a/src/VisualStudio/CodeLens/xlf/CodeLensVSResources.it.xlf b/src/VisualStudio/CodeLens/xlf/CodeLensVSResources.it.xlf index 0f39d65af832e..800681f28ef91 100644 --- a/src/VisualStudio/CodeLens/xlf/CodeLensVSResources.it.xlf +++ b/src/VisualStudio/CodeLens/xlf/CodeLensVSResources.it.xlf @@ -29,7 +29,7 @@ property - Proprietà. + proprietà diff --git a/src/VisualStudio/CodeLens/xlf/CodeLensVSResources.pt-BR.xlf b/src/VisualStudio/CodeLens/xlf/CodeLensVSResources.pt-BR.xlf index b589196026c9a..eaefe4a95e041 100644 --- a/src/VisualStudio/CodeLens/xlf/CodeLensVSResources.pt-BR.xlf +++ b/src/VisualStudio/CodeLens/xlf/CodeLensVSResources.pt-BR.xlf @@ -29,7 +29,7 @@ property - Propriedade. + propriedade diff --git a/src/VisualStudio/CodeLens/xlf/CodeLensVSResources.zh-Hans.xlf b/src/VisualStudio/CodeLens/xlf/CodeLensVSResources.zh-Hans.xlf index 7b6d8f14b49c7..bedc78dcacb5c 100644 --- a/src/VisualStudio/CodeLens/xlf/CodeLensVSResources.zh-Hans.xlf +++ b/src/VisualStudio/CodeLens/xlf/CodeLensVSResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + C# and Visual Basic References diff --git a/src/VisualStudio/CodeLens/xlf/CodeLensVSResources.zh-Hant.xlf b/src/VisualStudio/CodeLens/xlf/CodeLensVSResources.zh-Hant.xlf index 06b6b1c55b694..fd2f3b42926eb 100644 --- a/src/VisualStudio/CodeLens/xlf/CodeLensVSResources.zh-Hant.xlf +++ b/src/VisualStudio/CodeLens/xlf/CodeLensVSResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + C# and Visual Basic References diff --git a/src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/IVsTypeScriptVisualStudioProjectFactory.cs b/src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/IVsTypeScriptVisualStudioProjectFactory.cs new file mode 100644 index 0000000000000..333e0bfd49889 --- /dev/null +++ b/src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/IVsTypeScriptVisualStudioProjectFactory.cs @@ -0,0 +1,14 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using Microsoft.VisualStudio.Shell.Interop; + +namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api +{ + internal interface IVsTypeScriptVisualStudioProjectFactory + { + VSTypeScriptVisualStudioProjectWrapper CreateAndAddToWorkspace(string projectSystemName, string language, string projectFilePath, IVsHierarchy hierarchy, Guid projectGuid); + } +} diff --git a/src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/VSTypeScriptContainedDocumentWrapper.cs b/src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/VSTypeScriptContainedDocumentWrapper.cs index f89ae1763692e..45928bdca550b 100644 --- a/src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/VSTypeScriptContainedDocumentWrapper.cs +++ b/src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/VSTypeScriptContainedDocumentWrapper.cs @@ -4,9 +4,11 @@ #pragma warning disable CS0618 // Type or member is obsolete +using System; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; +using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api @@ -35,14 +37,21 @@ public static bool TryGetContainedDocument(DocumentId documentId, out VSTypeScri return false; } + public void Dispose() + => _underlyingObject.Dispose(); + + public ITextBuffer SubjectBuffer + => _underlyingObject.SubjectBuffer; + + public IVsContainedLanguageHost Host + => _underlyingObject.ContainedLanguageHost; + + [Obsolete("Remove once TypeScript has stopped using this.")] internal AbstractProject Project => _underlyingObject.Project; + [Obsolete("Remove once TypeScript has stopped using this.")] internal IVisualStudioHostDocument HostDocument => _underlyingObject; - - internal IVsContainedLanguageHost Host - => _underlyingObject.ContainedLanguageHost; - } } diff --git a/src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/VSTypeScriptContainedLanguageWrapper.cs b/src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/VSTypeScriptContainedLanguageWrapper.cs index 09d6f369c680b..df7694bb89f96 100644 --- a/src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/VSTypeScriptContainedLanguageWrapper.cs +++ b/src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/VSTypeScriptContainedLanguageWrapper.cs @@ -18,6 +18,7 @@ internal struct VSTypeScriptContainedLanguageWrapper { private readonly ContainedLanguage _underlyingObject; + [Obsolete("Remove once TypeScript has stopped using this.", error: true)] public VSTypeScriptContainedLanguageWrapper( IVsTextBufferCoordinator bufferCoordinator, IComponentModel componentModel, @@ -40,6 +41,28 @@ public VSTypeScriptContainedLanguageWrapper( vbHelperFormattingRule: null); } + public VSTypeScriptContainedLanguageWrapper( + IVsTextBufferCoordinator bufferCoordinator, + IComponentModel componentModel, + VSTypeScriptVisualStudioProjectWrapper project, + IVsHierarchy hierarchy, + uint itemid, + Guid languageServiceGuid) + { + var workspace = componentModel.GetService(); + var filePath = ContainedLanguage.GetFilePathFromHierarchyAndItemId(hierarchy, itemid); + + _underlyingObject = new ContainedLanguage( + bufferCoordinator, + componentModel, + workspace, + project.Project.Id, + project.Project, + filePath, + languageServiceGuid, + vbHelperFormattingRule: null); + } + public VSTypeScriptContainedLanguageWrapper( IVsTextBufferCoordinator bufferCoordinator, IComponentModel componentModel, diff --git a/src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/VSTypeScriptVisualStudioProjectWrapper.LSPContainedDocumentServiceProvider.cs b/src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/VSTypeScriptVisualStudioProjectWrapper.LSPContainedDocumentServiceProvider.cs new file mode 100644 index 0000000000000..337dddde4f165 --- /dev/null +++ b/src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/VSTypeScriptVisualStudioProjectWrapper.LSPContainedDocumentServiceProvider.cs @@ -0,0 +1,48 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Microsoft.CodeAnalysis.Host; + +namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api +{ + internal sealed partial class VSTypeScriptVisualStudioProjectWrapper + { + private sealed class LspContainedDocumentServiceProvider : IDocumentServiceProvider, IDocumentOperationService + { + private readonly VirtualDocumentPropertiesService _documentPropertiesService; + + private LspContainedDocumentServiceProvider() + { + _documentPropertiesService = VirtualDocumentPropertiesService.Instance; + } + + public static LspContainedDocumentServiceProvider Instance = new LspContainedDocumentServiceProvider(); + + bool IDocumentOperationService.CanApplyChange => true; + + bool IDocumentOperationService.SupportDiagnostics => true; + + TService? IDocumentServiceProvider.GetService() where TService : class + { + if (typeof(TService) == typeof(DocumentPropertiesService)) + { + return (TService)(object)_documentPropertiesService; + } + + return this as TService; + } + + private sealed class VirtualDocumentPropertiesService : DocumentPropertiesService + { + private const string _lspClientName = "TypeScript"; + + private VirtualDocumentPropertiesService() { } + + public static VirtualDocumentPropertiesService Instance = new VirtualDocumentPropertiesService(); + + public override string? DiagnosticsLspClientName => _lspClientName; + } + } + } +} diff --git a/src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/VSTypeScriptVisualStudioProjectWrapper.cs b/src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/VSTypeScriptVisualStudioProjectWrapper.cs new file mode 100644 index 0000000000000..19918dcdb1617 --- /dev/null +++ b/src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/VSTypeScriptVisualStudioProjectWrapper.cs @@ -0,0 +1,44 @@ +// Licensed to the .NET Foundation under one or more 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; +using Microsoft.CodeAnalysis.Text; +using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; + +namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api +{ + internal sealed partial class VSTypeScriptVisualStudioProjectWrapper + { + public VSTypeScriptVisualStudioProjectWrapper(VisualStudioProject underlyingObject) + => Project = underlyingObject; + + public ProjectId Id => Project.Id; + + public string DisplayName + { + get => Project.DisplayName; + set => Project.DisplayName = value; + } + + public void AddSourceFile(string fullPath) + => Project.AddSourceFile(fullPath, SourceCodeKind.Regular); + + public DocumentId AddSourceTextContainer(SourceTextContainer sourceTextContainer, string fullPath, bool isLspContainedDocument = false) + { + var documentServiceProvider = isLspContainedDocument ? LspContainedDocumentServiceProvider.Instance : null; + return Project.AddSourceTextContainer(sourceTextContainer, fullPath, SourceCodeKind.Regular, documentServiceProvider: documentServiceProvider); + } + + public void RemoveSourceFile(string fullPath) + => Project.RemoveSourceFile(fullPath); + + public void RemoveSourceTextContainer(SourceTextContainer sourceTextContainer) + => Project.RemoveSourceTextContainer(sourceTextContainer); + + public void RemoveFromWorkspace() + => Project.RemoveFromWorkspace(); + + internal VisualStudioProject Project { get; } + } +} diff --git a/src/VisualStudio/Core/Def/Implementation/LanguageClient/AlwaysActivateInProcLanguageClient.cs b/src/VisualStudio/Core/Def/Implementation/LanguageClient/AlwaysActivateInProcLanguageClient.cs index 9eeb3e4e7cb1c..afaecfb4e5e20 100644 --- a/src/VisualStudio/Core/Def/Implementation/LanguageClient/AlwaysActivateInProcLanguageClient.cs +++ b/src/VisualStudio/Core/Def/Implementation/LanguageClient/AlwaysActivateInProcLanguageClient.cs @@ -48,8 +48,13 @@ public override string Name protected internal override VSServerCapabilities GetCapabilities() => new VSServerCapabilities { + TextDocumentSync = new TextDocumentSyncOptions + { + Change = TextDocumentSyncKind.Incremental, + OpenClose = true, + }, SupportsDiagnosticRequests = _globalOptionService.GetOption(InternalDiagnosticsOptions.NormalDiagnosticMode) == DiagnosticMode.Pull, - // This flag ensures that cntrl+, search locally uses the old editor APIs so that only cntrl+Q search is powered via LSP. + // This flag ensures that ctrl+, search locally uses the old editor APIs so that only ctrl+Q search is powered via LSP. DisableGoToWorkspaceSymbols = true, WorkspaceSymbolProvider = true, }; diff --git a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/MetadataReferences/VisualStudioFrameworkAssemblyPathResolverFactory.cs b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/MetadataReferences/VisualStudioFrameworkAssemblyPathResolverFactory.cs index 461ea6b6a985c..3b4aef3a4d80c 100644 --- a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/MetadataReferences/VisualStudioFrameworkAssemblyPathResolverFactory.cs +++ b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/MetadataReferences/VisualStudioFrameworkAssemblyPathResolverFactory.cs @@ -7,8 +7,6 @@ using System.IO; using System.Reflection; using System.Runtime.Versioning; -using System.Threading; -using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; @@ -48,13 +46,12 @@ public Service(IThreadingContext threadingContext, VisualStudioWorkspace? worksp _serviceProvider = serviceProvider; } - public async Task ResolveAssemblyPathAsync( + public string? ResolveAssemblyPath( ProjectId projectId, string assemblyName, - string? fullyQualifiedTypeName, - CancellationToken cancellationToken) + string? fullyQualifiedTypeName) { - await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); + AssertIsForeground(); var assembly = ResolveAssembly(projectId, assemblyName); if (assembly != null) diff --git a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProjectFactory.cs b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProjectFactory.cs index 49daa3e7715a7..777dcb5a8ba57 100644 --- a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProjectFactory.cs +++ b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProjectFactory.cs @@ -10,6 +10,7 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Telemetry; @@ -17,7 +18,8 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { [Export(typeof(VisualStudioProjectFactory))] - internal sealed class VisualStudioProjectFactory + [Export(typeof(IVsTypeScriptVisualStudioProjectFactory))] + internal sealed class VisualStudioProjectFactory : IVsTypeScriptVisualStudioProjectFactory { private const string SolutionContextName = "Solution"; private const string SolutionSessionIdPropertyName = "SolutionSessionID"; @@ -130,5 +132,17 @@ static Guid GetSolutionSessionId() return solutionSessionId; } } + + VSTypeScriptVisualStudioProjectWrapper IVsTypeScriptVisualStudioProjectFactory.CreateAndAddToWorkspace(string projectSystemName, string language, string projectFilePath, IVsHierarchy hierarchy, Guid projectGuid) + { + var projectInfo = new VisualStudioProjectCreationInfo + { + FilePath = projectFilePath, + Hierarchy = hierarchy, + ProjectGuid = projectGuid, + }; + var visualStudioProject = this.CreateAndAddToWorkspace(projectSystemName, language, projectInfo); + return new VSTypeScriptVisualStudioProjectWrapper(visualStudioProject); + } } } diff --git a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioWorkspaceImpl.cs b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioWorkspaceImpl.cs index 9d11d30fd3ab4..73a1e9d3ed96d 100644 --- a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioWorkspaceImpl.cs +++ b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioWorkspaceImpl.cs @@ -1429,9 +1429,9 @@ public void EnsureEditableDocuments(IEnumerable documents) public void EnsureEditableDocuments(params DocumentId[] documents) => this.EnsureEditableDocuments((IEnumerable)documents); - internal override async Task CanAddProjectReferenceAsync(ProjectId referencingProject, ProjectId referencedProject, CancellationToken cancellationToken) + internal override bool CanAddProjectReference(ProjectId referencingProject, ProjectId referencedProject) { - await _foregroundObject.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); + _foregroundObject.AssertIsForeground(); if (!TryGetHierarchy(referencingProject, out var referencingHierarchy) || !TryGetHierarchy(referencedProject, out var referencedHierarchy)) diff --git a/src/VisualStudio/Core/Def/Implementation/TaskList/ExternalErrorDiagnosticUpdateSource.cs b/src/VisualStudio/Core/Def/Implementation/TaskList/ExternalErrorDiagnosticUpdateSource.cs index 0176b17285ce2..38e4b0ba42c8b 100644 --- a/src/VisualStudio/Core/Def/Implementation/TaskList/ExternalErrorDiagnosticUpdateSource.cs +++ b/src/VisualStudio/Core/Def/Implementation/TaskList/ExternalErrorDiagnosticUpdateSource.cs @@ -15,7 +15,6 @@ using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Roslyn.Utilities; @@ -717,7 +716,11 @@ IEnumerable GetProjectsWithErrors() public ImmutableArray GetLiveErrorsForProject(ProjectId projectId) { - var project = Solution.GetRequiredProject(projectId); + var project = Solution.GetProject(projectId); + if (project == null) + { + return ImmutableArray.Empty; + } var diagnostics = _projectMap.Where(kv => kv.Key == projectId).SelectMany(kv => kv.Value).Concat( _documentMap.Where(kv => kv.Key.ProjectId == projectId).SelectMany(kv => kv.Value)); diff --git a/src/VisualStudio/Core/Def/Implementation/Workspace/SourceGeneratedFileManager.cs b/src/VisualStudio/Core/Def/Implementation/Workspace/SourceGeneratedFileManager.cs index cb0a4987f85e6..dc713ddeb720a 100644 --- a/src/VisualStudio/Core/Def/Implementation/Workspace/SourceGeneratedFileManager.cs +++ b/src/VisualStudio/Core/Def/Implementation/Workspace/SourceGeneratedFileManager.cs @@ -7,6 +7,7 @@ using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.IO; +using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; @@ -109,7 +110,7 @@ public SourceGeneratedFileManager( this); } - public void NavigateToSourceGeneratedFile(Project project, ISourceGenerator generator, string generatedSourceHintName, TextSpan sourceSpan) + public void NavigateToSourceGeneratedFile(SourceGeneratedDocument document, TextSpan sourceSpan) { _foregroundThreadAffintizedObject.AssertIsForeground(); @@ -117,7 +118,7 @@ public void NavigateToSourceGeneratedFile(Project project, ISourceGenerator gene // but most URIs are blocked other than file:// and http://; they also get extra handling to attempt to download the file so // those aren't really usable anyways. - var generatorType = generator.GetType(); + var generatorType = document.SourceGenerator.GetType(); var generatorAssemblyName = generatorType.Assembly.GetName().Name ?? string.Empty; var generatorFullName = generatorType.FullName; @@ -144,9 +145,9 @@ public void NavigateToSourceGeneratedFile(Project project, ISourceGenerator gene // This can only be changed if the compiler changes the algorithm as well. The directory itself we can of course change. var temporaryFilePath = Path.Combine( _temporaryDirectory, - project.Id.Id.ToString(), + document.Project.Id.Id.ToString(), guidForDirectory.Value.ToString(), - generatedSourceHintName); + document.HintName); Directory.CreateDirectory(Path.GetDirectoryName(temporaryFilePath)); @@ -340,7 +341,7 @@ public void Dispose() public async Task UpdateBufferContentsAsync(CancellationToken cancellationToken) { - GeneratedSourceResult? generatedSource = null; + SourceText? generatedSource = null; var project = _workspace.CurrentSolution.GetProject(_projectId); // Locals correspond to the equivalently-named fields; we'll assign these and then assign to the fields while on the @@ -355,30 +356,29 @@ public async Task UpdateBufferContentsAsync(CancellationToken cancellationToken) } else { + var generatedDocuments = await project.GetSourceGeneratedDocumentsAsync(cancellationToken).ConfigureAwait(false); + var generatedDocument = generatedDocuments.SingleOrDefault(d => + d.SourceGenerator.GetType().FullName.Equals(_generatorTypeName) && + d.SourceGenerator.GetType().Assembly.GetName().Name.Equals(_generatorAssemblyName)); - var generatorDriverRunResults = await project.GetGeneratorDriverRunResultAsync(cancellationToken).ConfigureAwait(false); - var generatorRunResult = generatorDriverRunResults?.Results.SingleOrNull(r => - r.Generator.GetType().FullName.Equals(_generatorTypeName, StringComparison.OrdinalIgnoreCase) && - r.Generator.GetType().Assembly.GetName().Name.Equals(_generatorAssemblyName)); - - if (generatorRunResult == null) + if (generatedDocument != null) { - windowFrameMessageToShow = string.Format(ServicesVSResources.The_generator_0_that_generated_this_file_has_been_removed_from_the_project, _generatorTypeName); - windowFrameImageMonikerToShow = KnownMonikers.StatusError; + windowFrameMessageToShow = string.Format(ServicesVSResources.This_file_is_autogenerated_by_0_and_cannot_be_edited, _generatorTypeName); + windowFrameImageMonikerToShow = default; + generatedSource = await generatedDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); } else { - generatedSource = generatorRunResult.Value.GeneratedSources.SingleOrNull(r => r.HintName == _generatedSourceHintName); - - if (generatedSource == null) + // The file isn't there anymore; do we still have the generator at all? + if (project.AnalyzerReferences.Any(a => a.GetGenerators(project.Language).Any(g => g.GetType().Assembly.GetName().Name.Equals(_generatorAssemblyName)))) { windowFrameMessageToShow = string.Format(ServicesVSResources.The_generator_0_that_generated_this_file_has_stopped_generating_this_file, _generatorTypeName); windowFrameImageMonikerToShow = KnownMonikers.StatusError; } else { - windowFrameMessageToShow = string.Format(ServicesVSResources.This_file_is_autogenerated_by_0_and_cannot_be_edited, _generatorTypeName); - windowFrameImageMonikerToShow = default; + windowFrameMessageToShow = string.Format(ServicesVSResources.The_generator_0_that_generated_this_file_has_been_removed_from_the_project, _generatorTypeName); + windowFrameImageMonikerToShow = KnownMonikers.StatusError; } } } @@ -389,7 +389,7 @@ public async Task UpdateBufferContentsAsync(CancellationToken cancellationToken) _windowFrameImageMonikerToShow = windowFrameImageMonikerToShow; // Update the text if we have new text - if (generatedSource.HasValue) + if (generatedSource != null) { try { @@ -399,14 +399,14 @@ public async Task UpdateBufferContentsAsync(CancellationToken cancellationToken) // Ensure the encoding matches; this is necessary for debugger checksums to match what is in the PDB. if (_fileManager._textDocumentFactoryService.TryGetTextDocument(_textBuffer, out var textDocument)) { - textDocument.Encoding = generatedSource.Value.SourceText.Encoding; + textDocument.Encoding = generatedSource.Encoding; } // We'll ask the editor to do the diffing for us so updates don't refresh the entire buffer using (var edit = _textBuffer.CreateEdit(EditOptions.DefaultMinimalChange, reiteratedVersionNumber: null, editTag: null)) { // TODO: make the edit in some nicer way than creating a massive string - edit.Replace(startPosition: 0, _textBuffer.CurrentSnapshot.Length, generatedSource.Value.SourceText.ToString()); + edit.Replace(startPosition: 0, _textBuffer.CurrentSnapshot.Length, generatedSource.ToString()); edit.Apply(); } } diff --git a/src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioDocumentNavigationService.cs b/src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioDocumentNavigationService.cs index 8fb579be342d4..210c2a09b0717 100644 --- a/src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioDocumentNavigationService.cs +++ b/src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioDocumentNavigationService.cs @@ -43,19 +43,22 @@ internal sealed class VisualStudioDocumentNavigationService : ForegroundThreadAf private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; private readonly IVsRunningDocumentTable4 _runningDocumentTable; private readonly IThreadingContext _threadingContext; + private readonly Lazy _sourceGeneratedFileManager; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioDocumentNavigationService( IThreadingContext threadingContext, SVsServiceProvider serviceProvider, - IVsEditorAdaptersFactoryService editorAdaptersFactoryService) + IVsEditorAdaptersFactoryService editorAdaptersFactoryService, + Lazy sourceGeneratedFileManager /* lazy to avoid circularities */) : base(threadingContext) { _serviceProvider = serviceProvider; _editorAdaptersFactoryService = editorAdaptersFactoryService; _runningDocumentTable = (IVsRunningDocumentTable4)serviceProvider.GetService(typeof(SVsRunningDocumentTable)); _threadingContext = threadingContext; + _sourceGeneratedFileManager = sourceGeneratedFileManager; } public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan) @@ -236,6 +239,23 @@ private bool TryNavigateToLocation(Workspace workspace, DocumentId documentId, F using (OpenNewDocumentStateScope(options ?? workspace.Options)) { + if (workspace.CurrentSolution.GetDocument(documentId) == null) + { + // We unfortunately don't have a cancellation token to pass here right now; we don't expect this to be expensive though, + // because if a feature is asking to navigate to this file, it's because they already know this file contains something interesting; + // that probably means generators have already ran so this should be a no-op. If this proves to be wrong, we may want to refactor + // this further to have the SourceGeneratedFileManager instead open the file asynchronously. + var generatedDocument = workspace.CurrentSolution.GetProject(documentId.ProjectId) + .GetSourceGeneratedDocumentAsync(documentId, CancellationToken.None) + .GetAwaiter().GetResult(); + + if (generatedDocument != null) + { + _sourceGeneratedFileManager.Value.NavigateToSourceGeneratedFile(generatedDocument, getTextSpanForMapping(generatedDocument)); + return true; + } + } + // Before attempting to open the document, check if the location maps to a different file that should be opened instead. var document = workspace.CurrentSolution.GetDocument(documentId); var spanMappingService = document?.Services.GetService(); diff --git a/src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioSymbolNavigationService.cs b/src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioSymbolNavigationService.cs index 1f6748a6bfe30..70a19235aba7d 100644 --- a/src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioSymbolNavigationService.cs +++ b/src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioSymbolNavigationService.cs @@ -77,17 +77,6 @@ public bool TryNavigateToSymbol(ISymbol symbol, Project project, OptionSet optio var navigationService = editorWorkspace.Services.GetRequiredService(); return navigationService.TryNavigateToSpan(editorWorkspace, targetDocument.Id, sourceLocation.SourceSpan, options); } - else - { - // This may be a file from a source generator; if so let's go to it instead - var generatorRunResult = project.GetGeneratorDriverRunResultAsync(cancellationToken).WaitAndGetResult(cancellationToken); - - if (generatorRunResult.TryGetGeneratorAndHint(sourceLocation.SourceTree!, out var generator, out var hintName)) - { - _sourceGeneratedFileManager.NavigateToSourceGeneratedFile(project, generator, hintName, sourceLocation.SourceSpan); - return true; - } - } } // We don't have a source document, so show the Metadata as Source view in a preview tab. diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.cs.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.cs.xlf index 56192c2213423..646c47c36abc1 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.cs.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.cs.xlf @@ -39,107 +39,107 @@ &Default - &Default + &Default ErrorListSetSeverityDefault - ErrorListSetSeverityDefault + ErrorListSetSeverityDefault Default - Default + Default &Error - &Error + &Error ErrorListSetSeverityError - ErrorListSetSeverityError + ErrorListSetSeverityError Error - Error + Error &Silent - &Silent + &Silent ErrorListSetSeverityHidden - ErrorListSetSeverityHidden + ErrorListSetSeverityHidden Silent - Silent + Silent &Suggestion - &Suggestion + &Suggestion ErrorListSetSeverityInfo - ErrorListSetSeverityInfo + ErrorListSetSeverityInfo Suggestion - Suggestion + Suggestion &None - &None + &None ErrorListSetSeverityNone - ErrorListSetSeverityNone + ErrorListSetSeverityNone None - None + None Set severity - Set severity + Set severity Set severity - Set severity + Set severity Set severity - Set severity + Set severity &Warning - &Warning + &Warning ErrorListSetSeverityWarning - ErrorListSetSeverityWarning + ErrorListSetSeverityWarning Warning - Warning + Warning diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.de.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.de.xlf index dbae31b7fd05d..82dc17d6fbeb1 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.de.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.de.xlf @@ -39,107 +39,107 @@ &Default - &Default + &Default ErrorListSetSeverityDefault - ErrorListSetSeverityDefault + ErrorListSetSeverityDefault Default - Default + Default &Error - &Error + &Error ErrorListSetSeverityError - ErrorListSetSeverityError + ErrorListSetSeverityError Error - Error + Error &Silent - &Silent + &Silent ErrorListSetSeverityHidden - ErrorListSetSeverityHidden + ErrorListSetSeverityHidden Silent - Silent + Silent &Suggestion - &Suggestion + &Suggestion ErrorListSetSeverityInfo - ErrorListSetSeverityInfo + ErrorListSetSeverityInfo Suggestion - Suggestion + Suggestion &None - &None + &None ErrorListSetSeverityNone - ErrorListSetSeverityNone + ErrorListSetSeverityNone None - None + None Set severity - Set severity + Set severity Set severity - Set severity + Set severity Set severity - Set severity + Set severity &Warning - &Warning + &Warning ErrorListSetSeverityWarning - ErrorListSetSeverityWarning + ErrorListSetSeverityWarning Warning - Warning + Warning diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.es.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.es.xlf index 2d840944b3d59..3a230f73e861b 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.es.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.es.xlf @@ -39,107 +39,107 @@ &Default - &Default + &Default ErrorListSetSeverityDefault - ErrorListSetSeverityDefault + ErrorListSetSeverityDefault Default - Default + Default &Error - &Error + &Error ErrorListSetSeverityError - ErrorListSetSeverityError + ErrorListSetSeverityError Error - Error + Error &Silent - &Silent + &Silent ErrorListSetSeverityHidden - ErrorListSetSeverityHidden + ErrorListSetSeverityHidden Silent - Silent + Silent &Suggestion - &Suggestion + &Suggestion ErrorListSetSeverityInfo - ErrorListSetSeverityInfo + ErrorListSetSeverityInfo Suggestion - Suggestion + Suggestion &None - &None + &None ErrorListSetSeverityNone - ErrorListSetSeverityNone + ErrorListSetSeverityNone None - None + None Set severity - Set severity + Set severity Set severity - Set severity + Set severity Set severity - Set severity + Set severity &Warning - &Warning + &Warning ErrorListSetSeverityWarning - ErrorListSetSeverityWarning + ErrorListSetSeverityWarning Warning - Warning + Warning diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.fr.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.fr.xlf index 4e306e150bb38..5d3bb3bad0423 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.fr.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.fr.xlf @@ -39,107 +39,107 @@ &Default - &Default + &Default ErrorListSetSeverityDefault - ErrorListSetSeverityDefault + ErrorListSetSeverityDefault Default - Default + Default &Error - &Error + &Error ErrorListSetSeverityError - ErrorListSetSeverityError + ErrorListSetSeverityError Error - Error + Error &Silent - &Silent + &Silent ErrorListSetSeverityHidden - ErrorListSetSeverityHidden + ErrorListSetSeverityHidden Silent - Silent + Silent &Suggestion - &Suggestion + &Suggestion ErrorListSetSeverityInfo - ErrorListSetSeverityInfo + ErrorListSetSeverityInfo Suggestion - Suggestion + Suggestion &None - &None + &None ErrorListSetSeverityNone - ErrorListSetSeverityNone + ErrorListSetSeverityNone None - None + None Set severity - Set severity + Set severity Set severity - Set severity + Set severity Set severity - Set severity + Set severity &Warning - &Warning + &Warning ErrorListSetSeverityWarning - ErrorListSetSeverityWarning + ErrorListSetSeverityWarning Warning - Warning + Warning diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.it.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.it.xlf index ed44db51882ff..9ab4f9ab9da30 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.it.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.it.xlf @@ -39,107 +39,107 @@ &Default - &Default + &Default ErrorListSetSeverityDefault - ErrorListSetSeverityDefault + ErrorListSetSeverityDefault Default - Default + Default &Error - &Error + &Error ErrorListSetSeverityError - ErrorListSetSeverityError + ErrorListSetSeverityError Error - Error + Error &Silent - &Silent + &Silent ErrorListSetSeverityHidden - ErrorListSetSeverityHidden + ErrorListSetSeverityHidden Silent - Silent + Silent &Suggestion - &Suggestion + &Suggestion ErrorListSetSeverityInfo - ErrorListSetSeverityInfo + ErrorListSetSeverityInfo Suggestion - Suggestion + Suggestion &None - &None + &None ErrorListSetSeverityNone - ErrorListSetSeverityNone + ErrorListSetSeverityNone None - None + None Set severity - Set severity + Set severity Set severity - Set severity + Set severity Set severity - Set severity + Set severity &Warning - &Warning + &Warning ErrorListSetSeverityWarning - ErrorListSetSeverityWarning + ErrorListSetSeverityWarning Warning - Warning + Warning diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.ja.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.ja.xlf index eb815027250ca..1d329b634a821 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.ja.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.ja.xlf @@ -39,107 +39,107 @@ &Default - &Default + &Default ErrorListSetSeverityDefault - ErrorListSetSeverityDefault + ErrorListSetSeverityDefault Default - Default + Default &Error - &Error + &Error ErrorListSetSeverityError - ErrorListSetSeverityError + ErrorListSetSeverityError Error - Error + Error &Silent - &Silent + &Silent ErrorListSetSeverityHidden - ErrorListSetSeverityHidden + ErrorListSetSeverityHidden Silent - Silent + Silent &Suggestion - &Suggestion + &Suggestion ErrorListSetSeverityInfo - ErrorListSetSeverityInfo + ErrorListSetSeverityInfo Suggestion - Suggestion + Suggestion &None - &None + &None ErrorListSetSeverityNone - ErrorListSetSeverityNone + ErrorListSetSeverityNone None - None + None Set severity - Set severity + Set severity Set severity - Set severity + Set severity Set severity - Set severity + Set severity &Warning - &Warning + &Warning ErrorListSetSeverityWarning - ErrorListSetSeverityWarning + ErrorListSetSeverityWarning Warning - Warning + Warning diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.ko.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.ko.xlf index ad364043cdd78..a52578e81d8d7 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.ko.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.ko.xlf @@ -39,107 +39,107 @@ &Default - &Default + &Default ErrorListSetSeverityDefault - ErrorListSetSeverityDefault + ErrorListSetSeverityDefault Default - Default + Default &Error - &Error + &Error ErrorListSetSeverityError - ErrorListSetSeverityError + ErrorListSetSeverityError Error - Error + Error &Silent - &Silent + &Silent ErrorListSetSeverityHidden - ErrorListSetSeverityHidden + ErrorListSetSeverityHidden Silent - Silent + Silent &Suggestion - &Suggestion + &Suggestion ErrorListSetSeverityInfo - ErrorListSetSeverityInfo + ErrorListSetSeverityInfo Suggestion - Suggestion + Suggestion &None - &None + &None ErrorListSetSeverityNone - ErrorListSetSeverityNone + ErrorListSetSeverityNone None - None + None Set severity - Set severity + Set severity Set severity - Set severity + Set severity Set severity - Set severity + Set severity &Warning - &Warning + &Warning ErrorListSetSeverityWarning - ErrorListSetSeverityWarning + ErrorListSetSeverityWarning Warning - Warning + Warning diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.pl.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.pl.xlf index bd823ff04fd14..ebcca12449dcb 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.pl.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.pl.xlf @@ -39,107 +39,107 @@ &Default - &Default + &Default ErrorListSetSeverityDefault - ErrorListSetSeverityDefault + ErrorListSetSeverityDefault Default - Default + Default &Error - &Error + &Error ErrorListSetSeverityError - ErrorListSetSeverityError + ErrorListSetSeverityError Error - Error + Error &Silent - &Silent + &Silent ErrorListSetSeverityHidden - ErrorListSetSeverityHidden + ErrorListSetSeverityHidden Silent - Silent + Silent &Suggestion - &Suggestion + &Suggestion ErrorListSetSeverityInfo - ErrorListSetSeverityInfo + ErrorListSetSeverityInfo Suggestion - Suggestion + Suggestion &None - &None + &None ErrorListSetSeverityNone - ErrorListSetSeverityNone + ErrorListSetSeverityNone None - None + None Set severity - Set severity + Set severity Set severity - Set severity + Set severity Set severity - Set severity + Set severity &Warning - &Warning + &Warning ErrorListSetSeverityWarning - ErrorListSetSeverityWarning + ErrorListSetSeverityWarning Warning - Warning + Warning diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.pt-BR.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.pt-BR.xlf index 5f1c9ba4440d4..27de984854c8e 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.pt-BR.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.pt-BR.xlf @@ -39,107 +39,107 @@ &Default - &Default + &Default ErrorListSetSeverityDefault - ErrorListSetSeverityDefault + ErrorListSetSeverityDefault Default - Default + Default &Error - &Error + &Error ErrorListSetSeverityError - ErrorListSetSeverityError + ErrorListSetSeverityError Error - Error + Error &Silent - &Silent + &Silent ErrorListSetSeverityHidden - ErrorListSetSeverityHidden + ErrorListSetSeverityHidden Silent - Silent + Silent &Suggestion - &Suggestion + &Suggestion ErrorListSetSeverityInfo - ErrorListSetSeverityInfo + ErrorListSetSeverityInfo Suggestion - Suggestion + Suggestion &None - &None + &None ErrorListSetSeverityNone - ErrorListSetSeverityNone + ErrorListSetSeverityNone None - None + None Set severity - Set severity + Set severity Set severity - Set severity + Set severity Set severity - Set severity + Set severity &Warning - &Warning + &Warning ErrorListSetSeverityWarning - ErrorListSetSeverityWarning + ErrorListSetSeverityWarning Warning - Warning + Warning diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.ru.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.ru.xlf index c51c160919b8f..b08555c8f680e 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.ru.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.ru.xlf @@ -39,107 +39,107 @@ &Default - &Default + &Default ErrorListSetSeverityDefault - ErrorListSetSeverityDefault + ErrorListSetSeverityDefault Default - Default + Default &Error - &Error + &Error ErrorListSetSeverityError - ErrorListSetSeverityError + ErrorListSetSeverityError Error - Error + Error &Silent - &Silent + &Silent ErrorListSetSeverityHidden - ErrorListSetSeverityHidden + ErrorListSetSeverityHidden Silent - Silent + Silent &Suggestion - &Suggestion + &Suggestion ErrorListSetSeverityInfo - ErrorListSetSeverityInfo + ErrorListSetSeverityInfo Suggestion - Suggestion + Suggestion &None - &None + &None ErrorListSetSeverityNone - ErrorListSetSeverityNone + ErrorListSetSeverityNone None - None + None Set severity - Set severity + Set severity Set severity - Set severity + Set severity Set severity - Set severity + Set severity &Warning - &Warning + &Warning ErrorListSetSeverityWarning - ErrorListSetSeverityWarning + ErrorListSetSeverityWarning Warning - Warning + Warning diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.tr.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.tr.xlf index bfe07ac1dd28f..0f66c44e7250b 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.tr.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.tr.xlf @@ -39,107 +39,107 @@ &Default - &Default + &Default ErrorListSetSeverityDefault - ErrorListSetSeverityDefault + ErrorListSetSeverityDefault Default - Default + Default &Error - &Error + &Error ErrorListSetSeverityError - ErrorListSetSeverityError + ErrorListSetSeverityError Error - Error + Error &Silent - &Silent + &Silent ErrorListSetSeverityHidden - ErrorListSetSeverityHidden + ErrorListSetSeverityHidden Silent - Silent + Silent &Suggestion - &Suggestion + &Suggestion ErrorListSetSeverityInfo - ErrorListSetSeverityInfo + ErrorListSetSeverityInfo Suggestion - Suggestion + Suggestion &None - &None + &None ErrorListSetSeverityNone - ErrorListSetSeverityNone + ErrorListSetSeverityNone None - None + None Set severity - Set severity + Set severity Set severity - Set severity + Set severity Set severity - Set severity + Set severity &Warning - &Warning + &Warning ErrorListSetSeverityWarning - ErrorListSetSeverityWarning + ErrorListSetSeverityWarning Warning - Warning + Warning diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.zh-Hans.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.zh-Hans.xlf index 4c45348a1e4a0..955e404135e8a 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.zh-Hans.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Run Code &Analysis on Selection @@ -39,107 +39,107 @@ &Default - &Default + &Default ErrorListSetSeverityDefault - ErrorListSetSeverityDefault + ErrorListSetSeverityDefault Default - Default + Default &Error - &Error + &Error ErrorListSetSeverityError - ErrorListSetSeverityError + ErrorListSetSeverityError Error - Error + Error &Silent - &Silent + &Silent ErrorListSetSeverityHidden - ErrorListSetSeverityHidden + ErrorListSetSeverityHidden Silent - Silent + Silent &Suggestion - &Suggestion + &Suggestion ErrorListSetSeverityInfo - ErrorListSetSeverityInfo + ErrorListSetSeverityInfo Suggestion - Suggestion + Suggestion &None - &None + &None ErrorListSetSeverityNone - ErrorListSetSeverityNone + ErrorListSetSeverityNone None - None + None Set severity - Set severity + Set severity Set severity - Set severity + Set severity Set severity - Set severity + Set severity &Warning - &Warning + &Warning ErrorListSetSeverityWarning - ErrorListSetSeverityWarning + ErrorListSetSeverityWarning Warning - Warning + Warning diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.zh-Hant.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.zh-Hant.xlf index 1df8a6f1594fa..e94838d852490 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.zh-Hant.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Run Code &Analysis on Selection @@ -39,107 +39,107 @@ &Default - &Default + &Default ErrorListSetSeverityDefault - ErrorListSetSeverityDefault + ErrorListSetSeverityDefault Default - Default + Default &Error - &Error + &Error ErrorListSetSeverityError - ErrorListSetSeverityError + ErrorListSetSeverityError Error - Error + Error &Silent - &Silent + &Silent ErrorListSetSeverityHidden - ErrorListSetSeverityHidden + ErrorListSetSeverityHidden Silent - Silent + Silent &Suggestion - &Suggestion + &Suggestion ErrorListSetSeverityInfo - ErrorListSetSeverityInfo + ErrorListSetSeverityInfo Suggestion - Suggestion + Suggestion &None - &None + &None ErrorListSetSeverityNone - ErrorListSetSeverityNone + ErrorListSetSeverityNone None - None + None Set severity - Set severity + Set severity Set severity - Set severity + Set severity Set severity - Set severity + Set severity &Warning - &Warning + &Warning ErrorListSetSeverityWarning - ErrorListSetSeverityWarning + ErrorListSetSeverityWarning Warning - Warning + Warning diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.cs.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.cs.xlf index 80a0e36b42082..e27d3a4c7f4b9 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.cs.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.cs.xlf @@ -109,7 +109,7 @@ C#/Visual Basic Diagnostics Language Client - C#/Visual Basic Diagnostics Language Client + Klient jazyka diagnostiky C# nebo Visual Basic @@ -154,7 +154,7 @@ Color hints - Color hints + Barevné nápovědy @@ -164,7 +164,7 @@ Comments - Comments + Komentáře @@ -189,17 +189,17 @@ Display all hints while pressing Alt+F1 - Display all hints while pressing Alt+F1 + Při podržení kláves Alt+F1 zobrazit všechny nápovědy Disp_lay inline parameter name hints - Zobrazovat nápovědy k názvům v_ložených parametrů (experimentální) + Zobrazovat nápovědy k názvům v_ložených parametrů Display inline type hints - Display inline type hints + Zobrazovat vložené nápovědy k typům @@ -229,12 +229,12 @@ Enable Razor 'pull' diagnostics (experimental, requires restart) - Enable Razor 'pull' diagnostics (experimental, requires restart) + Povolit diagnostiku pull Razor (experimentální, vyžaduje restart) Enable 'pull' diagnostics (experimental, requires restart) - Enable 'pull' diagnostics (experimental, requires restart) + Povolit diagnostiku pull (experimentální, vyžaduje restart) @@ -259,7 +259,7 @@ Extract Base Class - Extract Base Class + Extrahovat základní třídu @@ -304,7 +304,7 @@ Inline Hints (experimental) - Inline Hints (experimental) + Vložené nápovědy (experimentální) @@ -399,12 +399,12 @@ Name conflicts with an existing type name. - Name conflicts with an existing type name. + Název koliduje s existujícím názvem typu. Name is not a valid {0} identifier. - Name is not a valid {0} identifier. + Název není platný identifikátor {0}. @@ -569,7 +569,7 @@ New Type Name: - New Type Name: + Název nového typu: @@ -814,22 +814,22 @@ Show hints for everything else - Show hints for everything else + Zobrazit nápovědy pro všechno ostatní Show hints for lambda parameter types - Show hints for lambda parameter types + Zobrazit nápovědy pro typy parametrů lambda Show hints for literals - Show hints for literals + Zobrazit nápovědy pro literály Show hints for variables with inferred types - Show hints for variables with inferred types + Zobrazit nápovědy pro proměnné s odvozenými typy @@ -839,12 +839,12 @@ Suppress hints when parameter name matches the method's intent - Suppress hints when parameter name matches the method's intent + Potlačit nápovědy, když název parametru odpovídá záměru metody Suppress hints when parameter names differ only by suffix - Suppress hints when parameter names differ only by suffix + Potlačit nápovědy, když se název parametru liší jen předponou @@ -854,17 +854,17 @@ The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. - The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. + Generátor {0}, který vygeneroval tento soubor, se odebral z projektu. Tento soubor už není součástí projektu. The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. - The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. + Generátor {0}, který vygeneroval tento soubor, přestal tento soubor generovat. Soubor už není součástí projektu. This file is auto-generated by the generator '{0}' and cannot be edited. - This file is auto-generated by the generator '{0}' and cannot be edited. + Tento soubor se automaticky vygeneroval pomocí generátoru {0} a nedá se upravit. @@ -909,7 +909,7 @@ Use 64-bit process for code analysis (requires restart) - Use 64-bit process for code analysis (requires restart) + Pro analýzu kódu použít 64bitový proces (vyžaduje restartování) @@ -1109,12 +1109,12 @@ [generated by {0}] - [generated by {0}] + [vygenerováno pomocí {0}] {0} is the name of a generator. [generated] - [generated] + [vygenerováno] diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.de.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.de.xlf index 11b91f7d3cebd..4322be404c217 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.de.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.de.xlf @@ -94,12 +94,12 @@ 32-bit - 32-bit + 32 Bit 64-bit - 64-bit + 64 Bit @@ -109,7 +109,7 @@ C#/Visual Basic Diagnostics Language Client - C#/Visual Basic Diagnostics Language Client + Client für C#-/Visual Basic-Diagnosesprache @@ -154,7 +154,7 @@ Color hints - Color hints + Farbhinweise @@ -164,7 +164,7 @@ Comments - Comments + Kommentare @@ -189,17 +189,17 @@ Display all hints while pressing Alt+F1 - Display all hints while pressing Alt+F1 + Alle Hinweise beim Drücken von ALT+F1 anzeigen Disp_lay inline parameter name hints - Disp_lay inline parameter name hints + Hinweise zu In_lineparameternamen anzeigen Display inline type hints - Display inline type hints + Inlinetyphinweise anzeigen @@ -229,12 +229,12 @@ Enable Razor 'pull' diagnostics (experimental, requires restart) - Enable Razor 'pull' diagnostics (experimental, requires restart) + Razor-Pull-Diagnose aktivieren (experimentell, Neustart erforderlich) Enable 'pull' diagnostics (experimental, requires restart) - Enable 'pull' diagnostics (experimental, requires restart) + Pull-Diagnose aktivieren (experimentell, Neustart erforderlich) @@ -259,7 +259,7 @@ Extract Base Class - Extract Base Class + Basisklasse extrahieren @@ -304,7 +304,7 @@ Inline Hints (experimental) - Inline Hints (experimental) + Inlinehinweise (experimentell) @@ -399,12 +399,12 @@ Name conflicts with an existing type name. - Name conflicts with an existing type name. + Der Name verursacht einen Konflikt mit einem vorhandenen Typnamen. Name is not a valid {0} identifier. - Name is not a valid {0} identifier. + Der Name ist kein gültiger {0}-Bezeichner. @@ -569,7 +569,7 @@ New Type Name: - New Type Name: + Neuer Typname: @@ -814,22 +814,22 @@ Show hints for everything else - Show hints for everything else + Hinweise für alles andere anzeigen Show hints for lambda parameter types - Show hints for lambda parameter types + Hinweise für Lambda-Parametertypen anzeigen Show hints for literals - Show hints for literals + Hinweise für Literale anzeigen Show hints for variables with inferred types - Show hints for variables with inferred types + Hinweise für Variablen mit abgeleiteten Typen anzeigen @@ -839,12 +839,12 @@ Suppress hints when parameter name matches the method's intent - Suppress hints when parameter name matches the method's intent + Hinweise unterdrücken, wenn der Parametername mit der Methodenabsicht übereinstimmt Suppress hints when parameter names differ only by suffix - Suppress hints when parameter names differ only by suffix + Hinweise unterdrücken, wenn sich Parameternamen nur durch das Suffix unterscheiden @@ -854,17 +854,17 @@ The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. - The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. + Der Generator "{0}", der diese Datei generiert hat, wurde aus dem Projekt entfernt. Diese Datei wird nicht mehr in Ihr Projekt einbezogen. The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. - The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. + Der Generator "{0}" hat diese Datei nicht vollständig generiert. Diese Datei wird nicht mehr in Ihr Projekt einbezogen. This file is auto-generated by the generator '{0}' and cannot be edited. - This file is auto-generated by the generator '{0}' and cannot be edited. + Diese Datei wird automatisch vom Generator "{0}" generiert und kann nicht bearbeitet werden. @@ -909,7 +909,7 @@ Use 64-bit process for code analysis (requires restart) - Use 64-bit process for code analysis (requires restart) + 64-Bit-Prozess für die Codeanalyse verwenden (Neustart erforderlich) @@ -1109,12 +1109,12 @@ [generated by {0}] - [generated by {0}] + [generiert von "{0}"] {0} is the name of a generator. [generated] - [generated] + [generiert] @@ -2358,15 +2358,15 @@ You acknowledge that binary code and source code might be protected by copyright Your use of the Decompiler is optional. Microsoft is not responsible and disclaims all liability for your use of the Decompiler that violates any laws or any software license terms which prohibit decompiling of the software. I agree to all of the foregoing: - IMPORTANT: Visual Studio includes decompiling functionality (“Decompiler”) that enables reproducing source code from binary code. By accessing and using the Decompiler, you agree to the Visual Studio license terms and the terms for the Decompiler below. If you do not agree with these combined terms, do not access or use the Decompiler. + WICHTIG: Visual Studio umfasst eine Funktionalität für die Dekompilierung ("Decompiler"), mit der Quellcode aus Binärcode reproduziert werden kann. Indem Sie auf den Decompiler zugreifen und ihn verwenden, erklären Sie sich mit den Lizenzbedingungen von Visual Studio und den nachstehenden Bedingungen für den Decompiler einverstanden. Wenn Sie mit diesen kombinierten Bedingungen nicht einverstanden sind, dürfen Sie nicht auf den Decompiler zugreifen oder ihn verwenden. -You acknowledge that binary code and source code might be protected by copyright and trademark laws. Before using the Decompiler on any binary code, you need to first: -(i) confirm that the license terms governing your use of the binary code do not contain a provision which prohibits you from decompiling the software; or -(ii) obtain permission to decompile the binary code from the owner of the software. +Sie erkennen an, dass der Binärcode und der Quellcode möglicherweise durch Urheberrechts- und Markengesetze geschützt sind. Bevor Sie den Decompiler für Binärcode verwenden, müssen Sie zunächst Folgendes sicherstellen: +(i) Sie müssen sich vergewissern, dass die Lizenzbestimmungen zur Regelung Ihrer Verwendung des Binärcodes keine Klausel enthalten, die das Dekompilieren der Software verbietet, oder +(ii) Sie müssen die Erlaubnis zur Dekompilierung der Software beim Besitzer der Software einholen. -Your use of the Decompiler is optional. Microsoft is not responsible and disclaims all liability for your use of the Decompiler that violates any laws or any software license terms which prohibit decompiling of the software. +Ihre Verwendung des Decompilers ist optional. Microsoft übernimmt keinerlei Verantwortung und lehnt jede Haftung für Ihre Nutzung des Decompilers ab, die gegen Gesetze oder Softwarelizenzbedingungen verstößt, die das Dekompilieren der Software verbieten. -I agree to all of the foregoing: +Ich stimme allen oben genannten Punkten zu: diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.es.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.es.xlf index a6b629d7ad345..4e8d5bc657127 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.es.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.es.xlf @@ -94,12 +94,12 @@ 32-bit - 32-bit + 32 bits 64-bit - 64-bit + 64 bits @@ -109,7 +109,7 @@ C#/Visual Basic Diagnostics Language Client - C#/Visual Basic Diagnostics Language Client + Cliente de lenguaje de diagnóstico de C#/Visual Basic @@ -154,7 +154,7 @@ Color hints - Color hints + Sugerencias de color @@ -164,7 +164,7 @@ Comments - Comments + Comentarios @@ -189,17 +189,17 @@ Display all hints while pressing Alt+F1 - Display all hints while pressing Alt+F1 + Mostrar todas las sugerencias al presionar Alt+F1 Disp_lay inline parameter name hints - Disp_lay inline parameter name hints + _Mostrar sugerencias de nombre de parámetro insertadas Display inline type hints - Display inline type hints + Mostrar sugerencias de tipo insertado @@ -229,12 +229,12 @@ Enable Razor 'pull' diagnostics (experimental, requires restart) - Enable Razor 'pull' diagnostics (experimental, requires restart) + Habilitar diagnósticos "pull" de Razor (experimental, requiere reiniciar) Enable 'pull' diagnostics (experimental, requires restart) - Enable 'pull' diagnostics (experimental, requires restart) + Habilitar diagnósticos "pull" (experimental, requiere reiniciar) @@ -259,7 +259,7 @@ Extract Base Class - Extract Base Class + Extraer clase base @@ -304,7 +304,7 @@ Inline Hints (experimental) - Inline Hints (experimental) + Sugerencias en línea (experimental) @@ -399,12 +399,12 @@ Name conflicts with an existing type name. - Name conflicts with an existing type name. + El nombre está en conflicto con un nombre de tipo que ya existía. Name is not a valid {0} identifier. - Name is not a valid {0} identifier. + El nombre no es un identificador de {0} válido. @@ -569,7 +569,7 @@ New Type Name: - New Type Name: + Nombre de tipo nuevo: @@ -814,22 +814,22 @@ Show hints for everything else - Show hints for everything else + Mostrar sugerencias para todo lo demás Show hints for lambda parameter types - Show hints for lambda parameter types + Mostrar sugerencias para los tipos de parámetros lambda Show hints for literals - Show hints for literals + Mostrar sugerencias para los literales Show hints for variables with inferred types - Show hints for variables with inferred types + Mostrar sugerencias para las variables con tipos inferidos @@ -839,12 +839,12 @@ Suppress hints when parameter name matches the method's intent - Suppress hints when parameter name matches the method's intent + Suprimir las sugerencias cuando el nombre del parámetro coincida con la intención del método Suppress hints when parameter names differ only by suffix - Suppress hints when parameter names differ only by suffix + Suprimir las sugerencias cuando los nombres de parámetro solo se diferencien por el sufijo @@ -854,17 +854,17 @@ The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. - The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. + El generador "{0}" que creó este archivo se ha quitado del proyecto; el archivo ya no se incluye en el proyecto. The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. - The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. + El generador "{0}" que creaba este archivo ha dejado de generarlo; el archivo ya no se incluye en el proyecto. This file is auto-generated by the generator '{0}' and cannot be edited. - This file is auto-generated by the generator '{0}' and cannot be edited. + El generador "{0}" crea este archivo de forma automática y no se puede editar. @@ -909,7 +909,7 @@ Use 64-bit process for code analysis (requires restart) - Use 64-bit process for code analysis (requires restart) + Usar el proceso de 64 bits para el análisis de código (requiere reiniciar) @@ -1109,12 +1109,12 @@ [generated by {0}] - [generated by {0}] + [generado por {0}] {0} is the name of a generator. [generated] - [generated] + [generado] @@ -2358,15 +2358,15 @@ You acknowledge that binary code and source code might be protected by copyright Your use of the Decompiler is optional. Microsoft is not responsible and disclaims all liability for your use of the Decompiler that violates any laws or any software license terms which prohibit decompiling of the software. I agree to all of the foregoing: - IMPORTANT: Visual Studio includes decompiling functionality (“Decompiler”) that enables reproducing source code from binary code. By accessing and using the Decompiler, you agree to the Visual Studio license terms and the terms for the Decompiler below. If you do not agree with these combined terms, do not access or use the Decompiler. + IMPORTANTE: Visual Studio incluye la funcionalidad de descompilación ("Descompilador") que permite la reproducción de código fuente a partir de código binario. Al acceder al Descompilador y usarlo, acepta los términos de licencia de Visual Studio y los términos del Descompilador que figuran a continuación. Si no acepta la combinación de estos términos, no acceda al Descompilador ni lo use. + +Reconoce que el código binario y el código fuente pueden estar protegidos por leyes de marca comercial y copyright. Antes de usar el Descompilador en cualquier código binario, primero debe: +(i) confirmar que los términos de licencia que rigen el uso del código binario no incluyen ninguna disposición que le prohíba descompilar el software; o bien, +(ii) obtener permiso del propietario del software para descompilar el código fuente. -You acknowledge that binary code and source code might be protected by copyright and trademark laws. Before using the Decompiler on any binary code, you need to first: -(i) confirm that the license terms governing your use of the binary code do not contain a provision which prohibits you from decompiling the software; or -(ii) obtain permission to decompile the binary code from the owner of the software. - -Your use of the Decompiler is optional. Microsoft is not responsible and disclaims all liability for your use of the Decompiler that violates any laws or any software license terms which prohibit decompiling of the software. +Su uso del Descompilador es opcional. Microsoft no es responsable y renuncia a toda responsabilidad con respecto a su uso del Descompilador que infrinja cualquier ley o término de licencia de software que prohíba la descompilación del mismo. -I agree to all of the foregoing: +Acepto todo lo anterior: diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.fr.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.fr.xlf index 4c6d15e02a486..7c748fbf02ca1 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.fr.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.fr.xlf @@ -94,12 +94,12 @@ 32-bit - 32-bit + 32 bits 64-bit - 64-bit + 64 bits @@ -109,7 +109,7 @@ C#/Visual Basic Diagnostics Language Client - C#/Visual Basic Diagnostics Language Client + Client de langage de diagnostics C#/Visual Basic @@ -154,7 +154,7 @@ Color hints - Color hints + Indicateurs de couleurs @@ -164,7 +164,7 @@ Comments - Comments + Commentaires @@ -189,17 +189,17 @@ Display all hints while pressing Alt+F1 - Display all hints while pressing Alt+F1 + Afficher tous les indicateurs en appuyant sur Alt+F1 Disp_lay inline parameter name hints - Disp_lay inline parameter name hints + Affic_her les indicateurs de noms de paramètres inline Display inline type hints - Display inline type hints + Afficher les indicateurs de type inline @@ -229,12 +229,12 @@ Enable Razor 'pull' diagnostics (experimental, requires restart) - Enable Razor 'pull' diagnostics (experimental, requires restart) + Activer les diagnostics de 'tirage (pull)' Razor (expérimental, nécessite un redémarrage) Enable 'pull' diagnostics (experimental, requires restart) - Enable 'pull' diagnostics (experimental, requires restart) + Activer les diagnostics de 'tirage (pull)' (expérimental, nécessite un redémarrage) @@ -259,7 +259,7 @@ Extract Base Class - Extract Base Class + Extraire la classe de base @@ -304,7 +304,7 @@ Inline Hints (experimental) - Inline Hints (experimental) + Indicateurs inline (expérimental) @@ -399,12 +399,12 @@ Name conflicts with an existing type name. - Name conflicts with an existing type name. + Le nom est en conflit avec un nom de type existant. Name is not a valid {0} identifier. - Name is not a valid {0} identifier. + Le nom n'est pas un identificateur {0} valide. @@ -569,7 +569,7 @@ New Type Name: - New Type Name: + Nouveau nom de type : @@ -814,22 +814,22 @@ Show hints for everything else - Show hints for everything else + Afficher les indicateurs pour tout le reste Show hints for lambda parameter types - Show hints for lambda parameter types + Afficher les indicateurs pour les types de paramètre lambda Show hints for literals - Show hints for literals + Afficher les indicateurs pour les littéraux Show hints for variables with inferred types - Show hints for variables with inferred types + Afficher les indicateurs pour les variables ayant des types déduits @@ -839,12 +839,12 @@ Suppress hints when parameter name matches the method's intent - Suppress hints when parameter name matches the method's intent + Supprimer les indicateurs quand le nom de paramètre correspond à l'intention de la méthode Suppress hints when parameter names differ only by suffix - Suppress hints when parameter names differ only by suffix + Supprimer les indicateurs quand les noms de paramètres ne diffèrent que par le suffixe @@ -854,17 +854,17 @@ The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. - The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. + Le générateur '{0}' qui a généré ce fichier a été supprimé du projet. Ce fichier n'est plus inclus dans votre projet. The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. - The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. + Le générateur '{0}' qui a généré ce fichier a arrêté de générer ce dernier. Le fichier n'est plus inclus dans votre projet. This file is auto-generated by the generator '{0}' and cannot be edited. - This file is auto-generated by the generator '{0}' and cannot be edited. + Ce fichier est généré automatiquement par le générateur '{0}' et ne peut pas être modifié. @@ -909,7 +909,7 @@ Use 64-bit process for code analysis (requires restart) - Use 64-bit process for code analysis (requires restart) + Utiliser le processus 64 bits pour l'analyse du code (redémarrage nécessaire) @@ -1109,12 +1109,12 @@ [generated by {0}] - [generated by {0}] + [généré par {0}] {0} is the name of a generator. [generated] - [generated] + [généré] @@ -2358,15 +2358,15 @@ You acknowledge that binary code and source code might be protected by copyright Your use of the Decompiler is optional. Microsoft is not responsible and disclaims all liability for your use of the Decompiler that violates any laws or any software license terms which prohibit decompiling of the software. I agree to all of the foregoing: - IMPORTANT: Visual Studio includes decompiling functionality (“Decompiler”) that enables reproducing source code from binary code. By accessing and using the Decompiler, you agree to the Visual Studio license terms and the terms for the Decompiler below. If you do not agree with these combined terms, do not access or use the Decompiler. + IMPORTANT : Visual Studio inclut une fonctionnalité de décompilation ("Décompileur") qui permet de reproduire du code source à partir de code binaire. En accédant au Décompileur et en l'utilisant, vous acceptez les termes du contrat de licence Visual Studio et les termes du Décompileur ci-dessous. Si vous n'êtes pas d'accord avec ces termes combinés, n'accédez pas au Décompileur et ne l'utilisez pas. -You acknowledge that binary code and source code might be protected by copyright and trademark laws. Before using the Decompiler on any binary code, you need to first: -(i) confirm that the license terms governing your use of the binary code do not contain a provision which prohibits you from decompiling the software; or -(ii) obtain permission to decompile the binary code from the owner of the software. +Vous reconnaissez que le code binaire et le code source peuvent être protégés par des lois sur les droits d'auteur et le droit des marques. Avant d'utiliser le Décompileur sur du code binaire, vous devez d'abord : +(i) confirmer que les termes du contrat de licence régissant votre utilisation du code binaire ne contiennent aucune disposition vous interdisant de décompiler le logiciel ; ou +(ii) obtenir l'autorisation de décompiler le code binaire auprès du propriétaire du logiciel. -Your use of the Decompiler is optional. Microsoft is not responsible and disclaims all liability for your use of the Decompiler that violates any laws or any software license terms which prohibit decompiling of the software. +Votre utilisation du Décompileur est facultative. Microsoft n'accepte aucune responsabilité et décline toute obligation relative à votre utilisation du Décompileur si vous transgressez les lois ou les termes du contrat de licence du logiciel interdisant la décompilation du logiciel. -I agree to all of the foregoing: +Je suis d'accord avec tout ce qui précède : diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.it.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.it.xlf index 7e0359c6f45d0..9b69608c76986 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.it.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.it.xlf @@ -94,12 +94,12 @@ 32-bit - 32-bit + 32 bit 64-bit - 64-bit + 64 bit @@ -109,7 +109,7 @@ C#/Visual Basic Diagnostics Language Client - C#/Visual Basic Diagnostics Language Client + Client del linguaggio di diagnostica C#/Visual Basic @@ -154,7 +154,7 @@ Color hints - Color hints + Suggerimenti per i colori @@ -164,7 +164,7 @@ Comments - Comments + Commenti @@ -189,17 +189,17 @@ Display all hints while pressing Alt+F1 - Display all hints while pressing Alt+F1 + Visualizza tutti i suggerimenti quando si preme ALT+F1 Disp_lay inline parameter name hints - Disp_lay inline parameter name hints + Visua_lizza suggerimenti per i nomi di parametro inline Display inline type hints - Display inline type hints + Visualizza suggerimenti di tipo inline @@ -229,12 +229,12 @@ Enable Razor 'pull' diagnostics (experimental, requires restart) - Enable Razor 'pull' diagnostics (experimental, requires restart) + Abilita diagnostica 'pull' di Razor (sperimentale, richiede il riavvio) Enable 'pull' diagnostics (experimental, requires restart) - Enable 'pull' diagnostics (experimental, requires restart) + Abilita diagnostica 'pull' (sperimentale, richiede il riavvio) @@ -259,7 +259,7 @@ Extract Base Class - Extract Base Class + Estrai classe di base @@ -304,7 +304,7 @@ Inline Hints (experimental) - Inline Hints (experimental) + Suggerimenti inline (sperimentale) @@ -399,12 +399,12 @@ Name conflicts with an existing type name. - Name conflicts with an existing type name. + Il nome è in conflitto con un nome di tipo esistente. Name is not a valid {0} identifier. - Name is not a valid {0} identifier. + Il nome non è un identificatore {0} valido. @@ -569,7 +569,7 @@ New Type Name: - New Type Name: + Nuovo nome di tipo: @@ -814,22 +814,22 @@ Show hints for everything else - Show hints for everything else + Mostra suggerimenti per tutto il resto Show hints for lambda parameter types - Show hints for lambda parameter types + Mostra suggerimenti per i tipi di parametro lambda Show hints for literals - Show hints for literals + Mostra suggerimenti per i valori letterali Show hints for variables with inferred types - Show hints for variables with inferred types + Mostra suggerimenti per variabili con tipi dedotti @@ -839,12 +839,12 @@ Suppress hints when parameter name matches the method's intent - Suppress hints when parameter name matches the method's intent + Non visualizzare suggerimenti quando il nome del parametro corrisponde alla finalità del metodo Suppress hints when parameter names differ only by suffix - Suppress hints when parameter names differ only by suffix + Non visualizzare suggerimenti quando i nomi dei parametri differiscono solo per il suffisso @@ -854,17 +854,17 @@ The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. - The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. + Il generatore '{0}' che ha generato questo file è stato rimosso dal progetto. Questo file non è più incluso nel progetto. The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. - The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. + Il generatore '{0}' che ha generato questo file non genera più il file. Questo file non è più incluso nel progetto. This file is auto-generated by the generator '{0}' and cannot be edited. - This file is auto-generated by the generator '{0}' and cannot be edited. + Questo file è stato generato automaticamente dal generatore '{0}' e non è modificabile. @@ -909,7 +909,7 @@ Use 64-bit process for code analysis (requires restart) - Use 64-bit process for code analysis (requires restart) + Usa il processo a 64 bit per l'analisi codice (richiede il riavvio) @@ -1109,12 +1109,12 @@ [generated by {0}] - [generated by {0}] + [generato da {0}] {0} is the name of a generator. [generated] - [generated] + [generato] @@ -1174,7 +1174,7 @@ Could not find project '{0}' - Il progetto '{0}' non è stato trovato. + Il progetto '{0}' non è stato trovato @@ -2358,15 +2358,15 @@ You acknowledge that binary code and source code might be protected by copyright Your use of the Decompiler is optional. Microsoft is not responsible and disclaims all liability for your use of the Decompiler that violates any laws or any software license terms which prohibit decompiling of the software. I agree to all of the foregoing: - IMPORTANT: Visual Studio includes decompiling functionality (“Decompiler”) that enables reproducing source code from binary code. By accessing and using the Decompiler, you agree to the Visual Studio license terms and the terms for the Decompiler below. If you do not agree with these combined terms, do not access or use the Decompiler. + IMPORTANTE: Visual Studio include la funzionalità di decompilazione ("Decompilatore") che consente di riprodurre codice sorgente da codice binario. L'accesso e l'uso del Decompilatore implica l'accettazione dei termini della licenza di Visual Studio e delle condizioni per l'uso del Decompilatore riportate di seguito. Se non si accettano tali termini e condizioni, non accedere o usare il Decompilatore. -You acknowledge that binary code and source code might be protected by copyright and trademark laws. Before using the Decompiler on any binary code, you need to first: -(i) confirm that the license terms governing your use of the binary code do not contain a provision which prohibits you from decompiling the software; or -(ii) obtain permission to decompile the binary code from the owner of the software. +L'utente riconosce che il codice binario e il codice sorgente potrebbero essere protetti dalle normative su marchi e copyright. Prima di usare il Decompilatore su qualsiasi codice binario, l'utente deve: +(i) confermare che i termini della licenza che regolano l'uso del codice binario non contengono una disposizione che impedisce la decompilazione del software; oppure +(ii) ottenere l'autorizzazione alla decompilazione del codice binario dal proprietario del software. -Your use of the Decompiler is optional. Microsoft is not responsible and disclaims all liability for your use of the Decompiler that violates any laws or any software license terms which prohibit decompiling of the software. +L'uso del Decompilatore è facoltativo. Microsoft non è responsabile e non riconosce alcuna responsabilità nel caso in cui l'utente usi il Decompilatore in violazione di normative o termini della licenza software che proibiscono la decompilazione del software. -I agree to all of the foregoing: +L'utente accetta le condizioni sopra riportate: diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.ja.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.ja.xlf index 98fd2e646fc84..35af8afd651e6 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.ja.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.ja.xlf @@ -94,12 +94,12 @@ 32-bit - 32-bit + 32 ビット 64-bit - 64-bit + 64 ビット @@ -109,7 +109,7 @@ C#/Visual Basic Diagnostics Language Client - C#/Visual Basic Diagnostics Language Client + C#/Visual Basic 診断言語クライアント @@ -154,7 +154,7 @@ Color hints - Color hints + 色のヒント @@ -164,7 +164,7 @@ Comments - Comments + コメント @@ -189,17 +189,17 @@ Display all hints while pressing Alt+F1 - Display all hints while pressing Alt+F1 + Alt+F1 を押しながらすべてのヒントを表示する Disp_lay inline parameter name hints - Disp_lay inline parameter name hints + インライン パラメーター名のヒントを表示する(_L) Display inline type hints - Display inline type hints + インライン型のヒントを表示する @@ -229,12 +229,12 @@ Enable Razor 'pull' diagnostics (experimental, requires restart) - Enable Razor 'pull' diagnostics (experimental, requires restart) + Razor 'pull' 診断を有効にする (試験段階、再起動が必要) Enable 'pull' diagnostics (experimental, requires restart) - Enable 'pull' diagnostics (experimental, requires restart) + 'pull' 診断を有効にする (試験段階、再起動が必要) @@ -259,7 +259,7 @@ Extract Base Class - Extract Base Class + 基底クラスの抽出 @@ -304,7 +304,7 @@ Inline Hints (experimental) - Inline Hints (experimental) + インラインのヒント (試験段階) @@ -399,12 +399,12 @@ Name conflicts with an existing type name. - Name conflicts with an existing type name. + 名前が既存の型名と競合します。 Name is not a valid {0} identifier. - Name is not a valid {0} identifier. + 名前が有効な {0} 識別子ではありません。 @@ -569,7 +569,7 @@ New Type Name: - New Type Name: + 新しい型名: @@ -814,22 +814,22 @@ Show hints for everything else - Show hints for everything else + その他すべてのヒントを表示する Show hints for lambda parameter types - Show hints for lambda parameter types + ラムダ パラメーター型のヒントを表示する Show hints for literals - Show hints for literals + リテラルのヒントを表示する Show hints for variables with inferred types - Show hints for variables with inferred types + 推論された型の変数のヒントを表示する @@ -839,12 +839,12 @@ Suppress hints when parameter name matches the method's intent - Suppress hints when parameter name matches the method's intent + パラメーター名がメソッドの意図と一致する場合にヒントを非表示にする Suppress hints when parameter names differ only by suffix - Suppress hints when parameter names differ only by suffix + パラメーター名のサフィックスのみが異なる場合にヒントを非表示にする @@ -854,17 +854,17 @@ The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. - The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. + このファイルの生成元であるジェネレーター '{0}' がプロジェクトから削除されました。このファイルはもうプロジェクトに含まれていません。 The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. - The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. + このファイルの生成元であるジェネレーター '{0}' で、このファイルの生成が停止しました。このファイルはもうプロジェクトに含まれていません。 This file is auto-generated by the generator '{0}' and cannot be edited. - This file is auto-generated by the generator '{0}' and cannot be edited. + このファイルはジェネレーター '{0}' によって自動生成されているため、編集できません。 @@ -909,7 +909,7 @@ Use 64-bit process for code analysis (requires restart) - Use 64-bit process for code analysis (requires restart) + コード分析に 64 ビット プロセスを使用する (再起動が必要) @@ -1109,12 +1109,12 @@ [generated by {0}] - [generated by {0}] + [{0} により生成] {0} is the name of a generator. [generated] - [generated] + [生成] @@ -1616,12 +1616,12 @@ Use the dropdown to view and switch to other projects this file may belong to. Installing '{0}' - {0}' をインストールしています + '{0}' をインストールしています Installing '{0}' completed - {0}' のインストールが完了しました + '{0}' のインストールが完了しました @@ -1801,22 +1801,22 @@ Use the dropdown to view and switch to other projects this file may belong to. Install '{0}' - {0}' をインストールする + '{0}' をインストールする Uninstalling '{0}' - {0}' アンインストールしています + '{0}' アンインストールしています Uninstalling '{0}' completed - {0}' のアンインストールが完了しました + '{0}' のアンインストールが完了しました Uninstall '{0}' - {0}' をアンインストールする + '{0}' をアンインストールする @@ -1864,7 +1864,7 @@ Use the dropdown to view and switch to other projects this file may belong to.Installing '{0}' failed. Additional information: {1} - {0}' をインストールできませんでした。 + '{0}' をインストールできませんでした。 追加情報: {1} @@ -1873,7 +1873,7 @@ Additional information: {1} Uninstalling '{0}' failed. Additional information: {1} - {0}' をアンインストールできませんでした。 + '{0}' をアンインストールできませんでした。 追加情報: {1} @@ -2175,7 +2175,7 @@ Additional information: {1} Get help for '{0}' - {0}' のヘルプの表示 + '{0}' のヘルプの表示 @@ -2320,7 +2320,7 @@ Additional information: {1} No references found to '{0}' - {0}' の参照は見つかりませんでした + '{0}' の参照は見つかりませんでした @@ -2358,15 +2358,15 @@ You acknowledge that binary code and source code might be protected by copyright Your use of the Decompiler is optional. Microsoft is not responsible and disclaims all liability for your use of the Decompiler that violates any laws or any software license terms which prohibit decompiling of the software. I agree to all of the foregoing: - IMPORTANT: Visual Studio includes decompiling functionality (“Decompiler”) that enables reproducing source code from binary code. By accessing and using the Decompiler, you agree to the Visual Studio license terms and the terms for the Decompiler below. If you do not agree with these combined terms, do not access or use the Decompiler. + 重要: Visual Studio には、逆コンパイル機能 (“デコンパイラ”) が含まれています。これは、バイナリ コードからのソース コードの再生成を可能にする機能です。デコンパイラにアクセスしてこれを使用することで、Visual Studio のライセンス条項とデコンパイラに関する以下の条項に同意したことになります。ここでまとめられている条項に同意しない場合は、デコンパイラへのアクセスも使用も行わないでください。 -You acknowledge that binary code and source code might be protected by copyright and trademark laws. Before using the Decompiler on any binary code, you need to first: -(i) confirm that the license terms governing your use of the binary code do not contain a provision which prohibits you from decompiling the software; or -(ii) obtain permission to decompile the binary code from the owner of the software. +バイナリ コードとソース コードが著作権と商標に関する法律によって保護されている可能性があることに同意します。バイナリ コードに対してデコンパイラを使用する前に、次のことを行う必要があります: +(i) バイナリ コードの使用を管理するライセンス条項にソフトウェアのデコンパイルを禁止する規定が含まれていないことを確認する。または +(ii) バイナリ コードをデコンパイルするための許可をソフトウェアの所有者から取得する。 -Your use of the Decompiler is optional. Microsoft is not responsible and disclaims all liability for your use of the Decompiler that violates any laws or any software license terms which prohibit decompiling of the software. +デコンパイラの使用は任意です。ソフトウェアの逆コンパイルを禁止する法律またはソフトウェア ライセンス条項に違反するデコンパイラの使用に関して、Microsoft は一切責任を負わず、一切保証いたしません。 -I agree to all of the foregoing: +上記の内容にすべて同意します: diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.ko.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.ko.xlf index 64000c1af8100..bf5dbf830514a 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.ko.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.ko.xlf @@ -94,12 +94,12 @@ 32-bit - 32-bit + 32비트 64-bit - 64-bit + 64비트 @@ -109,7 +109,7 @@ C#/Visual Basic Diagnostics Language Client - C#/Visual Basic Diagnostics Language Client + C#/Visual Basic 진단 언어 클라이언트 @@ -154,7 +154,7 @@ Color hints - Color hints + 색 힌트 @@ -164,7 +164,7 @@ Comments - Comments + 설명 @@ -189,17 +189,17 @@ Display all hints while pressing Alt+F1 - Display all hints while pressing Alt+F1 + Alt+F1을 누른 채 모든 힌트 표시 Disp_lay inline parameter name hints - Disp_lay inline parameter name hints + 인라인 매개 변수 이름 힌트 표시(_L) Display inline type hints - Display inline type hints + 인라인 유형 힌트 표시 @@ -229,12 +229,12 @@ Enable Razor 'pull' diagnostics (experimental, requires restart) - Enable Razor 'pull' diagnostics (experimental, requires restart) + Razor '풀' 진단 사용(실험적, 다시 시작 필요) Enable 'pull' diagnostics (experimental, requires restart) - Enable 'pull' diagnostics (experimental, requires restart) + '풀' 진단 사용(실험적, 다시 시작 필요) @@ -259,7 +259,7 @@ Extract Base Class - Extract Base Class + 기본 클래스 추출 @@ -304,7 +304,7 @@ Inline Hints (experimental) - Inline Hints (experimental) + 인라인 힌트(실험적) @@ -399,12 +399,12 @@ Name conflicts with an existing type name. - Name conflicts with an existing type name. + 이름이 기존 형식 이름과 충돌합니다. Name is not a valid {0} identifier. - Name is not a valid {0} identifier. + 이름이 유효한 {0} 식별자가 아닙니다. @@ -569,7 +569,7 @@ New Type Name: - New Type Name: + 새 형식 이름: @@ -814,22 +814,22 @@ Show hints for everything else - Show hints for everything else + 다른 모든 항목에 대한 힌트 표시 Show hints for lambda parameter types - Show hints for lambda parameter types + 람다 매개 변수 형식에 대한 힌트 표시 Show hints for literals - Show hints for literals + 리터럴에 대한 힌트 표시 Show hints for variables with inferred types - Show hints for variables with inferred types + 유추된 형식의 변수에 대한 힌트 표시 @@ -839,12 +839,12 @@ Suppress hints when parameter name matches the method's intent - Suppress hints when parameter name matches the method's intent + 매개 변수 이름이 메서드의 의도와 일치하는 경우 힌트 표시 안 함 Suppress hints when parameter names differ only by suffix - Suppress hints when parameter names differ only by suffix + 매개 변수 이름이 접미사만 다른 경우 힌트 표시 안 함 @@ -854,17 +854,17 @@ The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. - The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. + 이 파일을 생성한 생성기 '{0}'이(가) 프로젝트에서 제거되었습니다. 이 파일은 프로젝트에 더 이상 포함되지 않습니다. The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. - The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. + 이 파일을 생성한 생성기 '{0}'이(가) 이 파일 생성을 중지했습니다. 이 파일은 프로젝트에 더 이상 포함되지 않습니다. This file is auto-generated by the generator '{0}' and cannot be edited. - This file is auto-generated by the generator '{0}' and cannot be edited. + 이 파일은 생성기 '{0}'(으)로 자동 생성되며 편집할 수 없습니다. @@ -909,7 +909,7 @@ Use 64-bit process for code analysis (requires restart) - Use 64-bit process for code analysis (requires restart) + 코드 분석에 64비트 프로세스 사용(다시 시작 필요) @@ -1109,12 +1109,12 @@ [generated by {0}] - [generated by {0}] + [{0}이(가) 생성함] {0} is the name of a generator. [generated] - [generated] + [생성됨] @@ -1124,7 +1124,7 @@ Add a reference to '{0}' - {0}'에 참조 추가 + '{0}'에 참조 추가 @@ -1154,7 +1154,7 @@ Can't create a node id for this symbol kind: '{0}' - {0}' 기호 종류에 대한 노드 ID를 만들 수 없습니다. + '{0}' 기호 종류에 대한 노드 ID를 만들 수 없습니다. @@ -1174,7 +1174,7 @@ Could not find project '{0}' - {0}' 프로젝트를 찾을 수 없습니다. + '{0}' 프로젝트를 찾을 수 없습니다. @@ -1496,7 +1496,7 @@ Use the dropdown to view and switch to other projects this file may belong to. Analyzer assemblies '{0}' and '{1}' both have identity '{2}' but different contents. Only one will be loaded and analyzers using these assemblies may not run correctly. - {0}' 및 '{1}' 분석기 어셈블리의 ID는 '{2}'(으)로 동일하지만 콘텐츠가 다릅니다. 둘 중 하나만 로드되며 이러한 어셈블리를 사용하는 분석기는 제대로 실행되지 않을 수 있습니다. + '{0}' 및 '{1}' 분석기 어셈블리의 ID는 '{2}'(으)로 동일하지만 콘텐츠가 다릅니다. 둘 중 하나만 로드되며 이러한 어셈블리를 사용하는 분석기는 제대로 실행되지 않을 수 있습니다. @@ -1616,12 +1616,12 @@ Use the dropdown to view and switch to other projects this file may belong to. Installing '{0}' - {0}' 설치 중 + '{0}' 설치 중 Installing '{0}' completed - {0}' 설치 완료 + '{0}' 설치 완료 @@ -1801,22 +1801,22 @@ Use the dropdown to view and switch to other projects this file may belong to. Install '{0}' - {0}' 설치 + '{0}' 설치 Uninstalling '{0}' - {0}' 제거 중 + '{0}' 제거 중 Uninstalling '{0}' completed - {0}' 제거 완료 + '{0}' 제거 완료 Uninstall '{0}' - {0}' 제거 + '{0}' 제거 @@ -1864,7 +1864,7 @@ Use the dropdown to view and switch to other projects this file may belong to.Installing '{0}' failed. Additional information: {1} - {0}'을(를) 설치하지 못했습니다. + '{0}'을(를) 설치하지 못했습니다. 추가 정보: {1} @@ -1873,7 +1873,7 @@ Additional information: {1} Uninstalling '{0}' failed. Additional information: {1} - {0}'을(를) 제거하지 못했습니다. + '{0}'을(를) 제거하지 못했습니다. 추가 정보: {1} @@ -2175,7 +2175,7 @@ Additional information: {1} Get help for '{0}' - {0}'에 대한 도움 받기 + '{0}'에 대한 도움 받기 @@ -2320,7 +2320,7 @@ Additional information: {1} No references found to '{0}' - {0}'에 대한 참조가 없습니다. + '{0}'에 대한 참조가 없습니다. @@ -2358,15 +2358,15 @@ You acknowledge that binary code and source code might be protected by copyright Your use of the Decompiler is optional. Microsoft is not responsible and disclaims all liability for your use of the Decompiler that violates any laws or any software license terms which prohibit decompiling of the software. I agree to all of the foregoing: - IMPORTANT: Visual Studio includes decompiling functionality (“Decompiler”) that enables reproducing source code from binary code. By accessing and using the Decompiler, you agree to the Visual Studio license terms and the terms for the Decompiler below. If you do not agree with these combined terms, do not access or use the Decompiler. - -You acknowledge that binary code and source code might be protected by copyright and trademark laws. Before using the Decompiler on any binary code, you need to first: -(i) confirm that the license terms governing your use of the binary code do not contain a provision which prohibits you from decompiling the software; or -(ii) obtain permission to decompile the binary code from the owner of the software. - -Your use of the Decompiler is optional. Microsoft is not responsible and disclaims all liability for your use of the Decompiler that violates any laws or any software license terms which prohibit decompiling of the software. + 중요: Visual Studio에는 이진 코드에서 소스 코드를 재생할 수 있는 디컴파일 기능("디컴파일러")이 포함됩니다. 디컴파일러에 액세스하고 사용함으로써 아래의 Visual Studio 라이선스 조건 및 디컴파일러 조건에 동의하게 됩니다. 이러한 결합된 조건에 동의하지 않는 경우 디컴파일러에 액세스하거나 사용하지 마세요. + +이진 코드 및 소스 코드는 저작권 및 상표법으로 보호될 수 있습니다. 이진 코드에 디컴파일러를 사용하기 전에 먼저 +(i) 이진 코드 사용과 관련된 라이선스 조건에 소프트웨어 디컴파일을 금지하는 조항이 포함되어 있지 않은지 확인하거나 +(ii) 소프트웨어 소유자에게 이진 코드 디컴파일 권한을 얻으세요. + +디컴파일 사용은 선택 사항입니다. Microsoft는 소프트웨어 디컴파일을 금지하는 법 또는 소프트웨어 라이선스 조건을 위반하는 디컴파일러 사용을 책임지지 않으며 이와 관련된 모든 책임을 부인합니다. -I agree to all of the foregoing: +본인은 상기 내용에 모두 동의합니다. diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.pl.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.pl.xlf index 05a9d16e231af..5cf9e0548fda2 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.pl.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.pl.xlf @@ -94,12 +94,12 @@ 32-bit - 32-bit + 32-bitowa 64-bit - 64-bit + 64-bitowa @@ -109,7 +109,7 @@ C#/Visual Basic Diagnostics Language Client - C#/Visual Basic Diagnostics Language Client + Klient języka diagnostyki języka C#/Visual Basic @@ -154,7 +154,7 @@ Color hints - Color hints + Wskazówki kolorów @@ -164,7 +164,7 @@ Comments - Comments + Komentarze @@ -189,17 +189,17 @@ Display all hints while pressing Alt+F1 - Display all hints while pressing Alt+F1 + Wyświetl wszystkie wskazówki po naciśnięciu klawiszy Alt+F1 Disp_lay inline parameter name hints - Disp_lay inline parameter name hints + Wyś_wietl wskazówki w tekście dla nazw parametrów Display inline type hints - Display inline type hints + Wyświetl wskazówki w tekście dla typów @@ -229,12 +229,12 @@ Enable Razor 'pull' diagnostics (experimental, requires restart) - Enable Razor 'pull' diagnostics (experimental, requires restart) + Włącz diagnostykę operacji „pull” oprogramowania Razor (eksperymentalne, wymaga ponownego uruchomienia) Enable 'pull' diagnostics (experimental, requires restart) - Enable 'pull' diagnostics (experimental, requires restart) + Włącz diagnostykę operacji „pull” (eksperymentalne, wymaga ponownego uruchomienia) @@ -259,7 +259,7 @@ Extract Base Class - Extract Base Class + Wyodrębnij klasę bazową @@ -304,7 +304,7 @@ Inline Hints (experimental) - Inline Hints (experimental) + Wskazówki w tekście (eksperymentalne) @@ -399,12 +399,12 @@ Name conflicts with an existing type name. - Name conflicts with an existing type name. + Wystąpił konflikt z nazwą istniejącego typu. Name is not a valid {0} identifier. - Name is not a valid {0} identifier. + Nazwa nie jest prawidłowym identyfikatorem {0}. @@ -569,7 +569,7 @@ New Type Name: - New Type Name: + Nazwa nowego typu: @@ -814,22 +814,22 @@ Show hints for everything else - Show hints for everything else + Pokaż wskazówki dla wszystkich innych elementów Show hints for lambda parameter types - Show hints for lambda parameter types + Pokaż wskazówki dla typów parametrów funkcji lambda Show hints for literals - Show hints for literals + Pokaż wskazówki dla literałów Show hints for variables with inferred types - Show hints for variables with inferred types + Pokaż wskazówki dla zmiennych z wnioskowanymi typami @@ -839,12 +839,12 @@ Suppress hints when parameter name matches the method's intent - Suppress hints when parameter name matches the method's intent + Pomiń wskazówki, gdy nazwa parametru pasuje do intencji metody Suppress hints when parameter names differ only by suffix - Suppress hints when parameter names differ only by suffix + Pomiń wskazówki, gdy nazwy parametrów różnią się tylko sufiksem @@ -854,17 +854,17 @@ The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. - The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. + Generator „{0}”, który wygenerował ten plik, został usunięty z projektu; ten plik nie jest już uwzględniany w Twoim projekcie. The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. - The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. + Generator „{0}”, który wygenerował ten plik, przestał generować ten plik; ten plik nie jest już uwzględniany w Twoim projekcie. This file is auto-generated by the generator '{0}' and cannot be edited. - This file is auto-generated by the generator '{0}' and cannot be edited. + Ten plik jest generowany automatycznie przez generator „{0}” i nie może być edytowany. @@ -909,7 +909,7 @@ Use 64-bit process for code analysis (requires restart) - Use 64-bit process for code analysis (requires restart) + Użyj procesu 64-bitowego do analizy kodu (wymaga ponownego uruchomienia) @@ -1109,12 +1109,12 @@ [generated by {0}] - [generated by {0}] + [wygenerowane przez: {0}] {0} is the name of a generator. [generated] - [generated] + [wygenerowane] @@ -2090,7 +2090,7 @@ Dodatkowe informacje: {1} Collapse #regions when collapsing to definitions - Zwiń bloki #region podczas zwijania do definicji + Zwiń bloki #regions podczas zwijania do definicji @@ -2358,15 +2358,15 @@ You acknowledge that binary code and source code might be protected by copyright Your use of the Decompiler is optional. Microsoft is not responsible and disclaims all liability for your use of the Decompiler that violates any laws or any software license terms which prohibit decompiling of the software. I agree to all of the foregoing: - IMPORTANT: Visual Studio includes decompiling functionality (“Decompiler”) that enables reproducing source code from binary code. By accessing and using the Decompiler, you agree to the Visual Studio license terms and the terms for the Decompiler below. If you do not agree with these combined terms, do not access or use the Decompiler. + WAŻNE: Program Visual Studio zawiera funkcję dekompilacji („Dekompilator”), która pozwala odtworzyć kod źródłowy na podstawie kodu binarnego. Otwierając Dekompilator i korzystając z niego, wyrażasz zgodę na postanowienia licencyjne programu Visual Studio i przedstawione niżej warunki dotyczące Dekompilatora. Jeśli nie zgadzasz się na połączenie tych warunków, nie otwieraj Dekompilatora i nie korzystaj z niego. -You acknowledge that binary code and source code might be protected by copyright and trademark laws. Before using the Decompiler on any binary code, you need to first: -(i) confirm that the license terms governing your use of the binary code do not contain a provision which prohibits you from decompiling the software; or -(ii) obtain permission to decompile the binary code from the owner of the software. +Potwierdzasz, że kod binarny i kod źródłowy mogą być chronione prawem autorskim i jako znak towarowy. Przed użyciem Dekompilatora na jakimkolwiek kodzie binarnym musisz najpierw: +(i) potwierdzić, że postanowienia licencyjne, na mocy których korzystasz z kodu binarnego, nie zawierają zapisów zabraniających dekompilowania tego oprogramowania; lub +(ii) uzyskać zgodę na dekompilację kodu binarnego od właściciela tego oprogramowania. -Your use of the Decompiler is optional. Microsoft is not responsible and disclaims all liability for your use of the Decompiler that violates any laws or any software license terms which prohibit decompiling of the software. +Korzystanie z Dekompilatora jest opcjonalne. Firma Microsoft nie odpowiada za takie użycie przez Ciebie Dekompilatora, które narusza jakiekolwiek prawo lub postanowienia licencyjne dotyczące oprogramowania zabraniające dekompilowania tego oprogramowania, i zrzeka się wszelkiej odpowiedzialności za nie. -I agree to all of the foregoing: +Wyrażam zgodę na wszystkie następujące postanowienia: diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.pt-BR.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.pt-BR.xlf index fde5f25394a99..93c0e217edd6f 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.pt-BR.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.pt-BR.xlf @@ -94,12 +94,12 @@ 32-bit - 32-bit + 32 bits 64-bit - 64-bit + 64 bits @@ -109,7 +109,7 @@ C#/Visual Basic Diagnostics Language Client - C#/Visual Basic Diagnostics Language Client + Cliente da Linguagem de Diagnóstico C#/Visual Basic @@ -154,7 +154,7 @@ Color hints - Color hints + Dicas com cores @@ -164,7 +164,7 @@ Comments - Comments + Comentários @@ -189,17 +189,17 @@ Display all hints while pressing Alt+F1 - Display all hints while pressing Alt+F1 + Exibir todas as dicas ao pressionar Alt+F1 Disp_lay inline parameter name hints - Disp_lay inline parameter name hints + Exi_bir as dicas embutidas de nome de parâmetro Display inline type hints - Display inline type hints + Exibir as dicas embutidas de tipo @@ -229,12 +229,12 @@ Enable Razor 'pull' diagnostics (experimental, requires restart) - Enable Razor 'pull' diagnostics (experimental, requires restart) + Habilitar o diagnóstico de 'pull' do Razor (experimental, exige uma reinicialização) Enable 'pull' diagnostics (experimental, requires restart) - Enable 'pull' diagnostics (experimental, requires restart) + Habilitar o diagnóstico de 'pull' (experimental, exige uma reinicialização) @@ -259,7 +259,7 @@ Extract Base Class - Extract Base Class + Extrair a Classe Base @@ -304,7 +304,7 @@ Inline Hints (experimental) - Inline Hints (experimental) + Dicas Embutidas (experimental) @@ -399,12 +399,12 @@ Name conflicts with an existing type name. - Name conflicts with an existing type name. + O nome está em conflito com um nome de tipo existente. Name is not a valid {0} identifier. - Name is not a valid {0} identifier. + O nome não é um identificador de {0} válido. @@ -474,7 +474,7 @@ property - Propriedade. + propriedade This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "property" (which allows for the retrieval of data). @@ -569,7 +569,7 @@ New Type Name: - New Type Name: + Novo Nome de Tipo: @@ -814,22 +814,22 @@ Show hints for everything else - Show hints for everything else + Mostrar as dicas para tudo Show hints for lambda parameter types - Show hints for lambda parameter types + Mostrar as dicas para os tipos de parâmetro lambda Show hints for literals - Show hints for literals + Mostrar as dicas para os literais Show hints for variables with inferred types - Show hints for variables with inferred types + Mostrar as dicas para as variáveis com tipos inferidos @@ -839,12 +839,12 @@ Suppress hints when parameter name matches the method's intent - Suppress hints when parameter name matches the method's intent + Suprimir as dicas quando o nome do parâmetro corresponder à intenção do método Suppress hints when parameter names differ only by suffix - Suppress hints when parameter names differ only by suffix + Suprimir as dicas quando os nomes de parâmetros diferirem somente pelo sufixo @@ -854,17 +854,17 @@ The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. - The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. + O gerador '{0}' que gerou esse arquivo foi removido do projeto. Esse arquivo não será mais incluído no projeto. The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. - The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. + O gerador '{0}' que gerou esse arquivo parou de gerá-lo. Esse arquivo não será mais incluído no projeto. This file is auto-generated by the generator '{0}' and cannot be edited. - This file is auto-generated by the generator '{0}' and cannot be edited. + Esse arquivo é gerado automaticamente pelo gerador '{0}' e não pode ser editado. @@ -909,7 +909,7 @@ Use 64-bit process for code analysis (requires restart) - Use 64-bit process for code analysis (requires restart) + Usar o processo de 64 bits para análise de código (requer reinicialização) @@ -1109,12 +1109,12 @@ [generated by {0}] - [generated by {0}] + [gerado por {0}] {0} is the name of a generator. [generated] - [generated] + [gerado] @@ -2358,15 +2358,15 @@ You acknowledge that binary code and source code might be protected by copyright Your use of the Decompiler is optional. Microsoft is not responsible and disclaims all liability for your use of the Decompiler that violates any laws or any software license terms which prohibit decompiling of the software. I agree to all of the foregoing: - IMPORTANT: Visual Studio includes decompiling functionality (“Decompiler”) that enables reproducing source code from binary code. By accessing and using the Decompiler, you agree to the Visual Studio license terms and the terms for the Decompiler below. If you do not agree with these combined terms, do not access or use the Decompiler. + IMPORTANTE: o Visual Studio inclui a funcionalidade de descompilação (“Descompilador”) que permite a reprodução do código-fonte usando código binário. Ao acessar e usar o Descompilador, você concorda com os termos de licença do Visual Studio e com os termos do Descompilador abaixo. Se você não concorda com esses termos combinados, não acesse nem use o Descompilador. + +Você reconhece que o código binário e o código-fonte podem estar protegidos por leis de direitos autorais e de marca. Antes de usar o Descompilador em qualquer código binário, você deve primeiro: +(i) confirmar que os termos da licença que regem o uso do código binário não contenham uma provisão que proíba você de descompilar o software; ou +(ii) obter permissão do proprietário do software para descompilar o código binário. + +O uso que você faz do Descompilador é opcional. A Microsoft não é responsável e isenta-se de toda obrigação referente ao uso que você faz do Descompilador em violação a alguma lei ou termo de licença do software que proíba a descompilação do software. -You acknowledge that binary code and source code might be protected by copyright and trademark laws. Before using the Decompiler on any binary code, you need to first: -(i) confirm that the license terms governing your use of the binary code do not contain a provision which prohibits you from decompiling the software; or -(ii) obtain permission to decompile the binary code from the owner of the software. - -Your use of the Decompiler is optional. Microsoft is not responsible and disclaims all liability for your use of the Decompiler that violates any laws or any software license terms which prohibit decompiling of the software. - -I agree to all of the foregoing: +Eu concordo com todo o conteúdo citado acima: diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.ru.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.ru.xlf index 6fbb7aceedb4c..0f1f090f80318 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.ru.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.ru.xlf @@ -94,12 +94,12 @@ 32-bit - 32-bit + 32-разрядный 64-bit - 64-bit + 64-разрядный @@ -109,7 +109,7 @@ C#/Visual Basic Diagnostics Language Client - C#/Visual Basic Diagnostics Language Client + Языковой клиент диагностики C#/Visual Basic @@ -154,7 +154,7 @@ Color hints - Color hints + Цветовые подсказки @@ -164,7 +164,7 @@ Comments - Comments + Комментарии @@ -189,17 +189,17 @@ Display all hints while pressing Alt+F1 - Display all hints while pressing Alt+F1 + Отображать все подсказки при нажатии клавиш ALT+F1 Disp_lay inline parameter name hints - Disp_lay inline parameter name hints + Отображать п_одсказки для имен встроенных параметров Display inline type hints - Display inline type hints + Отображать подсказки для встроенных типов @@ -229,12 +229,12 @@ Enable Razor 'pull' diagnostics (experimental, requires restart) - Enable Razor 'pull' diagnostics (experimental, requires restart) + Включить диагностику "pull" Razor (экспериментальная функция, требуется перезапуск) Enable 'pull' diagnostics (experimental, requires restart) - Enable 'pull' diagnostics (experimental, requires restart) + Включить диагностику "pull" (экспериментальная функция, требуется перезапуск) @@ -259,7 +259,7 @@ Extract Base Class - Extract Base Class + Извлечь базовый класс @@ -304,7 +304,7 @@ Inline Hints (experimental) - Inline Hints (experimental) + Встроенные подсказки (экспериментальная функция) @@ -399,12 +399,12 @@ Name conflicts with an existing type name. - Name conflicts with an existing type name. + Имя конфликтует с существующим именем типа. Name is not a valid {0} identifier. - Name is not a valid {0} identifier. + Имя не является допустимым идентификатором {0}. @@ -569,7 +569,7 @@ New Type Name: - New Type Name: + Новое имя типа: @@ -814,22 +814,22 @@ Show hints for everything else - Show hints for everything else + Отображать подсказки для всех остальных элементов Show hints for lambda parameter types - Show hints for lambda parameter types + Отображать подсказки для типов лямбда-параметров Show hints for literals - Show hints for literals + Отображать подсказки для литералов Show hints for variables with inferred types - Show hints for variables with inferred types + Отображать подсказки для переменных с выводимыми типами @@ -839,12 +839,12 @@ Suppress hints when parameter name matches the method's intent - Suppress hints when parameter name matches the method's intent + Скрывать подсказки, если имя параметра соответствует намерению метода. Suppress hints when parameter names differ only by suffix - Suppress hints when parameter names differ only by suffix + Скрывать подсказки, если имена параметров различаются только суффиксом. @@ -854,17 +854,17 @@ The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. - The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. + Генератор "{0}", создавший этот файл, был удален из проекта; этот файл больше не включен в проект. The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. - The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. + Генератор "{0}", создавший этот файл, остановил создание этого файла; этот файл больше не включен в проект. This file is auto-generated by the generator '{0}' and cannot be edited. - This file is auto-generated by the generator '{0}' and cannot be edited. + Этот файл создан автоматически генератором "{0}" и не может быть изменен. @@ -909,7 +909,7 @@ Use 64-bit process for code analysis (requires restart) - Use 64-bit process for code analysis (requires restart) + Использовать 64-разрядный процесс для анализа кода (требуется перезапуск) @@ -1109,12 +1109,12 @@ [generated by {0}] - [generated by {0}] + [создан генератором {0}] {0} is the name of a generator. [generated] - [generated] + [создан генератором] @@ -2358,15 +2358,15 @@ You acknowledge that binary code and source code might be protected by copyright Your use of the Decompiler is optional. Microsoft is not responsible and disclaims all liability for your use of the Decompiler that violates any laws or any software license terms which prohibit decompiling of the software. I agree to all of the foregoing: - IMPORTANT: Visual Studio includes decompiling functionality (“Decompiler”) that enables reproducing source code from binary code. By accessing and using the Decompiler, you agree to the Visual Studio license terms and the terms for the Decompiler below. If you do not agree with these combined terms, do not access or use the Decompiler. + ВАЖНО! Visual Studio включает в себя функцию декомпиляции ("декомпилятор"), позволяющую воспроизводить исходный код из двоичного. Открывая и используя декомпилятор, вы принимаете условия лицензионного соглашения Visual Studio, а также приведенные ниже условия для декомпилятора. Если вы не согласны с какими-либо из этих условий, не открывайте и не используйте декомпилятор. -You acknowledge that binary code and source code might be protected by copyright and trademark laws. Before using the Decompiler on any binary code, you need to first: -(i) confirm that the license terms governing your use of the binary code do not contain a provision which prohibits you from decompiling the software; or -(ii) obtain permission to decompile the binary code from the owner of the software. +Вы подтверждаете, что двоичный и исходный код может быть защищен законами об авторских правах и торговых марках. Прежде чем применять декомпилятор на любом двоичном коде, вам следует: +(i) убедиться, что условия лицензии, регулирующие использование вами этого двоичного кода, не содержат положение, запрещающее декомпиляцию данного программного обеспечения; или +(ii) получить разрешение на декомпиляцию этого двоичного кода у владельца соответствующего программного обеспечения. -Your use of the Decompiler is optional. Microsoft is not responsible and disclaims all liability for your use of the Decompiler that violates any laws or any software license terms which prohibit decompiling of the software. +Вы используете этот декомпилятор по собственной инициативе. Корпорация Майкрософт не несет ответственности за такое использование вами компилятора, которое нарушает любые законы или условия лицензионного соглашения на использование программного обеспечения, запрещающие декомпиляцию этого программного обеспечения. -I agree to all of the foregoing: +Я принимаю все указанные выше условия и положения: diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.tr.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.tr.xlf index 2d0ea3dfa5f14..155d5b20db467 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.tr.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.tr.xlf @@ -94,12 +94,12 @@ 32-bit - 32-bit + 32 bit 64-bit - 64-bit + 64 bit @@ -109,7 +109,7 @@ C#/Visual Basic Diagnostics Language Client - C#/Visual Basic Diagnostics Language Client + C#/Visual Basic Tanılama Dili İstemcisi @@ -154,7 +154,7 @@ Color hints - Color hints + Renk ipuçları @@ -164,7 +164,7 @@ Comments - Comments + Açıklamalar @@ -189,17 +189,17 @@ Display all hints while pressing Alt+F1 - Display all hints while pressing Alt+F1 + Alt+F1 tuşlarına basılırken tüm ipuçlarını görüntüle Disp_lay inline parameter name hints - Disp_lay inline parameter name hints + Satır içi parametre adı ipuç_larını göster Display inline type hints - Display inline type hints + Satır içi tür ipuçlarını göster @@ -229,12 +229,12 @@ Enable Razor 'pull' diagnostics (experimental, requires restart) - Enable Razor 'pull' diagnostics (experimental, requires restart) + Razor 'pull' tanılamasını etkinleştir (deneysel, yeniden başlatma gerekir) Enable 'pull' diagnostics (experimental, requires restart) - Enable 'pull' diagnostics (experimental, requires restart) + 'Pull' tanılamasını etkinleştir (deneysel, yeniden başlatma gerekir) @@ -259,7 +259,7 @@ Extract Base Class - Extract Base Class + Temel Sınıfı Ayıkla @@ -304,7 +304,7 @@ Inline Hints (experimental) - Inline Hints (experimental) + Satır İçi İpuçları (deneysel) @@ -399,12 +399,12 @@ Name conflicts with an existing type name. - Name conflicts with an existing type name. + Ad, mevcut bir tür adıyla çakışıyor. Name is not a valid {0} identifier. - Name is not a valid {0} identifier. + Ad geçerli bir {0} tanımlayıcısı değil. @@ -569,7 +569,7 @@ New Type Name: - New Type Name: + Yeni Tür Adı: @@ -814,22 +814,22 @@ Show hints for everything else - Show hints for everything else + Diğer her şey için ipuçlarını göster Show hints for lambda parameter types - Show hints for lambda parameter types + Lambda parametre türleri için ipuçlarını göster Show hints for literals - Show hints for literals + Sabit değerler için ipuçlarını göster Show hints for variables with inferred types - Show hints for variables with inferred types + Çıkarsanan türlere sahip değişkenler için ipuçlarını göster @@ -839,12 +839,12 @@ Suppress hints when parameter name matches the method's intent - Suppress hints when parameter name matches the method's intent + Parametre adı metodun hedefi ile eşleştiğinde ipuçlarını gizle Suppress hints when parameter names differ only by suffix - Suppress hints when parameter names differ only by suffix + Parametre adlarının yalnızca sonekleri farklı olduğunda ipuçlarını gizle @@ -854,17 +854,17 @@ The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. - The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. + Bu dosyayı oluşturan '{0}' oluşturucusu projeden kaldırıldı; bu dosya artık projenize dahil edilmiyor. The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. - The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. + Bu dosyayı oluşturan '{0}' oluşturucusu bu dosyayı oluşturmayı durdurdu; bu dosya artık projenize dahil edilmiyor. This file is auto-generated by the generator '{0}' and cannot be edited. - This file is auto-generated by the generator '{0}' and cannot be edited. + Bu dosya, '{0}' oluşturucusu tarafından otomatik olarak oluşturuldu ve düzenlenemez. @@ -909,7 +909,7 @@ Use 64-bit process for code analysis (requires restart) - Use 64-bit process for code analysis (requires restart) + Kod analizi için 64 bit işlemi kullanın (yeniden başlatma gerekir) @@ -1109,12 +1109,12 @@ [generated by {0}] - [generated by {0}] + [{0} tarafından oluşturuldu] {0} is the name of a generator. [generated] - [generated] + [oluşturuldu] @@ -1124,7 +1124,7 @@ Add a reference to '{0}' - {0}' öğesine başvuru ekleyin + '{0}' öğesine başvuru ekleyin @@ -1154,7 +1154,7 @@ Can't create a node id for this symbol kind: '{0}' - {0}' sembol türü için düğüm kimliği oluşturulamıyor + '{0}' sembol türü için düğüm kimliği oluşturulamıyor @@ -1174,7 +1174,7 @@ Could not find project '{0}' - {0}' adlı proje bulunamadı + '{0}' adlı proje bulunamadı @@ -1471,7 +1471,7 @@ Bu dosyanın ait olabileceği diğer projeleri görüntülemek ve bunlara geçi Reference to '{0}' in project '{1}' - {1}' adlı projedeki '{0}' öğesine yönelik başvuru + '{1}' adlı projedeki '{0}' öğesine yönelik başvuru @@ -1481,12 +1481,12 @@ Bu dosyanın ait olabileceği diğer projeleri görüntülemek ve bunlara geçi Analyzer reference to '{0}' in project '{1}' - {1}' projesindeki '{0}' öğesine yönelik çözümleyici başvurusu + '{1}' projesindeki '{0}' öğesine yönelik çözümleyici başvurusu Project reference to '{0}' in project '{1}' - {1}' adlı projedeki '{0}' öğesine yönelik proje başvurusu + '{1}' adlı projedeki '{0}' öğesine yönelik proje başvurusu @@ -1496,7 +1496,7 @@ Bu dosyanın ait olabileceği diğer projeleri görüntülemek ve bunlara geçi Analyzer assemblies '{0}' and '{1}' both have identity '{2}' but different contents. Only one will be loaded and analyzers using these assemblies may not run correctly. - {0}' ve '{1}' çözümleyici bütünleştirilmiş kodlarının ikisi de '{2}' kimliğine sahip, ancak içerikleri farklı. Yalnızca biri yüklenecek; bu bütünleştirilmiş kodları kullanan çözümleyiciler düzgün şekilde çalışmayabilir. + '{0}' ve '{1}' çözümleyici bütünleştirilmiş kodlarının ikisi de '{2}' kimliğine sahip, ancak içerikleri farklı. Yalnızca biri yüklenecek; bu bütünleştirilmiş kodları kullanan çözümleyiciler düzgün şekilde çalışmayabilir. @@ -1616,12 +1616,12 @@ Bu dosyanın ait olabileceği diğer projeleri görüntülemek ve bunlara geçi Installing '{0}' - {0}' yükleniyor + '{0}' yükleniyor Installing '{0}' completed - {0}' yüklendi + '{0}' yüklendi @@ -1801,22 +1801,22 @@ Bu dosyanın ait olabileceği diğer projeleri görüntülemek ve bunlara geçi Install '{0}' - {0}' öğesini yükle + '{0}' öğesini yükle Uninstalling '{0}' - {0}' kaldırılıyor + '{0}' kaldırılıyor Uninstalling '{0}' completed - {0}' kaldırıldı + '{0}' kaldırıldı Uninstall '{0}' - {0}' öğesini kaldır + '{0}' öğesini kaldır @@ -1864,7 +1864,7 @@ Bu dosyanın ait olabileceği diğer projeleri görüntülemek ve bunlara geçi Installing '{0}' failed. Additional information: {1} - {0}' yüklenemedi. + '{0}' yüklenemedi. Ek bilgiler: {1} @@ -1873,7 +1873,7 @@ Ek bilgiler: {1} Uninstalling '{0}' failed. Additional information: {1} - {0}' kaldırılamadı. + '{0}' kaldırılamadı. Ek bilgiler: {1} @@ -2175,12 +2175,12 @@ Ek bilgiler: {1} Get help for '{0}' - {0}' için yardım alın + '{0}' için yardım alın Get help for '{0}' from Bing - {0}' için Bing'den yardım alın + '{0}' için Bing'den yardım alın @@ -2320,7 +2320,7 @@ Ek bilgiler: {1} No references found to '{0}' - {0}' için başvuru bulunamadı + '{0}' için başvuru bulunamadı @@ -2358,15 +2358,15 @@ You acknowledge that binary code and source code might be protected by copyright Your use of the Decompiler is optional. Microsoft is not responsible and disclaims all liability for your use of the Decompiler that violates any laws or any software license terms which prohibit decompiling of the software. I agree to all of the foregoing: - IMPORTANT: Visual Studio includes decompiling functionality (“Decompiler”) that enables reproducing source code from binary code. By accessing and using the Decompiler, you agree to the Visual Studio license terms and the terms for the Decompiler below. If you do not agree with these combined terms, do not access or use the Decompiler. + ÖNEMLİ: Visual Studio ikili koddan kaynak kodu yeniden üretmeyi sağlayan kaynak koda dönüştürme (“Kaynak Koda Dönüştürücü”) işlevini içerir. Kaynak Koda Dönüştürücü’ye erişerek ve kullanarak, Visual Studio lisans koşullarını ve aşağıdaki Kaynak Koda Dönüştürücü koşullarını kabul etmiş olursunuz. Bu birleşik koşulları kabul etmiyorsanız, Kaynak Koda Dönüştürücü’ye erişmeyin veya kullanmayın. -You acknowledge that binary code and source code might be protected by copyright and trademark laws. Before using the Decompiler on any binary code, you need to first: -(i) confirm that the license terms governing your use of the binary code do not contain a provision which prohibits you from decompiling the software; or -(ii) obtain permission to decompile the binary code from the owner of the software. +İkili kodun ve kaynak kodun telif hakkı ve ticari marka yasaları tarafından korunuyor olabileceğini kabul etmiş olursunuz. Kaynak Koda Dönüştürücü’yü herhangi bir ikili kod üzerinde kullanmadan önce: +(i) ikili kodu kullanımınızı yöneten yasaların yazılımı kaynak koda dönüştürmeyi yasaklayan bir madde içermediğinden emin olmanız; veya +(ii) yazılım sahibinden ikili kodu kaynak koda dönüştürmek için izin almanız gerekir. -Your use of the Decompiler is optional. Microsoft is not responsible and disclaims all liability for your use of the Decompiler that violates any laws or any software license terms which prohibit decompiling of the software. +Kaynak Koda Dönüştürücü’yü kullanmak isteğe bağlıdır. Microsoft, yazılımın kaynak koda dönüştürülmesini yasaklayan herhangi bir yasayı veya yazılım lisansı koşulunu ihlal eden kullanımlardan sorumlu değildir ve tüm sorumluluğu reddeder. -I agree to all of the foregoing: +Aşağıdakilerin tümünü onaylıyorum: diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.zh-Hans.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.zh-Hans.xlf index 4367b3a1b5577..758f6f50b8192 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.zh-Hans.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + A new .editorconfig file was detected at the root of your solution. Would you like to make it a solution item? @@ -109,7 +109,7 @@ C#/Visual Basic Diagnostics Language Client - C#/Visual Basic Diagnostics Language Client + C#/Visual Basic 语言服务器客户端 @@ -154,7 +154,7 @@ Color hints - Color hints + 颜色提示 @@ -164,7 +164,7 @@ Comments - Comments + 备注 @@ -189,17 +189,17 @@ Display all hints while pressing Alt+F1 - Display all hints while pressing Alt+F1 + 按 Alt+F1 时显示所有提示 Disp_lay inline parameter name hints - 显示内联参数名称提示(实验)(_L) + 显示内联参数名称提示(_L) Display inline type hints - Display inline type hints + 显示内联类型提示 @@ -229,12 +229,12 @@ Enable Razor 'pull' diagnostics (experimental, requires restart) - Enable Razor 'pull' diagnostics (experimental, requires restart) + 启用 Razor“拉取”诊断(实验性,需要重启) Enable 'pull' diagnostics (experimental, requires restart) - Enable 'pull' diagnostics (experimental, requires restart) + 启用“拉取”诊断(实验性,需要重启) @@ -259,7 +259,7 @@ Extract Base Class - Extract Base Class + 提取基类 @@ -304,7 +304,7 @@ Inline Hints (experimental) - Inline Hints (experimental) + 内联提示(实验性) @@ -399,12 +399,12 @@ Name conflicts with an existing type name. - Name conflicts with an existing type name. + 名称与现有类型名称相冲突。 Name is not a valid {0} identifier. - Name is not a valid {0} identifier. + 名称不是有效的 {0} 标识符。 @@ -569,7 +569,7 @@ New Type Name: - New Type Name: + 新类型名称: @@ -814,22 +814,22 @@ Show hints for everything else - Show hints for everything else + 显示其他所有内容的提示 Show hints for lambda parameter types - Show hints for lambda parameter types + 显示 lambda 参数类型的提示 Show hints for literals - Show hints for literals + 显示文本提示 Show hints for variables with inferred types - Show hints for variables with inferred types + 显示具有推断类型的变量的提示 @@ -839,12 +839,12 @@ Suppress hints when parameter name matches the method's intent - Suppress hints when parameter name matches the method's intent + 当参数名称与方法的意图匹配时禁止显示提示 Suppress hints when parameter names differ only by suffix - Suppress hints when parameter names differ only by suffix + 当参数名称只有后缀不同时禁止显示提示 @@ -854,17 +854,17 @@ The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. - The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. + 生成此文件的生成器“{0}”已从项目中删除;项目中不再包含此文件。 The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. - The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. + 生成此文件的生成器“{0}”已停止生成此文件;项目中不再包含此文件。 This file is auto-generated by the generator '{0}' and cannot be edited. - This file is auto-generated by the generator '{0}' and cannot be edited. + 此文件由生成器“{0}”自动生成,无法编辑。 @@ -909,7 +909,7 @@ Use 64-bit process for code analysis (requires restart) - Use 64-bit process for code analysis (requires restart) + 对代码分析使用 64 位进程(需要重启) @@ -1109,12 +1109,12 @@ [generated by {0}] - [generated by {0}] + [由 {0} 生成] {0} is the name of a generator. [generated] - [generated] + [已生成] @@ -1511,7 +1511,7 @@ Use the dropdown to view and switch to other projects this file may belong to. '{0}' encountered an error and has been disabled. - '“{0}”遇到了错误,且已被禁用。 + “{0}”遇到了错误,且已被禁用。 diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.zh-Hant.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.zh-Hant.xlf index 6870c9c9b469a..7d22efc7094b4 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.zh-Hant.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + A new .editorconfig file was detected at the root of your solution. Would you like to make it a solution item? @@ -94,12 +94,12 @@ 32-bit - 32-bit + 32 位元 64-bit - 64-bit + 64 位元 @@ -109,7 +109,7 @@ C#/Visual Basic Diagnostics Language Client - C#/Visual Basic Diagnostics Language Client + C#/Visual Basic 診斷語言用戶端 @@ -154,7 +154,7 @@ Color hints - Color hints + 色彩提示 @@ -164,7 +164,7 @@ Comments - Comments + 註解 @@ -189,17 +189,17 @@ Display all hints while pressing Alt+F1 - Display all hints while pressing Alt+F1 + 按 Alt+F1 時顯示所有提示 Disp_lay inline parameter name hints - Disp_lay inline parameter name hints + 顯示內嵌參數名稱提示(_L) Display inline type hints - Display inline type hints + 顯示內嵌類型提示 @@ -229,12 +229,12 @@ Enable Razor 'pull' diagnostics (experimental, requires restart) - Enable Razor 'pull' diagnostics (experimental, requires restart) + 啟用 Razor 'pull' 診斷 (實驗性,需要重新啟動) Enable 'pull' diagnostics (experimental, requires restart) - Enable 'pull' diagnostics (experimental, requires restart) + 啟用 'pull' 診斷 (實驗性,需要重新啟動) @@ -259,7 +259,7 @@ Extract Base Class - Extract Base Class + 擷取基底類別 @@ -304,7 +304,7 @@ Inline Hints (experimental) - Inline Hints (experimental) + 內嵌提示 (實驗性) @@ -399,12 +399,12 @@ Name conflicts with an existing type name. - Name conflicts with an existing type name. + 名稱與現有類型名稱衝突。 Name is not a valid {0} identifier. - Name is not a valid {0} identifier. + 名稱不是有效的 {0} 識別碼。 @@ -569,7 +569,7 @@ New Type Name: - New Type Name: + 新的型別名稱: @@ -594,7 +594,7 @@ Optional parameters must provide a default value - 選擇性參數必須提供預設值。 + 選擇性參數必須提供預設值 @@ -814,22 +814,22 @@ Show hints for everything else - Show hints for everything else + 顯示所有其他項目的提示 Show hints for lambda parameter types - Show hints for lambda parameter types + 顯示 Lambda 參數類型的提示 Show hints for literals - Show hints for literals + 顯示常值的提示 Show hints for variables with inferred types - Show hints for variables with inferred types + 顯示有推斷類型之變數的提示 @@ -839,12 +839,12 @@ Suppress hints when parameter name matches the method's intent - Suppress hints when parameter name matches the method's intent + 當參數名稱符合方法的意圖時,不出現提示 Suppress hints when parameter names differ only by suffix - Suppress hints when parameter names differ only by suffix + 當參數名稱只有尾碼不同時,不出現提示 @@ -854,17 +854,17 @@ The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. - The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project. + 已從專案中移除產生此檔案的產生器 '{0}'; 此檔案已不再包含在您的專案中。 The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. - The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project. + 產生此檔案的產生器 '{0}' 已停止產生此檔案; 此檔案已不再包含在您的專案中。 This file is auto-generated by the generator '{0}' and cannot be edited. - This file is auto-generated by the generator '{0}' and cannot be edited. + 此檔案是由產生器 '{0}' 自動產生,無法加以編輯。 @@ -909,7 +909,7 @@ Use 64-bit process for code analysis (requires restart) - Use 64-bit process for code analysis (requires restart) + 使用 64 位元處理序進行程式碼分析 (需要重新啟動) @@ -1109,12 +1109,12 @@ [generated by {0}] - [generated by {0}] + [由 {0} 產生] {0} is the name of a generator. [generated] - [generated] + [已產生] @@ -2358,15 +2358,15 @@ You acknowledge that binary code and source code might be protected by copyright Your use of the Decompiler is optional. Microsoft is not responsible and disclaims all liability for your use of the Decompiler that violates any laws or any software license terms which prohibit decompiling of the software. I agree to all of the foregoing: - IMPORTANT: Visual Studio includes decompiling functionality (“Decompiler”) that enables reproducing source code from binary code. By accessing and using the Decompiler, you agree to the Visual Studio license terms and the terms for the Decompiler below. If you do not agree with these combined terms, do not access or use the Decompiler. + 注意事項: Visual Studio 包含能從二進位程式碼重新產生原始程式碼的反向組譯功能 (「解編程式」)。存取及使用此解編程式,即表示貴用戶同意 Visual Studio 授權條款及下方的解編程式條款。若貴用戶不同意這些合併條款,請勿存取或使用解編程式。 -You acknowledge that binary code and source code might be protected by copyright and trademark laws. Before using the Decompiler on any binary code, you need to first: -(i) confirm that the license terms governing your use of the binary code do not contain a provision which prohibits you from decompiling the software; or -(ii) obtain permission to decompile the binary code from the owner of the software. +貴用戶了解二進位程式碼及原始程式碼可能為著作權及商標法所保護。在針對任何二進位程式碼使用解編程式前,貴用戶首先需要: +(i) 確認管理貴用戶使用二進位程式碼的授權條款未禁止貴用戶反向組譯軟體; 或 +(ii) 向軟體擁有者取得反向組譯二進位程式碼的權限。 -Your use of the Decompiler is optional. Microsoft is not responsible and disclaims all liability for your use of the Decompiler that violates any laws or any software license terms which prohibit decompiling of the software. +貴用戶可自行選擇是否要使用解編程式。Microsoft 聲明不為貴用戶在使用編譯程式時觸犯的法律,或任何禁止反向解譯軟體的軟體授權條約承擔任何責任。 -I agree to all of the foregoing: +我同意以上條款: diff --git a/src/VisualStudio/Core/Def/xlf/VSPackage.zh-Hans.xlf b/src/VisualStudio/Core/Def/xlf/VSPackage.zh-Hans.xlf index f1e61d07d0735..98df943e0b880 100644 --- a/src/VisualStudio/Core/Def/xlf/VSPackage.zh-Hans.xlf +++ b/src/VisualStudio/Core/Def/xlf/VSPackage.zh-Hans.xlf @@ -1,6 +1,6 @@  - + \ No newline at end of file diff --git a/src/VisualStudio/Core/Def/xlf/VSPackage.zh-Hant.xlf b/src/VisualStudio/Core/Def/xlf/VSPackage.zh-Hant.xlf index f7dceb10f783b..ee27afe155e95 100644 --- a/src/VisualStudio/Core/Def/xlf/VSPackage.zh-Hant.xlf +++ b/src/VisualStudio/Core/Def/xlf/VSPackage.zh-Hant.xlf @@ -1,6 +1,6 @@  - + \ No newline at end of file diff --git a/src/VisualStudio/Core/Impl/SolutionExplorer/AnalyzerItem/AnalyzerItemSource.cs b/src/VisualStudio/Core/Impl/SolutionExplorer/AnalyzerItem/AnalyzerItemSource.cs index da92ecc4214a5..1fea8d81f8b2c 100644 --- a/src/VisualStudio/Core/Impl/SolutionExplorer/AnalyzerItem/AnalyzerItemSource.cs +++ b/src/VisualStudio/Core/Impl/SolutionExplorer/AnalyzerItem/AnalyzerItemSource.cs @@ -222,7 +222,7 @@ private ImmutableArray GetFilteredAnalyzers(IEnumerable(); - _diagnosticItems.AddRange(GetDiagnosticItems(project.Language, project.CompilationOptions, _analyzerConfigOptions)); + _diagnosticItems = CreateDiagnosticItems(project.Language, project.CompilationOptions, _analyzerConfigOptions); Workspace.WorkspaceChanged += OnWorkspaceChangedLookForOptionsChanges; } @@ -97,7 +96,7 @@ public IEnumerable Items } } - private IEnumerable GetDiagnosticItems(string language, CompilationOptions options, AnalyzerConfigOptionsResult? analyzerConfigOptions) + private BulkObservableCollection CreateDiagnosticItems(string language, CompilationOptions options, AnalyzerConfigOptionsResult? analyzerConfigOptions) { // Within an analyzer assembly, an individual analyzer may report multiple different diagnostics // with the same ID. Or, multiple analyzers may report diagnostics with the same ID. Or a @@ -110,7 +109,9 @@ private IEnumerable GetDiagnosticItems(string language, Comp Contract.ThrowIfFalse(HasItems); - return AnalyzerReference.GetAnalyzers(language) + var collection = new BulkObservableCollection(); + collection.AddRange( + AnalyzerReference.GetAnalyzers(language) .SelectMany(a => _diagnosticAnalyzerService.AnalyzerInfoCache.GetDiagnosticDescriptors(a)) .GroupBy(d => d.Id) .OrderBy(g => g.Key, StringComparer.CurrentCulture) @@ -119,7 +120,9 @@ private IEnumerable GetDiagnosticItems(string language, Comp var selectedDiagnostic = g.OrderBy(d => d, s_comparer).First(); var effectiveSeverity = selectedDiagnostic.GetEffectiveSeverity(options, analyzerConfigOptions); return CreateItem(selectedDiagnostic, effectiveSeverity, language); - }); + })); + + return collection; } private void OnWorkspaceChangedLookForOptionsChanges(object sender, WorkspaceChangeEventArgs e) diff --git a/src/VisualStudio/Core/Impl/xlf/SolutionExplorerShim.zh-Hans.xlf b/src/VisualStudio/Core/Impl/xlf/SolutionExplorerShim.zh-Hans.xlf index 4364de4d50cba..ae9c9bdf5fe03 100644 --- a/src/VisualStudio/Core/Impl/xlf/SolutionExplorerShim.zh-Hans.xlf +++ b/src/VisualStudio/Core/Impl/xlf/SolutionExplorerShim.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Analyzers diff --git a/src/VisualStudio/Core/Impl/xlf/SolutionExplorerShim.zh-Hant.xlf b/src/VisualStudio/Core/Impl/xlf/SolutionExplorerShim.zh-Hant.xlf index 8a346b20c9156..f58d25631e7d0 100644 --- a/src/VisualStudio/Core/Impl/xlf/SolutionExplorerShim.zh-Hant.xlf +++ b/src/VisualStudio/Core/Impl/xlf/SolutionExplorerShim.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Analyzers diff --git a/src/VisualStudio/Core/Test/SolutionExplorer/CpsDiagnosticItemSourceTests.vb b/src/VisualStudio/Core/Test/SolutionExplorer/CpsDiagnosticItemSourceTests.vb new file mode 100644 index 0000000000000..82812dbb1c7d7 --- /dev/null +++ b/src/VisualStudio/Core/Test/SolutionExplorer/CpsDiagnosticItemSourceTests.vb @@ -0,0 +1,51 @@ +' Licensed to the .NET Foundation under one or more agreements. +' The .NET Foundation licenses this file to you under the MIT license. +' See the LICENSE file in the project root for more information. + +Imports System.Collections.Immutable +Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Diagnostics +Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces +Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.Internal.VisualStudio.PlatformUI +Imports Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer +Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework +Imports Microsoft.VisualStudio.Shell + +Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.SolutionExplorer + + Public Class CpsDiagnosticItemSourceTests + + Public Sub AnalyzerHasDiagnostics() + Dim workspaceXml = + + + + + + Using workspace = TestWorkspace.Create(workspaceXml) + Dim project = workspace.Projects.Single() + + Dim analyzers = New Dictionary(Of String, ImmutableArray(Of DiagnosticAnalyzer)) + + ' The choice here of this analyzer to test with is arbitray -- there's nothing special about this + ' analyzer versus any other one. + analyzers.Add(LanguageNames.VisualBasic, ImmutableArray.Create(Of DiagnosticAnalyzer)(New Microsoft.CodeAnalysis.VisualBasic.UseAutoProperty.VisualBasicUseAutoPropertyAnalyzer())) + + Const analyzerPath = "C:\Analyzer.dll" + workspace.OnAnalyzerReferenceAdded(project.Id, New TestAnalyzerReferenceByLanguage(analyzers, analyzerPath)) + + Dim source As IAttachedCollectionSource = New CpsDiagnosticItemSource( + workspace, + project.FilePath, + project.Id, + New MockHierarchyItem() With {.CanonicalName = "\net472\analyzerdependency\" + analyzerPath}, + New FakeAnalyzersCommandHandler, workspace.GetService(Of IDiagnosticAnalyzerService)) + + Assert.True(source.HasItems) + Dim diagnostic = Assert.IsAssignableFrom(Of ITreeDisplayItem)(Assert.Single(source.Items)) + Assert.Contains(IDEDiagnosticIds.UseAutoPropertyDiagnosticId, diagnostic.Text) + End Using + End Sub + End Class +End Namespace diff --git a/src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpAddMissingImportsOnPaste.cs b/src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpAddMissingImportsOnPaste.cs new file mode 100644 index 0000000000000..35f04a689cb2e --- /dev/null +++ b/src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpAddMissingImportsOnPaste.cs @@ -0,0 +1,99 @@ +// Licensed to the .NET Foundation under one or more 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; +using Microsoft.CodeAnalysis.Editor.Shared.Options; +using Microsoft.CodeAnalysis.Test.Utilities; +using Microsoft.VisualStudio.IntegrationTest.Utilities; +using Roslyn.Test.Utilities; +using Xunit; + +namespace Roslyn.VisualStudio.IntegrationTests.CSharp +{ + [Collection(nameof(SharedIntegrationHostFixture))] + public class CSharpAddMissingImportsOnPaste : AbstractEditorTest + { + public CSharpAddMissingImportsOnPaste(VisualStudioInstanceFactory instanceFactory) + : base(instanceFactory, nameof(CSharpAddMissingImportsOnPaste)) + { + } + + protected override string LanguageName => LanguageNames.CSharp; + + [WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)] + public void VerifyMissingByDefault() + { + var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName); + VisualStudio.SolutionExplorer.AddFile(project, "Foo.cs", contents: @" +public class Foo +{ +} +"); + SetUpEditor(@" +using System; + +class Program +{ + static void Main(string[] args) + { + } + + $$ +}"); + + VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;"); + + VisualStudio.Editor.Verify.TextContains(@" +using System; + +class Program +{ + static void Main(string[] args) + { + } + + Task DoThingAsync() => Task.CompletedTask; +}"); + } + + [WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)] + public void VerifyAddImportsOnPaste() + { + var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName); + VisualStudio.SolutionExplorer.AddFile(project, "Foo.cs", contents: @" +public class Foo +{ +} +"); + SetUpEditor(@" +using System; + +class Program +{ + static void Main(string[] args) + { + } + + $$ +}"); + + VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, "True"); + + VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;"); + + VisualStudio.Editor.Verify.TextContains(@" +using System; +using System.Threading.Tasks; + +class Program +{ + static void Main(string[] args) + { + } + + Task DoThingAsync() => Task.CompletedTask; +}"); + } + } +} diff --git a/src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpAutomaticBraceCompletion.cs b/src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpAutomaticBraceCompletion.cs index 6279868d5edd2..3dc459639bad8 100644 --- a/src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpAutomaticBraceCompletion.cs +++ b/src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpAutomaticBraceCompletion.cs @@ -63,6 +63,103 @@ void Goo() { VisualStudio.Editor.Verify.CurrentLineText("if (true) { }$$", assertCaretPosition: true); } + /// + /// This is a muscle-memory test for users who rely on the following sequence: + /// + /// Enter + /// { + /// Enter + /// } + /// + /// + [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] + public void Braces_Overtyping_Method() + { + SetUpEditor(@" +class C { + $$ +}"); + + VisualStudio.Editor.SendKeys("public void A()"); + VisualStudio.Editor.SendKeys(VirtualKey.Enter, '{', VirtualKey.Enter, '}'); + + VisualStudio.Editor.Verify.CurrentLineText("}$$", assertCaretPosition: true); + } + + /// + /// This is a muscle-memory test for users who rely on the following sequence: + /// + /// Enter + /// { + /// Enter + /// } + /// + /// + [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] + public void Braces_Overtyping_Property() + { + SetUpEditor(@" +class C { + $$ +}"); + + VisualStudio.Editor.SendKeys("public int X"); + VisualStudio.Editor.SendKeys(VirtualKey.Enter, '{', VirtualKey.Enter, '}'); + + VisualStudio.Editor.Verify.CurrentLineText("}$$", assertCaretPosition: true); + } + + /// + /// This is a muscle-memory test for users who rely on the following sequence: + /// + /// Enter + /// { + /// Enter + /// } + /// + /// + [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] + public void Braces_Overtyping_CollectionInitializer() + { + SetUpEditor(@" +using System.Collections.Generic; +class C { + void Method() { + $$ + } +}"); + + VisualStudio.Editor.SendKeys("var x = new List()"); + VisualStudio.Editor.SendKeys(VirtualKey.Enter, '{', VirtualKey.Enter, '}'); + + VisualStudio.Editor.Verify.CurrentLineText("}$$", assertCaretPosition: true); + } + + /// + /// This is a muscle-memory test for users who rely on the following sequence: + /// + /// Enter + /// { + /// Enter + /// } + /// + /// + [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] + public void Braces_Overtyping_ObjectInitializer() + { + SetUpEditor(@" +class C { + void Method() { + $$ + } +}"); + + VisualStudio.Editor.SendKeys("var x = new object()"); + VisualStudio.Editor.SendKeys(VirtualKey.Enter, '{', VirtualKey.Enter, '}'); + + VisualStudio.Editor.Verify.CurrentLineText("}$$", assertCaretPosition: true); + } + [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Braces_OnReturnNoFormattingOnlyIndentationBeforeCloseBrace(bool showCompletionInArgumentLists) { diff --git a/src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpSourceGenerators.cs b/src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpSourceGenerators.cs index 4dae826b5a756..444e5f63470d3 100644 --- a/src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpSourceGenerators.cs +++ b/src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpSourceGenerators.cs @@ -4,10 +4,14 @@ #nullable disable +using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; +using Microsoft.CodeAnalysis.TestSourceGenerator; using Microsoft.VisualStudio.IntegrationTest.Utilities; +using Microsoft.VisualStudio.IntegrationTest.Utilities.Common; +using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Microsoft.VisualStudio.LanguageServices; using Roslyn.Test.Utilities; using Xunit; @@ -29,10 +33,10 @@ public override async Task InitializeAsync() { await base.InitializeAsync(); - VisualStudio.SolutionExplorer.AddAnalyzerReference(typeof(IntegrationTestSourceGenerator).Assembly.Location, new ProjectUtils.Project(ProjectName)); + VisualStudio.SolutionExplorer.AddAnalyzerReference(typeof(HelloWorldGenerator).Assembly.Location, new ProjectUtils.Project(ProjectName)); } - [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/47255"), Trait(Traits.Feature, Traits.Features.SourceGenerators)] + [WpfFact, Trait(Traits.Feature, Traits.Features.SourceGenerators)] public void GoToDefinitionOpensGeneratedFile() { VisualStudio.Editor.SetText(@"using System; @@ -40,14 +44,51 @@ internal static class Program { public static void Main() { - Console.WriteLine(" + IntegrationTestSourceGenerator.GeneratedClassName + @".GetMessage()); + Console.WriteLine(" + HelloWorldGenerator.GeneratedClassName + @".GetMessage()); } }"); - VisualStudio.Editor.PlaceCaret(IntegrationTestSourceGenerator.GeneratedClassName); + VisualStudio.Editor.PlaceCaret(HelloWorldGenerator.GeneratedClassName); VisualStudio.Editor.GoToDefinition(); - Assert.Equal($"{IntegrationTestSourceGenerator.GeneratedClassName}.cs {ServicesVSResources.generated_suffix}", VisualStudio.Shell.GetActiveWindowCaption()); - Assert.Equal(IntegrationTestSourceGenerator.GeneratedClassName, VisualStudio.Editor.GetSelectedText()); + Assert.Equal($"{HelloWorldGenerator.GeneratedClassName}.cs {ServicesVSResources.generated_suffix}", VisualStudio.Shell.GetActiveWindowCaption()); + Assert.Equal(HelloWorldGenerator.GeneratedClassName, VisualStudio.Editor.GetSelectedText()); + } + + [WpfFact, Trait(Traits.Feature, Traits.Features.SourceGenerators)] + public void FindReferencesForFileWithDefinitionInSourceGeneratedFile() + { + VisualStudio.Editor.SetText(@"using System; +internal static class Program +{ + public static void Main() + { + Console.WriteLine(" + HelloWorldGenerator.GeneratedClassName + @".GetMessage()); + } +}"); + + VisualStudio.Editor.PlaceCaret(HelloWorldGenerator.GeneratedClassName); + VisualStudio.Editor.SendKeys(Shift(VirtualKey.F12)); + + string programReferencesCaption = $"'{HelloWorldGenerator.GeneratedClassName}' references"; + var results = VisualStudio.FindReferencesWindow.GetContents(programReferencesCaption); + + Assert.Collection( + results, + new Action[] + { + reference => + { + Assert.Equal(expected: "internal class HelloWorld", actual: reference.Code); + Assert.Equal(expected: 1, actual: reference.Line); + Assert.Equal(expected: 15, actual: reference.Column); + }, + reference => + { + Assert.Equal(expected: "Console.WriteLine(" + HelloWorldGenerator.GeneratedClassName + ".GetMessage());", actual: reference.Code); + Assert.Equal(expected: 5, actual: reference.Line); + Assert.Equal(expected: 26, actual: reference.Column); + } + }); } } } diff --git a/src/VisualStudio/IntegrationTest/IntegrationTests/Microsoft.VisualStudio.LanguageServices.IntegrationTests.csproj b/src/VisualStudio/IntegrationTest/IntegrationTests/Microsoft.VisualStudio.LanguageServices.IntegrationTests.csproj index b8b89e2de18d7..67ae5dd0ffc76 100644 --- a/src/VisualStudio/IntegrationTest/IntegrationTests/Microsoft.VisualStudio.LanguageServices.IntegrationTests.csproj +++ b/src/VisualStudio/IntegrationTest/IntegrationTests/Microsoft.VisualStudio.LanguageServices.IntegrationTests.csproj @@ -40,6 +40,7 @@ + diff --git a/src/VisualStudio/IntegrationTest/TestUtilities/Input/VirtualKey.cs b/src/VisualStudio/IntegrationTest/TestUtilities/Input/VirtualKey.cs index b44ea89f5835a..6a1e994b7d4f2 100644 --- a/src/VisualStudio/IntegrationTest/TestUtilities/Input/VirtualKey.cs +++ b/src/VisualStudio/IntegrationTest/TestUtilities/Input/VirtualKey.cs @@ -83,6 +83,18 @@ public enum VirtualKey : byte Y = 0x59, Z = 0x5A, - Period = 0xBE + Period = 0xBE, + + /// + /// Used for miscellaneous characters; it can vary by keyboard.
+ /// For the US standard keyboard, the '[{' key. + ///
+ VK_OEM_4 = 0xDB, + + /// + /// Used for miscellaneous characters; it can vary by keyboard.
+ /// For the US standard keyboard, the ']}' key. + ///
+ VK_OEM_6 = 0xDD, } } diff --git a/src/VisualStudio/LiveShare/Impl/Shims/TypeScriptHandlerShims.cs b/src/VisualStudio/LiveShare/Impl/Shims/TypeScriptHandlerShims.cs index ed9619a459756..5134a8b7894b8 100644 --- a/src/VisualStudio/LiveShare/Impl/Shims/TypeScriptHandlerShims.cs +++ b/src/VisualStudio/LiveShare/Impl/Shims/TypeScriptHandlerShims.cs @@ -18,6 +18,7 @@ using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SignatureHelp; +using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.LiveShare.Protocol; using Microsoft.VisualStudio.LiveShare.LanguageServices; @@ -196,7 +197,15 @@ public static LSP.RequestContext CreateRequestContext(this var (documentId, solution) = provider.GetDocumentAndSolution(textDocument, clientName); var document = solution.GetDocument(documentId); - return new LSP.RequestContext(solution, clientCapabilities, clientName, document, documentChangeTracker: null); + return new LSP.RequestContext(solution, clientCapabilities, clientName, document, new NoOpDocumentChangeTracker()); + } + + private class NoOpDocumentChangeTracker : RequestExecutionQueue.IDocumentChangeTracker + { + public bool IsTracking(Uri documentUri) => false; + public void StartTracking(Uri documentUri, SourceText initialText) { } + public void StopTracking(Uri documentUri) { } + public void UpdateTrackedDocument(Uri documentUri, SourceText text) { } } } } diff --git a/src/VisualStudio/Setup/Roslyn.VisualStudio.Setup.csproj b/src/VisualStudio/Setup/Roslyn.VisualStudio.Setup.csproj index 323ddf990f606..b3b25ad3a1e8b 100644 --- a/src/VisualStudio/Setup/Roslyn.VisualStudio.Setup.csproj +++ b/src/VisualStudio/Setup/Roslyn.VisualStudio.Setup.csproj @@ -263,7 +263,7 @@ InteractiveHost.Core64 - TargetFramework=net5.0-windows + TargetFramework=net5.0-windows7.0 true false diff --git a/src/VisualStudio/VisualBasic/Impl/BasicVSResources.resx b/src/VisualStudio/VisualBasic/Impl/BasicVSResources.resx index 8bb6a6ab74b26..79da0f9020575 100644 --- a/src/VisualStudio/VisualBasic/Impl/BasicVSResources.resx +++ b/src/VisualStudio/VisualBasic/Impl/BasicVSResources.resx @@ -310,4 +310,8 @@ Show hints for 'New' expressions + + Add missing imports on paste + 'import' is a Visual Basic keyword and should not be localized + \ No newline at end of file diff --git a/src/VisualStudio/VisualBasic/Impl/Options/AdvancedOptionPageControl.xaml b/src/VisualStudio/VisualBasic/Impl/Options/AdvancedOptionPageControl.xaml index 403bd404b8fa8..8325cf3521030 100644 --- a/src/VisualStudio/VisualBasic/Impl/Options/AdvancedOptionPageControl.xaml +++ b/src/VisualStudio/VisualBasic/Impl/Options/AdvancedOptionPageControl.xaml @@ -47,6 +47,10 @@ + +
+ + Add missing imports on paste + Add missing imports on paste + 'import' is a Visual Basic keyword and should not be localized + In relational operators: = <> < > <= >= Like Is V relačních operátorech: = <> < > <= >= Like Is @@ -9,7 +14,7 @@ Insert ' at the start of new lines when writing ' comments - Insert ' at the start of new lines when writing ' comments + Při psaní komentářů ' na začátek řádku vkládat ' @@ -39,7 +44,7 @@ Prefer 'IsNot' expression - Prefer 'IsNot' expression + Upřednostňovat výraz IsNot @@ -49,12 +54,12 @@ Show hints for 'New' expressions - Show hints for 'New' expressions + Zobrazit nápovědy pro výrazy New Show items from unimported namespaces - Zobrazit položky z neimportovaných oborů názvů (experimentální) + Zobrazit položky z neimportovaných oborů názvů diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.de.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.de.xlf index e97a679d6538f..fab5c58b9f6da 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.de.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.de.xlf @@ -2,6 +2,11 @@ + + Add missing imports on paste + Add missing imports on paste + 'import' is a Visual Basic keyword and should not be localized + In relational operators: = <> < > <= >= Like Is In relationalen Operatoren: = <> < > <= >= Like Is @@ -9,7 +14,7 @@ Insert ' at the start of new lines when writing ' comments - Insert ' at the start of new lines when writing ' comments + Fügen Sie beim Schreiben von '-Kommentaren ein Apostroph (') am Anfang der neuen Zeilen ein. @@ -39,7 +44,7 @@ Prefer 'IsNot' expression - Prefer 'IsNot' expression + Ausdruck "IsNot" bevorzugen @@ -49,12 +54,12 @@ Show hints for 'New' expressions - Show hints for 'New' expressions + Hinweise für new-Ausdrücke anzeigen Show items from unimported namespaces - Elemente aus nicht importierten Namespaces anzeigen (experimentell) + Elemente aus nicht importierten Namespaces anzeigen @@ -174,7 +179,7 @@ _Place 'System' directives first when sorting imports - System-Direktiven beim Sortieren von Import-Direktiven an erster Stelle platzieren + System-Anweisungen beim Sortieren von import-Anweisungen an erster Stelle _platzieren diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.es.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.es.xlf index 92c66dc6aff6f..d9bb544d92bab 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.es.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.es.xlf @@ -2,6 +2,11 @@ + + Add missing imports on paste + Add missing imports on paste + 'import' is a Visual Basic keyword and should not be localized + In relational operators: = <> < > <= >= Like Is En los operadores relacionales: = <> < > <= >= Like Is @@ -9,7 +14,7 @@ Insert ' at the start of new lines when writing ' comments - Insert ' at the start of new lines when writing ' comments + Insertar ' al comienzo de las líneas nuevas al escribir comentarios ' @@ -39,7 +44,7 @@ Prefer 'IsNot' expression - Prefer 'IsNot' expression + Anteponer expresión "IsNot" @@ -49,12 +54,12 @@ Show hints for 'New' expressions - Show hints for 'New' expressions + Mostrar sugerencias para las expresiones "new" Show items from unimported namespaces - Mostrar elementos de espacios de nombres no importados (experimental) + Mostrar elementos de espacios de nombres no importados diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.fr.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.fr.xlf index 822ce328b74ce..980cbb168ade2 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.fr.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.fr.xlf @@ -2,6 +2,11 @@ + + Add missing imports on paste + Add missing imports on paste + 'import' is a Visual Basic keyword and should not be localized + In relational operators: = <> < > <= >= Like Is Dans les opérateurs relationnels : = <> < > <= >= Like Is @@ -9,7 +14,7 @@ Insert ' at the start of new lines when writing ' comments - Insert ' at the start of new lines when writing ' comments + Insérer ' au début des nouvelles lignes pour l'écriture de commentaires ' @@ -39,7 +44,7 @@ Prefer 'IsNot' expression - Prefer 'IsNot' expression + Préférer l'expression 'IsNot' @@ -49,12 +54,12 @@ Show hints for 'New' expressions - Show hints for 'New' expressions + Afficher les indicateurs pour les expressions 'New' Show items from unimported namespaces - Afficher les éléments des espaces de noms qui ne sont pas importés (expérimental) + Afficher les éléments des espaces de noms qui ne sont pas importés diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.it.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.it.xlf index 890bfdbb45b81..96656a89082c6 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.it.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.it.xlf @@ -2,6 +2,11 @@ + + Add missing imports on paste + Add missing imports on paste + 'import' is a Visual Basic keyword and should not be localized + In relational operators: = <> < > <= >= Like Is In operatori relazionali: = <> < > <= >= Like Is @@ -9,7 +14,7 @@ Insert ' at the start of new lines when writing ' comments - Insert ' at the start of new lines when writing ' comments + Inserisci * all'inizio di nuove righe quando si scrivono commenti ' @@ -39,7 +44,7 @@ Prefer 'IsNot' expression - Prefer 'IsNot' expression + Preferisci l'espressione 'IsNot' @@ -49,12 +54,12 @@ Show hints for 'New' expressions - Show hints for 'New' expressions + Mostra suggerimenti per le espressioni 'New' Show items from unimported namespaces - Mostra elementi da spazi dei nomi non importati (sperimentale) + Mostra elementi da spazi dei nomi non importati diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.ja.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.ja.xlf index da7f3f134ab3d..c26269215f20c 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.ja.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.ja.xlf @@ -2,6 +2,11 @@ + + Add missing imports on paste + Add missing imports on paste + 'import' is a Visual Basic keyword and should not be localized + In relational operators: = <> < > <= >= Like Is 関係演算子: = <> < > <= >= Like Is @@ -9,7 +14,7 @@ Insert ' at the start of new lines when writing ' comments - Insert ' at the start of new lines when writing ' comments + ' コメントの記述時に ' を新しい行の先頭に挿入する @@ -39,7 +44,7 @@ Prefer 'IsNot' expression - Prefer 'IsNot' expression + 'IsNot' 式を優先する @@ -49,12 +54,12 @@ Show hints for 'New' expressions - Show hints for 'New' expressions + 'New' 式のヒントを表示する Show items from unimported namespaces - インポートされていない名前空間の項目を表示する (試験段階) + インポートされていない名前空間の項目を表示する diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.ko.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.ko.xlf index 4db6f33b5dac1..ca84ca7492307 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.ko.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.ko.xlf @@ -2,6 +2,11 @@ + + Add missing imports on paste + Add missing imports on paste + 'import' is a Visual Basic keyword and should not be localized + In relational operators: = <> < > <= >= Like Is 관계형 연산자: = <> < > <= >= Like Is @@ -9,7 +14,7 @@ Insert ' at the start of new lines when writing ' comments - Insert ' at the start of new lines when writing ' comments + ' 주석을 작성할 때 새 줄의 시작 부분에 ' 삽입 @@ -39,7 +44,7 @@ Prefer 'IsNot' expression - Prefer 'IsNot' expression + 'IsNot' 식 선호 @@ -49,12 +54,12 @@ Show hints for 'New' expressions - Show hints for 'New' expressions + 'New' 식에 대한 힌트 표시 Show items from unimported namespaces - 가져오지 않은 네임스페이스의 항목 표시(실험적) + 가져오지 않은 네임스페이스의 항목 표시 diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.pl.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.pl.xlf index 824e0a0f54207..a264d8b326917 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.pl.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.pl.xlf @@ -2,6 +2,11 @@ + + Add missing imports on paste + Add missing imports on paste + 'import' is a Visual Basic keyword and should not be localized + In relational operators: = <> < > <= >= Like Is W operatorach relacyjnych: = <> < > <= >= Like Is @@ -9,7 +14,7 @@ Insert ' at the start of new lines when writing ' comments - Insert ' at the start of new lines when writing ' comments + Wstaw znak ' na początku nowych wierszy podczas pisania komentarzy ze znakiem ' @@ -39,7 +44,7 @@ Prefer 'IsNot' expression - Prefer 'IsNot' expression + Preferuj wyrażenie „IsNot” @@ -49,12 +54,12 @@ Show hints for 'New' expressions - Show hints for 'New' expressions + Pokaż wskazówki dla wyrażeń „New” Show items from unimported namespaces - Pokaż elementy z nieimportowanych przestrzeni nazw (eksperymentalne) + Pokaż elementy z nieimportowanych przestrzeni nazw diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.pt-BR.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.pt-BR.xlf index f75bc40bf302f..9cab096f58052 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.pt-BR.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.pt-BR.xlf @@ -2,6 +2,11 @@ + + Add missing imports on paste + Add missing imports on paste + 'import' is a Visual Basic keyword and should not be localized + In relational operators: = <> < > <= >= Like Is Em operadores relacionais: = <> < > <= >= Como É @@ -9,7 +14,7 @@ Insert ' at the start of new lines when writing ' comments - Insert ' at the start of new lines when writing ' comments + Inserir ' no início de novas linhas ao escrever comentários de ' @@ -39,7 +44,7 @@ Prefer 'IsNot' expression - Prefer 'IsNot' expression + Preferir a expressão 'IsNot' @@ -49,12 +54,12 @@ Show hints for 'New' expressions - Show hints for 'New' expressions + Mostrar as dicas para as expressões 'New' Show items from unimported namespaces - Mostrar itens de namespaces não importados (experimental) + Mostrar os itens de namespaces não importados diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.ru.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.ru.xlf index 4884f549585e8..f4f347fdb8412 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.ru.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.ru.xlf @@ -2,6 +2,11 @@ + + Add missing imports on paste + Add missing imports on paste + 'import' is a Visual Basic keyword and should not be localized + In relational operators: = <> < > <= >= Like Is В реляционных операторах: = <> < > <= >= Like Is @@ -9,7 +14,7 @@ Insert ' at the start of new lines when writing ' comments - Insert ' at the start of new lines when writing ' comments + Вставлять "'" в начале новых строк при написании комментариев "'" @@ -39,7 +44,7 @@ Prefer 'IsNot' expression - Prefer 'IsNot' expression + Предпочтительно использовать выражение IsNot @@ -49,12 +54,12 @@ Show hints for 'New' expressions - Show hints for 'New' expressions + Отображать подсказки для выражений "New" Show items from unimported namespaces - Показать элементы из неимпортированных пространств имен (экспериментальная функция) + Отображать элементы из неимпортированных пространств имен diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.tr.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.tr.xlf index c9ef3568c3290..7d17df31ff200 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.tr.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.tr.xlf @@ -2,6 +2,11 @@ + + Add missing imports on paste + Add missing imports on paste + 'import' is a Visual Basic keyword and should not be localized + In relational operators: = <> < > <= >= Like Is İlişkisel işleçleri içinde: = Transfeleri'nin < > <> = nasıl olduğunu = @@ -9,7 +14,7 @@ Insert ' at the start of new lines when writing ' comments - Insert ' at the start of new lines when writing ' comments + ' açıklamaları yazılırken yeni satırların başlangıcına ' ekle @@ -39,7 +44,7 @@ Prefer 'IsNot' expression - Prefer 'IsNot' expression + 'IsNot' ifadesini tercih edin @@ -49,12 +54,12 @@ Show hints for 'New' expressions - Show hints for 'New' expressions + 'New' ifadeleri için ipuçlarını göster Show items from unimported namespaces - İçeri aktarılmayan ad alanlarındaki öğeleri göster (deneysel) + İçeri aktarılmayan ad alanlarındaki öğeleri göster diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.zh-Hans.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.zh-Hans.xlf index f50a0b75a3f01..ce6353b80814c 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.zh-Hans.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.zh-Hans.xlf @@ -1,7 +1,12 @@  - + + + Add missing imports on paste + Add missing imports on paste + 'import' is a Visual Basic keyword and should not be localized + In relational operators: = <> < > <= >= Like Is 在关系运算符中: = <> < > <= >= Like Is @@ -9,7 +14,7 @@ Insert ' at the start of new lines when writing ' comments - Insert ' at the start of new lines when writing ' comments + 编写 ' 注释时,在新行开头插入 ' @@ -39,7 +44,7 @@ Prefer 'IsNot' expression - Prefer 'IsNot' expression + 首选 "IsNot" 表达式 @@ -49,12 +54,12 @@ Show hints for 'New' expressions - Show hints for 'New' expressions + 显示 "New" 表达式的提示 Show items from unimported namespaces - 显示 unimported 命名空间中的项(实验) + 显示 unimported 命名空间中的项 diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.zh-Hant.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.zh-Hant.xlf index 4cd2cd4ed1d9a..822a069aaaf4f 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.zh-Hant.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.zh-Hant.xlf @@ -1,7 +1,12 @@  - + + + Add missing imports on paste + Add missing imports on paste + 'import' is a Visual Basic keyword and should not be localized + In relational operators: = <> < > <= >= Like Is 在關係運算子中: = <> < > <= >= Like Is @@ -9,7 +14,7 @@ Insert ' at the start of new lines when writing ' comments - Insert ' at the start of new lines when writing ' comments + 撰寫 ' 註解時,於新行開頭插入 ' @@ -39,7 +44,7 @@ Prefer 'IsNot' expression - Prefer 'IsNot' expression + 建議使用 'IsNot' 運算式 @@ -49,12 +54,12 @@ Show hints for 'New' expressions - Show hints for 'New' expressions + 顯示 'New' 運算式的提示 Show items from unimported namespaces - 顯示來自未匯入命名空間的項目 (實驗性) + 顯示來自未匯入命名空間的項目 diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.cs.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.cs.xlf index 8fa341ccfeaf9..f1fc32c2ce5f3 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.cs.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.cs.xlf @@ -19,7 +19,7 @@ Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme; - Zobrazovat nápovědy k názvům vložených parametrů;Automatické vložení koncových konstruktorů;Změnit nastavení přehledného výpisu;Změnit režim sbalení;Automatické vkládání členů Interface a MustOverride;Zobrazit nebo skrýt oddělovače řádků procedur;Zapnout nebo vypnout návrhy oprav;Zapnout nebo vypnout zvýrazňování odkazů a klíčových slov;Regex;Obarvit regulární výrazy;Zvýrazňovat související komponenty pod kurzorem;Nahlásit neplatné regulární výrazy;reg. výr.;regulární výraz;Používat rozšířené barvy;Barevné schéma editoru; + Zobrazovat vložené nápovědy;Automatické vložení koncových konstruktorů;Změnit nastavení přehledného výpisu;Změnit režim sbalení;Automatické vkládání členů Interface a MustOverride;Zobrazit nebo skrýt oddělovače řádků procedur;Zapnout nebo vypnout návrhy oprav;Zapnout nebo vypnout zvýrazňování odkazů a klíčových slov;Regex;Obarvit regulární výrazy;Zvýrazňovat související komponenty pod kurzorem;Nahlásit neplatné regulární výrazy;reg. výr.;regulární výraz;Používat rozšířené barvy;Barevné schéma editoru; Advanced options page keywords diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.de.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.de.xlf index 4f5b1f92cf7ab..ea2b9181f9614 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.de.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.de.xlf @@ -19,7 +19,7 @@ Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme; - Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme; + Inline-Hinweise anzeigen;Endkonstrukte automatisch einfügen;Einstellungen für automatische Strukturierung und Einrückung ändern;Gliederungsmodus ändern;Schnittstellen- und MustOverride-Member automatisch einfügen;Zeilentrennzeichen zwischen Prozeduren anzeigen oder ausblenden;Vorschläge für Fehlerkorrektur ein- oder ausschalten;Hervorhebung von Verweisen und Schlüsselwörtern ein- oder ausschalten;Regex;Reguläre Ausdrücke farbig markieren;Verwandte Komponenten unter Cursor hervorheben;Ungültige reguläre Ausdrücke melden;regex;regulärer Ausdruck;nErweiterte Farben verwenden;Editor-Farbschema; Advanced options page keywords diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.es.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.es.xlf index 0710c804d622e..dafd2973a2002 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.es.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.es.xlf @@ -19,7 +19,7 @@ Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme; - Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme; + Mostrar sugerencias insertadas;Inserción automática de construcciones End;Cambiar configuración de la lista descriptiva;Cambiar modo de esquematización;Inserción automática de miembros Interface y MustOverride;Mostrar u ocultar separadores de línea de procedimientos;Activar o desactivar sugerencias de corrección de errores;Activar o desactivar resaltado de referencias y palabras clave;Regex;Colorear expresiones regulares;Resaltar componentes relacionados bajo el cursor;Informar sobre expresiones regulares no válidas;regex;expresión regular;Usar colores mejorados;Combinación de colores del editor; Advanced options page keywords diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.fr.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.fr.xlf index eec726572e906..8af1fb613c47c 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.fr.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.fr.xlf @@ -19,7 +19,7 @@ Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme; - Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme; + Afficher les indicateurs inline;Insertion automatique des constructions de fin;Changer les paramètres de listing en mode Pretty;Changer le mode Plan;Insertion automatique des membres Interface et MustOverride;Afficher ou masquer les séparateurs de ligne de procédure;Activer ou désactiver les suggestions de correction d'erreurs;Activer ou désactiver la mise en surbrillance des références et des mots clés;Regex;Mettre en couleurs les expressions régulières;Mettre en surbrillance les composants connexes sous le curseur;Signaler les expressions régulières non valides;regex;expression régulière;Utiliser des couleurs améliorées;Modèle de couleurs de l'éditeur; Advanced options page keywords diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.it.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.it.xlf index 39ace602d6674..f6cf37d00242d 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.it.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.it.xlf @@ -19,7 +19,7 @@ Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme; - Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme; + Visualizza suggerimenti inline;Inserimento automatico di costrutti End;Modifica impostazioni di riformattazione;Modifica modalità struttura;Inserimento automatico di membri Interface e MustOverride;Mostra o nascondi separatori di riga routine;Attiva o disattiva i suggerimenti per la correzione degli errori;Attiva o disattiva l'evidenziazione di riferimenti e parole chiave;Regex;Colora espressioni regolari;Evidenzia i componenti correlati sotto il cursore;Segnala espressioni regolari non valide;regex;espressione regolare;Usa colori migliorati;Combinazione colori editor; Advanced options page keywords diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.ja.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.ja.xlf index ee623db1f5ba1..6c5a51b6074d4 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.ja.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.ja.xlf @@ -19,7 +19,7 @@ Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme; - Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme; + インラインのヒントを表示する;コンストラクトの終端の自動挿入;再フォーマット設定の変更;アウトライン モードの変更;Interface と MustOverride メンバーの自動挿入;プロシージャ行の区切り記号の表示/非表示;エラー修正候補のオン/オフの切り替え;参照とキーワードの強調表示のオン/オフの切り替え;Regex;正規表現の色付け;カーソルの下の関連コンポーネントの強調表示;無効な正規表現の報告;Regex;正規表現;拡張された色を使用する;エディターの配色; Advanced options page keywords diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.ko.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.ko.xlf index 27718e45189f3..1676ff6c48eed 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.ko.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.ko.xlf @@ -19,7 +19,7 @@ Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme; - Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme; + 인라인 힌트 표시; 맺음 구문 자동 삽입; 자동 서식 지정 설정 변경; 개요 모드 변경; 인터페이스 및 MustOverride 멤버 자동 삽입; 프로시저 줄 구분 기호 표시/숨기기; 오류 수정 제안 설정/해제; 참조 및 키워드 강조 표시 설정/해제; Regex; 정규식 색 지정; 커서 아래의 관련 구성 요소 강조 표시; 잘못된 정규식 보고; regex; 정규식; 향상된 색 사용; 편집기 색 구성표; Advanced options page keywords diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.pl.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.pl.xlf index e4867ebc0ec0b..1e500657f2141 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.pl.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.pl.xlf @@ -19,7 +19,7 @@ Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme; - Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme; + Wyświetlaj wskazówki w tekście;Automatyczne wstawianie konstrukcji końcowych;Zmień ustawienia formatowania kodu;Zmień tryb konspektu;Automatyczne wstawianie składowych Interface i MustOverride;Pokaż lub ukryj separatory wierszy procedury;Włącz lub wyłącz sugestie dotyczące poprawy błędów;Włącz lub wyłącz wyróżnianie odwołań i słów kluczowych;Wyrażenie regularne;Koloruj wyrażenia regularne;Wyróżnij pokrewne składniki wskazane przez kursor;Zgłaszaj nieprawidłowe wyrażenia regularne;wyrażenie regularne;wyrażenie regularne;Użyj ulepszonych kolorów;Schemat kolorów edytora; Advanced options page keywords diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.pt-BR.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.pt-BR.xlf index fe122bfcf8c84..0f58644c134dc 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.pt-BR.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.pt-BR.xlf @@ -19,7 +19,7 @@ Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme; - Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme; + Exibir as dicas embutidas;Inserção automática de constructos finais;Alterar as configurações de reformatação automática;Alterar o modo de estrutura de tópicos;Inserção automática dos membros Interface e MustOverride;Mostrar ou ocultar os separadores de linha de procedimento;Ativar ou desativar as sugestões para correção de erros;Ativar ou desativar o realce de referências e palavras-chave;Regex;Colorir as expressões regulares;Realçar os componentes relacionados sob o cursor;Relatar as expressões regulares inválidas;regex;expressão regular;Usar cores avançadas;Esquema de Cores do Editor; Advanced options page keywords diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.ru.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.ru.xlf index 93f35c9239f93..54fe830209e41 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.ru.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.ru.xlf @@ -19,7 +19,7 @@ Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme; - Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme; + Отображать встроенные подсказки;Автоматическая вставка конечных конструкций;Изменение параметров автоматического форматирования;Изменение режима структуры;Автоматическая вставка интерфейса и элементов MustOverride;Отображение или скрытие разделителей строк для процедуры;Включение или отключение предложений об исправлении ошибок;Включение или отключение выделения ссылок и ключевых слов;Регулярные выражения;Выделение регулярных выражений цветом;Выделение связанных компонентов под курсором;Выделение недопустимых регулярных выражений;регулярное выражение;регулярное выражение;Использование расширенных цветов;Цветовая схема редактора; Advanced options page keywords diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.tr.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.tr.xlf index 41ac1587168d3..9b61761bf5a82 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.tr.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.tr.xlf @@ -19,7 +19,7 @@ Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme; - Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme; + Satır içi ipuçlarını göster;Bitiş yapılarının otomatik olarak eklenmesi;Düzgün listeleme ayarlarını değiştir;Ana hat modunu değiştir;Interface ve MustOverride üyelerinin otomatik olarak eklenmesi;Yordam satır ayıraçlarını göster veya gizle;Hata düzeltme önerilerini aç veya kapat;Başvuruları ve anahtar sözcükleri vurgulamayı aç veya kapat;Normal ifade;Normal ifadeleri renklendir;İmlecin altındaki ilgili bileşenleri vurgula;Geçersiz normal ifadeleri bildir;normal ifade;normal ifade;Gelişmiş renkleri kullan;Düzenleyici Renk Düzeni; Advanced options page keywords diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.zh-Hans.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.zh-Hans.xlf index 8666a8099d652..660927eccecf9 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.zh-Hans.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Visual Basic @@ -19,7 +19,7 @@ Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme; - 显示内联参数名称提示;自动插入 End 构造;更改整齐排列设置;更改大纲模式;自动插入 Interface 和 MustOverride 成员;显示或隐藏过程行分隔符;打开或关闭错误纠正建议;打开或关闭引用和关键字的突出显示;正则表达式;对正则表达式着色;突出显示光标下的相关部分;报告无效正则表达式;regex;正则表达式;使用增强色;编辑器配色方案; + 显示内联提示;自动插入 End 构造;更改整齐排列设置;更改大纲模式;自动插入 Interface 和 MustOverride 成员;显示或隐藏过程行分隔符;打开或关闭错误纠正建议;打开或关闭引用和关键字的突出显示;正则表达式;对正则表达式着色;突出显示光标下的相关部分;报告无效正则表达式;regex;正则表达式;使用增强色;编辑器配色方案; Advanced options page keywords diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.zh-Hant.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.zh-Hant.xlf index 8aa6fe3ca5148..8cba14141c0cf 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.zh-Hant.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Visual Basic @@ -19,7 +19,7 @@ Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme; - Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme; + 顯示內嵌提示;自動插入 End 建構;變更美化列表設定;變更大綱模式;自動插入 Interface 和 MustOverride 成員;顯示或隱藏程序行分隔符號;開啟或關閉錯誤修正建議;開啟或關閉參考及關鍵字的醒目提示;Regex;為規則運算式著色;醒目提示游標下的相關元件;回報無效的規則運算式;regex;規則運算式;使用進階色彩;編輯器色彩配置; Advanced options page keywords diff --git a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/Resources.zh-Hans.xlf b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/Resources.zh-Hans.xlf index f1cd6f8eaef1b..28061c9ad3258 100644 --- a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/Resources.zh-Hans.xlf +++ b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/Resources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Can not create tool window. diff --git a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/Resources.zh-Hant.xlf b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/Resources.zh-Hant.xlf index 73418afdb48a9..8ceced4dd84f0 100644 --- a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/Resources.zh-Hant.xlf +++ b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/Resources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Can not create tool window. diff --git a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VSPackage.zh-Hans.xlf b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VSPackage.zh-Hans.xlf index 138b84eae6fa5..733155049da17 100644 --- a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VSPackage.zh-Hans.xlf +++ b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VSPackage.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Roslyn Diagnostics diff --git a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VSPackage.zh-Hant.xlf b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VSPackage.zh-Hant.xlf index 8c30199462e71..605cdeef84d1e 100644 --- a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VSPackage.zh-Hant.xlf +++ b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VSPackage.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Roslyn Diagnostics diff --git a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VisualStudioDiagnosticsWindow.vsct.zh-Hans.xlf b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VisualStudioDiagnosticsWindow.vsct.zh-Hans.xlf index 4f72f676b8e78..cd715e6140e83 100644 --- a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VisualStudioDiagnosticsWindow.vsct.zh-Hans.xlf +++ b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VisualStudioDiagnosticsWindow.vsct.zh-Hans.xlf @@ -1,6 +1,6 @@  - + cmdIDRoslynDiagnosticWindow diff --git a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VisualStudioDiagnosticsWindow.vsct.zh-Hant.xlf b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VisualStudioDiagnosticsWindow.vsct.zh-Hant.xlf index f54af21826e8d..e152a487fcce9 100644 --- a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VisualStudioDiagnosticsWindow.vsct.zh-Hant.xlf +++ b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VisualStudioDiagnosticsWindow.vsct.zh-Hant.xlf @@ -1,6 +1,6 @@  - + cmdIDRoslynDiagnosticWindow diff --git a/src/VisualStudio/Xaml/Impl/Features/Diagnostics/IXamlPullDiagnosticService.cs b/src/VisualStudio/Xaml/Impl/Features/Diagnostics/IXamlPullDiagnosticService.cs new file mode 100644 index 0000000000000..b9ee8fff86e1a --- /dev/null +++ b/src/VisualStudio/Xaml/Impl/Features/Diagnostics/IXamlPullDiagnosticService.cs @@ -0,0 +1,28 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Host; + +namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Diagnostics +{ + internal interface IXamlPullDiagnosticService : ILanguageService + { + /// + /// Get diagnostic report for the given TextDocument. + /// + /// The TextDocument to get diagnostic report from. Should not be null. + /// Previous ResultId we get from the Pull Diagnostic request. This can null when we don't see a corresponding previousResultId for this document from the request. + /// cancellationToken + /// A XamlDiagnosticReport which will be used as the response to the Pull Diagnostic request. + Task GetDiagnosticReportAsync(TextDocument document, string? previousResultId, CancellationToken cancellationToken); + } +} diff --git a/src/VisualStudio/Xaml/Impl/Features/Diagnostics/XamlDiagnostic.cs b/src/VisualStudio/Xaml/Impl/Features/Diagnostics/XamlDiagnostic.cs new file mode 100644 index 0000000000000..76c24cb4aa9f3 --- /dev/null +++ b/src/VisualStudio/Xaml/Impl/Features/Diagnostics/XamlDiagnostic.cs @@ -0,0 +1,18 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Diagnostics +{ + internal class XamlDiagnostic + { + public string? Code { get; set; } + public string? Message { get; set; } + public XamlDiagnosticSeverity Severity { get; set; } + public int Offset { get; set; } + public int Length { get; set; } + public string? Tool { get; set; } + public string? ExtendedMessage { get; set; } + public string[]? CustomTags { get; set; } + } +} diff --git a/src/VisualStudio/Xaml/Impl/Features/Diagnostics/XamlDiagnosticReport.cs b/src/VisualStudio/Xaml/Impl/Features/Diagnostics/XamlDiagnosticReport.cs new file mode 100644 index 0000000000000..f730bb087c388 --- /dev/null +++ b/src/VisualStudio/Xaml/Impl/Features/Diagnostics/XamlDiagnosticReport.cs @@ -0,0 +1,20 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Immutable; + +namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Diagnostics +{ + internal class XamlDiagnosticReport + { + public string? ResultId { get; set; } + public ImmutableArray? Diagnostics { get; set; } + + public XamlDiagnosticReport(string? resultId = null, ImmutableArray? diagnostics = null) + { + this.ResultId = resultId; + this.Diagnostics = diagnostics; + } + } +} diff --git a/src/VisualStudio/Xaml/Impl/Features/Diagnostics/XamlDiagnosticSeverity.cs b/src/VisualStudio/Xaml/Impl/Features/Diagnostics/XamlDiagnosticSeverity.cs new file mode 100644 index 0000000000000..1bd67d73f64f1 --- /dev/null +++ b/src/VisualStudio/Xaml/Impl/Features/Diagnostics/XamlDiagnosticSeverity.cs @@ -0,0 +1,29 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Diagnostics +{ + internal enum XamlDiagnosticSeverity + { + /// + /// Represents an error. + /// + Error, + + /// + /// Represent a warning. + /// + Warning, + + /// + /// Represents an informational note. + /// + Message, + + /// + /// Represents a hidden note. + /// + Hidden + } +} diff --git a/src/VisualStudio/Xaml/Impl/Implementation/LanguageClient/XamlInProcLanguageClient.cs b/src/VisualStudio/Xaml/Impl/Implementation/LanguageClient/XamlInProcLanguageClient.cs index d843c195ba43d..db3077b54e1b9 100644 --- a/src/VisualStudio/Xaml/Impl/Implementation/LanguageClient/XamlInProcLanguageClient.cs +++ b/src/VisualStudio/Xaml/Impl/Implementation/LanguageClient/XamlInProcLanguageClient.cs @@ -51,8 +51,10 @@ protected internal override VSServerCapabilities GetCapabilities() OnAutoInsertProvider = new DocumentOnAutoInsertOptions { TriggerCharacters = new[] { "=", "/", ">" } }, TextDocumentSync = new TextDocumentSyncOptions { - Change = TextDocumentSyncKind.None + Change = TextDocumentSyncKind.None, + OpenClose = false }, + SupportsDiagnosticRequests = true, }; } } diff --git a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Extensions/SolutionExtensions.cs b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Extensions/SolutionExtensions.cs new file mode 100644 index 0000000000000..73d6b7e5fbe45 --- /dev/null +++ b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Extensions/SolutionExtensions.cs @@ -0,0 +1,20 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Editor.Xaml; + +namespace Microsoft.VisualStudio.LanguageServices.Xaml.Implementation.LanguageServer.Extensions +{ + internal static class SolutionExtensions + { + public static IEnumerable GetXamlProjects(this Solution solution) + => solution.Projects.Where(p => p.Language == StringConstants.XamlLanguageName); + } +} diff --git a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Diagnostics/AbstractPullDiagnosticHandler.cs b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Diagnostics/AbstractPullDiagnosticHandler.cs new file mode 100644 index 0000000000000..c173a15fcb817 --- /dev/null +++ b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Diagnostics/AbstractPullDiagnosticHandler.cs @@ -0,0 +1,186 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.LanguageServer; +using Microsoft.CodeAnalysis.LanguageServer.Handler; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Shared.Extensions; +using Microsoft.CodeAnalysis.Text; +using Microsoft.VisualStudio.LanguageServer.Protocol; +using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Diagnostics; +using Roslyn.Utilities; +using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; + +namespace Microsoft.VisualStudio.LanguageServices.Xaml.Implementation.LanguageServer.Handler.Diagnostics +{ + /// + /// Root type for both document and workspace diagnostic pull requests. + /// + internal abstract class AbstractPullDiagnosticHandler : IRequestHandler + where TReport : DiagnosticReport + { + private readonly ILspSolutionProvider _solutionProvider; + private readonly IXamlPullDiagnosticService _xamlDiagnosticService; + + public abstract TextDocumentIdentifier? GetTextDocumentIdentifier(TDiagnosticsParams request); + + /// + /// Gets the progress object to stream results to. + /// + protected abstract IProgress? GetProgress(TDiagnosticsParams diagnosticsParams); + + /// + /// Retrieve the previous results we reported. + /// + protected abstract DiagnosticParams[]? GetPreviousResults(TDiagnosticsParams diagnosticsParams); + + /// + /// Returns all the documents that should be processed. + /// + protected abstract ImmutableArray GetDocuments(RequestContext context); + + /// + /// Creates the instance we'll report back to clients to let them know our + /// progress. + /// + protected abstract TReport CreateReport(TextDocumentIdentifier? identifier, VSDiagnostic[]? diagnostics, string? resultId); + + protected AbstractPullDiagnosticHandler(ILspSolutionProvider solutionProvider, IXamlPullDiagnosticService xamlDiagnosticService) + { + _solutionProvider = solutionProvider; + _xamlDiagnosticService = xamlDiagnosticService; + } + + public async Task HandleRequestAsync(TDiagnosticsParams diagnosticsParams, RequestContext context, CancellationToken cancellationToken) + { + using var progress = BufferedProgress.Create(GetProgress(diagnosticsParams)); + + // Get the set of results the request said were previously reported. + var previousResults = GetPreviousResults(diagnosticsParams); + + var documentToPreviousResultId = new Dictionary(); + if (previousResults != null) + { + // Go through the previousResults and check if we need to remove diagnostic information for any documents + foreach (var previousResult in previousResults) + { + if (previousResult.TextDocument != null) + { + var document = _solutionProvider.GetDocument(previousResult.TextDocument); + if (document == null) + { + // We can no longer get this document, return null for both diagnostics and resultId + progress.Report(CreateReport(previousResult.TextDocument, diagnostics: null, resultId: null)); + } + else + { + // Cache the document to previousResultId mapping so we can easily retrieve the resultId later. + documentToPreviousResultId[document] = previousResult.PreviousResultId; + } + } + } + } + + // Go through the documents that we need to process and call XamlPullDiagnosticService to get the diagnostic report + foreach (var document in GetDocuments(context)) + { + var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); + var documentId = ProtocolConversions.DocumentToTextDocumentIdentifier(document); + + // If we can get a previousId of the document, use it, + // otherwise use null as the previousId to pass into the XamlPullDiagnosticService + var previousResultId = documentToPreviousResultId.TryGetValue(document, out var id) ? id : null; + + // Call XamlPullDiagnosticService to get the diagnostic report for this document. + // We will compute what to report inside XamlPullDiagnosticService, for example, whether we should keep using the previousId or use a new resultId, + // and the handler here just return the result get from XamlPullDiagnosticService. + var diagnosticReport = await _xamlDiagnosticService.GetDiagnosticReportAsync(document, previousResultId, cancellationToken).ConfigureAwait(false); + progress.Report(CreateReport( + documentId, + ConvertToVSDiagnostics(diagnosticReport.Diagnostics, document, text), + diagnosticReport.ResultId)); + } + + return progress.GetValues(); + } + + /// + /// Convert XamlDiagnostics to VSDiagnostics + /// + private static VSDiagnostic[]? ConvertToVSDiagnostics(ImmutableArray? xamlDiagnostics, Document document, SourceText text) + { + if (xamlDiagnostics == null) + { + return null; + } + + var project = document.Project; + return xamlDiagnostics.Value.Select(d => new VSDiagnostic() + { + Code = d.Code, + Message = d.Message ?? string.Empty, + ExpandedMessage = d.ExtendedMessage, + Severity = ConvertDiagnosticSeverity(d.Severity), + Range = ProtocolConversions.TextSpanToRange(new TextSpan(d.Offset, d.Length), text), + Tags = ConvertTags(d), + Source = d.Tool, + Projects = new[] + { + new ProjectAndContext + { + ProjectIdentifier = project.Id.Id.ToString(), + ProjectName = project.Name, + }, + }, + }).ToArray(); + } + + private static LSP.DiagnosticSeverity ConvertDiagnosticSeverity(XamlDiagnosticSeverity severity) + => severity switch + { + // Hidden is translated in ConvertTags to pass along appropriate _ms tags + // that will hide the item in a client that knows about those tags. + XamlDiagnosticSeverity.Hidden => LSP.DiagnosticSeverity.Hint, + XamlDiagnosticSeverity.Message => LSP.DiagnosticSeverity.Information, + XamlDiagnosticSeverity.Warning => LSP.DiagnosticSeverity.Warning, + XamlDiagnosticSeverity.Error => LSP.DiagnosticSeverity.Error, + _ => throw ExceptionUtilities.UnexpectedValue(severity), + }; + + /// + /// If you make change in this method, please also update the corresponding file in + /// src\Features\LanguageServer\Protocol\Handler\Diagnostics\AbstractPullDiagnosticHandler.cs + /// + private static DiagnosticTag[] ConvertTags(XamlDiagnostic diagnostic) + { + using var _ = ArrayBuilder.GetInstance(out var result); + + result.Add(VSDiagnosticTags.IntellisenseError); + + if (diagnostic.Severity == XamlDiagnosticSeverity.Hidden) + { + result.Add(VSDiagnosticTags.HiddenInEditor); + result.Add(VSDiagnosticTags.HiddenInErrorList); + result.Add(VSDiagnosticTags.SuppressEditorToolTip); + } + else + { + result.Add(VSDiagnosticTags.VisibleInErrorList); + } + + if (diagnostic.CustomTags?.Contains(WellKnownDiagnosticTags.Unnecessary) == true) + result.Add(DiagnosticTag.Unnecessary); + + return result.ToArray(); + } + } +} diff --git a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Diagnostics/DocumentPullDiagnosticHandler.cs b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Diagnostics/DocumentPullDiagnosticHandler.cs new file mode 100644 index 0000000000000..4cd1f677b7ce3 --- /dev/null +++ b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Diagnostics/DocumentPullDiagnosticHandler.cs @@ -0,0 +1,51 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Immutable; +using System.Composition; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Editor.Xaml; +using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.LanguageServer; +using Microsoft.CodeAnalysis.LanguageServer.Handler; +using Microsoft.VisualStudio.LanguageServer.Protocol; +using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Diagnostics; + +namespace Microsoft.VisualStudio.LanguageServices.Xaml.Implementation.LanguageServer.Handler.Diagnostics +{ + [ExportLspMethod(MSLSPMethods.DocumentPullDiagnosticName, mutatesSolutionState: false, StringConstants.XamlLanguageName), Shared] + internal class DocumentPullDiagnosticHandler : AbstractPullDiagnosticHandler + { + [ImportingConstructor] + [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + public DocumentPullDiagnosticHandler( + ILspSolutionProvider solutionProvider, + IXamlPullDiagnosticService xamlPullDiagnosticService) + : base(solutionProvider, xamlPullDiagnosticService) + { } + + public override TextDocumentIdentifier? GetTextDocumentIdentifier(DocumentDiagnosticsParams request) + => request.TextDocument; + + protected override DiagnosticReport CreateReport(TextDocumentIdentifier? identifier, VSDiagnostic[]? diagnostics, string? resultId) + => new DiagnosticReport { Diagnostics = diagnostics, ResultId = resultId }; + + protected override ImmutableArray GetDocuments(RequestContext context) + { + // For the single document case, that is the only doc we want to process. + // + // Note: context.Document may be null in the case where the client is asking about a document that we have + // since removed from the workspace. In this case, we don't really have anything to process. + // GetPreviousResults will be used to properly realize this and notify the client that the doc is gone. + return context.Document == null ? ImmutableArray.Empty : ImmutableArray.Create(context.Document); + } + + protected override DiagnosticParams[]? GetPreviousResults(DocumentDiagnosticsParams diagnosticsParams) + => new[] { diagnosticsParams }; + + protected override IProgress? GetProgress(DocumentDiagnosticsParams diagnosticsParams) + => diagnosticsParams.PartialResultToken; + } +} diff --git a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Diagnostics/WorkspacePullDiagnosticHandler.cs b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Diagnostics/WorkspacePullDiagnosticHandler.cs new file mode 100644 index 0000000000000..2bc317f980ade --- /dev/null +++ b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Diagnostics/WorkspacePullDiagnosticHandler.cs @@ -0,0 +1,60 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Immutable; +using System.Composition; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Editor.Xaml; +using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.LanguageServer; +using Microsoft.CodeAnalysis.LanguageServer.Handler; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.VisualStudio.LanguageServer.Protocol; +using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Diagnostics; +using Microsoft.VisualStudio.LanguageServices.Xaml.Implementation.LanguageServer.Extensions; + +namespace Microsoft.VisualStudio.LanguageServices.Xaml.Implementation.LanguageServer.Handler.Diagnostics +{ + [ExportLspMethod(MSLSPMethods.WorkspacePullDiagnosticName, mutatesSolutionState: false, StringConstants.XamlLanguageName), Shared] + internal class WorkspacePullDiagnosticHandler : AbstractPullDiagnosticHandler + { + [ImportingConstructor] + [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + public WorkspacePullDiagnosticHandler( + ILspSolutionProvider solutionProvider, + IXamlPullDiagnosticService xamlPullDiagnosticService) + : base(solutionProvider, xamlPullDiagnosticService) + { } + + public override TextDocumentIdentifier? GetTextDocumentIdentifier(WorkspaceDocumentDiagnosticsParams request) => null; + + protected override WorkspaceDiagnosticReport CreateReport(TextDocumentIdentifier? identifier, VSDiagnostic[]? diagnostics, string? resultId) + => new WorkspaceDiagnosticReport { TextDocument = identifier, Diagnostics = diagnostics, ResultId = resultId }; + + /// + /// Collect all the opened documents from solution. + /// In XamlLanguageService, we are only able to retrieve diagnostic information for opened documents. + /// So this is the same error experience we have now in full VS scenario. + /// + protected override ImmutableArray GetDocuments(RequestContext context) + { + using var _ = ArrayBuilder.GetInstance(out var result); + var projects = context.Solution.GetXamlProjects(); + foreach (var project in projects) + { + result.AddRange(project.Documents); + } + + return result.Distinct().ToImmutableArray(); + } + + protected override DiagnosticParams[]? GetPreviousResults(WorkspaceDocumentDiagnosticsParams diagnosticsParams) + => diagnosticsParams.PreviousResults; + + protected override IProgress? GetProgress(WorkspaceDocumentDiagnosticsParams diagnosticsParams) + => diagnosticsParams.PartialResultToken; + } +} diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.de.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.de.xlf index 822a18984147e..dc43b5f84eab4 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.de.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.de.xlf @@ -19,7 +19,7 @@ XAML Language Server Client - XAML Language Server Client + Client des XAML-Sprachservers diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.es.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.es.xlf index 78aaf17078afb..48b42cfdeaab6 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.es.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.es.xlf @@ -19,7 +19,7 @@ XAML Language Server Client - XAML Language Server Client + Cliente de servidor de lenguaje XAML diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.fr.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.fr.xlf index b3310591d6135..f72fd9f363b39 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.fr.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.fr.xlf @@ -19,7 +19,7 @@ XAML Language Server Client - XAML Language Server Client + Client du serveur de langage XAML diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.it.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.it.xlf index e770e56dbae43..dd99f2cbaa8f8 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.it.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.it.xlf @@ -19,7 +19,7 @@ XAML Language Server Client - XAML Language Server Client + Client del server di linguaggio XAML diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.ja.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.ja.xlf index da41cedaf2f98..8b16cd6590469 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.ja.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.ja.xlf @@ -19,7 +19,7 @@ XAML Language Server Client - XAML Language Server Client + XAML 言語サーバー クライアント diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.ko.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.ko.xlf index 6d7f65cd090e3..a11ca0bb4fbd1 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.ko.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.ko.xlf @@ -19,7 +19,7 @@ XAML Language Server Client - XAML Language Server Client + XAML 언어 서버 클라이언트 diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.pl.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.pl.xlf index 8cd809d35eb5d..4a2b0226b69ae 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.pl.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.pl.xlf @@ -19,7 +19,7 @@ XAML Language Server Client - XAML Language Server Client + Klient serwera języka XAML diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.pt-BR.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.pt-BR.xlf index 7138d12b9ad71..5ea97dfd0f0b9 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.pt-BR.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.pt-BR.xlf @@ -19,7 +19,7 @@ XAML Language Server Client - XAML Language Server Client + Cliente do Servidor de Linguagem XAML diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.ru.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.ru.xlf index f94e527432758..4ed371f17f257 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.ru.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.ru.xlf @@ -19,7 +19,7 @@ XAML Language Server Client - XAML Language Server Client + Клиент языкового сервера XAML diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.tr.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.tr.xlf index c5fa6321f2253..e59e5bdfbfdf9 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.tr.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.tr.xlf @@ -19,7 +19,7 @@ XAML Language Server Client - XAML Language Server Client + XAML Dil Sunucusu İstemcisi diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.zh-Hans.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.zh-Hans.xlf index 7dfeda74a88ab..e093ddb145522 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.zh-Hans.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Remove &and Sort Namespaces diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.zh-Hant.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.zh-Hant.xlf index 92c7087ed9944..d3481602fe0d1 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.zh-Hant.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Remove &and Sort Namespaces @@ -19,7 +19,7 @@ XAML Language Server Client - XAML Language Server Client + XAML 語言伺服器用戶端 diff --git a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.ja.xlf b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.ja.xlf index 698d74492b5f6..0da9178c1248c 100644 --- a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.ja.xlf +++ b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.ja.xlf @@ -59,7 +59,7 @@ Implement Interface - インターフェイスを実装します。 + インターフェイスを実装します diff --git a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.zh-Hans.xlf b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.zh-Hans.xlf index f3aa0d431c08a..b8f01934dad7e 100644 --- a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.zh-Hans.xlf +++ b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Indentation preferences diff --git a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.zh-Hant.xlf b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.zh-Hant.xlf index 9e24387134fb9..aabf840735849 100644 --- a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.zh-Hant.xlf +++ b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Indentation preferences @@ -54,7 +54,7 @@ Only attributes, constructor initializers, expressions or statements can be made explicit - 只有屬性、建構函式初始設定式、運算式或陳述式才可明確設定。 + 只有屬性、建構函式初始設定式、運算式或陳述式才可明確設定 diff --git a/src/Workspaces/CSharpTest/OrganizeImports/OrganizeUsingsTests.cs b/src/Workspaces/CSharpTest/OrganizeImports/OrganizeUsingsTests.cs index b8d06b5efe970..f6b730f8dd6da 100644 --- a/src/Workspaces/CSharpTest/OrganizeImports/OrganizeUsingsTests.cs +++ b/src/Workspaces/CSharpTest/OrganizeImports/OrganizeUsingsTests.cs @@ -4,6 +4,7 @@ #nullable disable +using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editing; diff --git a/src/Workspaces/Core/Desktop/xlf/WorkspaceDesktopResources.zh-Hans.xlf b/src/Workspaces/Core/Desktop/xlf/WorkspaceDesktopResources.zh-Hans.xlf index 1b22574fa628c..c93d52f0ff76a 100644 --- a/src/Workspaces/Core/Desktop/xlf/WorkspaceDesktopResources.zh-Hans.xlf +++ b/src/Workspaces/Core/Desktop/xlf/WorkspaceDesktopResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Invalid assembly name diff --git a/src/Workspaces/Core/Desktop/xlf/WorkspaceDesktopResources.zh-Hant.xlf b/src/Workspaces/Core/Desktop/xlf/WorkspaceDesktopResources.zh-Hant.xlf index f5aa489884a41..eb65ab4f52ea7 100644 --- a/src/Workspaces/Core/Desktop/xlf/WorkspaceDesktopResources.zh-Hant.xlf +++ b/src/Workspaces/Core/Desktop/xlf/WorkspaceDesktopResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Invalid assembly name diff --git a/src/Workspaces/Core/MSBuild/Microsoft.CodeAnalysis.Workspaces.MSBuild.csproj b/src/Workspaces/Core/MSBuild/Microsoft.CodeAnalysis.Workspaces.MSBuild.csproj index 4f635d489acee..5a61127cf4389 100644 --- a/src/Workspaces/Core/MSBuild/Microsoft.CodeAnalysis.Workspaces.MSBuild.csproj +++ b/src/Workspaces/Core/MSBuild/Microsoft.CodeAnalysis.Workspaces.MSBuild.csproj @@ -25,7 +25,7 @@ - + diff --git a/src/Workspaces/Core/MSBuild/xlf/WorkspaceMSBuildResources.ja.xlf b/src/Workspaces/Core/MSBuild/xlf/WorkspaceMSBuildResources.ja.xlf index 3c8709032ef6e..ac90e805578e7 100644 --- a/src/Workspaces/Core/MSBuild/xlf/WorkspaceMSBuildResources.ja.xlf +++ b/src/Workspaces/Core/MSBuild/xlf/WorkspaceMSBuildResources.ja.xlf @@ -14,7 +14,7 @@ Msbuild failed when processing the file '{0}' with message: {1} - '{0}' 파일 처리 시 Msbuild에서 실패했습니다. 메시지: {1} + ファイル '{0}' の処理中に MSBuild が次のメッセージで失敗しました: {1} diff --git a/src/Workspaces/Core/MSBuild/xlf/WorkspaceMSBuildResources.ko.xlf b/src/Workspaces/Core/MSBuild/xlf/WorkspaceMSBuildResources.ko.xlf index 38e2fd6e00a2e..9ceafe412042c 100644 --- a/src/Workspaces/Core/MSBuild/xlf/WorkspaceMSBuildResources.ko.xlf +++ b/src/Workspaces/Core/MSBuild/xlf/WorkspaceMSBuildResources.ko.xlf @@ -14,7 +14,7 @@ Msbuild failed when processing the file '{0}' with message: {1} - {0}' 파일 처리 시 Msbuild에서 실패했습니다. 메시지: {1} + '{0}' 파일 처리 시 Msbuild에서 실패했습니다. 메시지: {1} diff --git a/src/Workspaces/Core/MSBuild/xlf/WorkspaceMSBuildResources.zh-Hans.xlf b/src/Workspaces/Core/MSBuild/xlf/WorkspaceMSBuildResources.zh-Hans.xlf index 56be471fe5b65..44b185a42a9b6 100644 --- a/src/Workspaces/Core/MSBuild/xlf/WorkspaceMSBuildResources.zh-Hans.xlf +++ b/src/Workspaces/Core/MSBuild/xlf/WorkspaceMSBuildResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Found project reference without a matching metadata reference: {0} diff --git a/src/Workspaces/Core/MSBuild/xlf/WorkspaceMSBuildResources.zh-Hant.xlf b/src/Workspaces/Core/MSBuild/xlf/WorkspaceMSBuildResources.zh-Hant.xlf index b1487ce018746..5c8efcd3c06ae 100644 --- a/src/Workspaces/Core/MSBuild/xlf/WorkspaceMSBuildResources.zh-Hant.xlf +++ b/src/Workspaces/Core/MSBuild/xlf/WorkspaceMSBuildResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Found project reference without a matching metadata reference: {0} diff --git a/src/Workspaces/Core/Portable/PublicAPI.Unshipped.txt b/src/Workspaces/Core/Portable/PublicAPI.Unshipped.txt index d0d6e5f508b3e..c6fb5237cdedd 100644 --- a/src/Workspaces/Core/Portable/PublicAPI.Unshipped.txt +++ b/src/Workspaces/Core/Portable/PublicAPI.Unshipped.txt @@ -1,2 +1,8 @@ +Microsoft.CodeAnalysis.Project.GetSourceGeneratedDocumentAsync(Microsoft.CodeAnalysis.DocumentId documentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +Microsoft.CodeAnalysis.Project.GetSourceGeneratedDocumentsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask> const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.RecordName = "record name" -> string Microsoft.CodeAnalysis.Editing.DeclarationKind.Record = 29 -> Microsoft.CodeAnalysis.Editing.DeclarationKind +Microsoft.CodeAnalysis.Solution.GetSourceGeneratedDocumentAsync(Microsoft.CodeAnalysis.DocumentId documentId, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.ValueTask +Microsoft.CodeAnalysis.SourceGeneratedDocument +Microsoft.CodeAnalysis.SourceGeneratedDocument.HintName.get -> string +Microsoft.CodeAnalysis.SourceGeneratedDocument.SourceGenerator.get -> Microsoft.CodeAnalysis.ISourceGenerator \ No newline at end of file diff --git a/src/Workspaces/Core/Portable/SemanticModelReuse/AbstractSemanticModelReuseLanguageService.cs b/src/Workspaces/Core/Portable/SemanticModelReuse/AbstractSemanticModelReuseLanguageService.cs index 7b325a4ab45a8..ba205a043d92f 100644 --- a/src/Workspaces/Core/Portable/SemanticModelReuse/AbstractSemanticModelReuseLanguageService.cs +++ b/src/Workspaces/Core/Portable/SemanticModelReuse/AbstractSemanticModelReuseLanguageService.cs @@ -2,11 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.LanguageServices; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SemanticModelReuse { @@ -20,6 +21,11 @@ internal abstract class AbstractSemanticModelReuseLanguageService< where TBasePropertyDeclarationSyntax : TMemberDeclarationSyntax where TAccessorDeclarationSyntax : SyntaxNode { + /// + /// Used to make sure we only report one watson per sessoin here. + /// + private static bool s_watsonReported; + protected abstract ISyntaxFacts SyntaxFacts { get; } public abstract SyntaxNode? TryGetContainingMethodBodyForSpeculation(SyntaxNode node); @@ -28,14 +34,44 @@ internal abstract class AbstractSemanticModelReuseLanguageService< protected abstract SyntaxList GetAccessors(TBasePropertyDeclarationSyntax baseProperty); protected abstract TBasePropertyDeclarationSyntax GetBasePropertyDeclaration(TAccessorDeclarationSyntax accessor); - public Task TryGetSpeculativeSemanticModelAsync(SemanticModel previousSemanticModel, SyntaxNode currentBodyNode, CancellationToken cancellationToken) + public async Task TryGetSpeculativeSemanticModelAsync(SemanticModel previousSemanticModel, SyntaxNode currentBodyNode, CancellationToken cancellationToken) { var previousSyntaxTree = previousSemanticModel.SyntaxTree; var currentSyntaxTree = currentBodyNode.SyntaxTree; - // This operation is only valid if top-level equivalent trees were passed in. - Contract.ThrowIfFalse(previousSyntaxTree.IsEquivalentTo(currentSyntaxTree, topLevel: true)); - return TryGetSpeculativeSemanticModelWorkerAsync(previousSemanticModel, currentBodyNode, cancellationToken); + // This operation is only valid if top-level equivalent trees were passed in. If they're not equivalent + // then something very bad happened as we did that document.Project.GetDependentSemanticVersionAsync was + // still the same. So somehow w don't have top-level equivalence, but we do have the same semantic version. + // + // log a NFW to help diagnose what the source looks like as it may help us determine what sort of edit is + // causing this. + if (!previousSyntaxTree.IsEquivalentTo(currentSyntaxTree, topLevel: true)) + { + if (!s_watsonReported) + { + s_watsonReported = true; + + try + { + throw new InvalidOperationException( + $@"Syntax trees should have been equivalent. +--- +{previousSyntaxTree.GetText(CancellationToken.None)} +--- +{currentSyntaxTree.GetText(CancellationToken.None)} +---"); + + } + catch (Exception e) when (FatalError.ReportAndCatch(e)) + { + } + } + + return null; + } + + return await TryGetSpeculativeSemanticModelWorkerAsync( + previousSemanticModel, currentBodyNode, cancellationToken).ConfigureAwait(false); } protected SyntaxNode GetPreviousBodyNode(SyntaxNode previousRoot, SyntaxNode currentRoot, SyntaxNode currentBodyNode) diff --git a/src/Workspaces/Core/Portable/Shared/Extensions/CodeActionExtensions.cs b/src/Workspaces/Core/Portable/Shared/Extensions/CodeActionExtensions.cs new file mode 100644 index 0000000000000..e604e33c3e8ea --- /dev/null +++ b/src/Workspaces/Core/Portable/Shared/Extensions/CodeActionExtensions.cs @@ -0,0 +1,26 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.Shared.Utilities; + +namespace Microsoft.CodeAnalysis.Shared.Extensions +{ + internal static class CodeActionExtensions + { + public static async Task GetRequiredChangedSolutionAsync(this CodeAction codeAction, IProgressTracker progressTracker, CancellationToken cancellationToken) + { + var solution = await codeAction.GetChangedSolutionAsync(progressTracker, cancellationToken).ConfigureAwait(false); + if (solution is null) + { + throw new InvalidOperationException(string.Format(WorkspacesResources.CodeAction__0__did_not_produce_a_changed_solution, codeAction.Title)); + } + + return solution; + } + } +} diff --git a/src/Workspaces/Core/Portable/Shared/TestHooks/IAsynchronousOperationListener.cs b/src/Workspaces/Core/Portable/Shared/TestHooks/IAsynchronousOperationListener.cs index cc2b478b9fac7..407d85905a1f9 100644 --- a/src/Workspaces/Core/Portable/Shared/TestHooks/IAsynchronousOperationListener.cs +++ b/src/Workspaces/Core/Portable/Shared/TestHooks/IAsynchronousOperationListener.cs @@ -8,6 +8,6 @@ namespace Microsoft.CodeAnalysis.Shared.TestHooks { internal interface IAsynchronousOperationListener : IExpeditableDelaySource { - IAsyncToken BeginAsyncOperation(string name, object tag = null, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0); + IAsyncToken BeginAsyncOperation(string name, object? tag = null, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0); } } diff --git a/src/Workspaces/Core/Portable/Workspace/Host/Metadata/FrameworkAssemblyPathResolverFactory.cs b/src/Workspaces/Core/Portable/Workspace/Host/Metadata/FrameworkAssemblyPathResolverFactory.cs index f3a4ff7698148..7c9385d6f038b 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/Metadata/FrameworkAssemblyPathResolverFactory.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/Metadata/FrameworkAssemblyPathResolverFactory.cs @@ -4,10 +4,7 @@ using System; using System.Composition; -using System.Threading; -using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { @@ -34,10 +31,10 @@ public Service() // return false; //} - public Task ResolveAssemblyPathAsync(ProjectId projectId, string assemblyName, string? fullyQualifiedTypeName, CancellationToken cancellationToken) + public string? ResolveAssemblyPath(ProjectId projectId, string assemblyName, string? fullyQualifiedTypeName) { // Assembly path resolution not supported at the default workspace level. - return SpecializedTasks.Null(); + return null; } } } diff --git a/src/Workspaces/Core/Portable/Workspace/Host/Metadata/IFrameworkAssemblyPathResolver.cs b/src/Workspaces/Core/Portable/Workspace/Host/Metadata/IFrameworkAssemblyPathResolver.cs index b68e05fd3b48e..dac42355f9408 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/Metadata/IFrameworkAssemblyPathResolver.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/Metadata/IFrameworkAssemblyPathResolver.cs @@ -2,9 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Threading; -using System.Threading.Tasks; - namespace Microsoft.CodeAnalysis.Host { /// @@ -22,7 +19,7 @@ internal interface IFrameworkAssemblyPathResolver : IWorkspaceService /// exist in the assembly. /// The project context to search within. /// The name of the assembly to try to resolve. - Task ResolveAssemblyPathAsync(ProjectId projectId, string assemblyName, string? fullyQualifiedName, CancellationToken cancellationToken); + string? ResolveAssemblyPath(ProjectId projectId, string assemblyName, string? fullyQualifiedName); // bool CanResolveType(ProjectId projectId, string assemblyName, string fullyQualifiedTypeName); } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/DocumentState.cs b/src/Workspaces/Core/Portable/Workspace/Solution/DocumentState.cs index 6c0cd73bb94ff..d4e83de88c6d2 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/DocumentState.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/DocumentState.cs @@ -32,7 +32,7 @@ internal partial class DocumentState : TextDocumentState // null if the document doesn't support syntax trees: private readonly ValueSource? _treeSource; - private DocumentState( + protected DocumentState( HostLanguageServices languageServices, SolutionServices solutionServices, IDocumentServiceProvider? documentServiceProvider, diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/Project.cs b/src/Workspaces/Core/Portable/Workspace/Solution/Project.cs index da0427cefb344..a7bd7b75482f5 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/Project.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/Project.cs @@ -12,6 +12,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; +using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Collections.Immutable; @@ -28,6 +29,7 @@ public partial class Project private readonly Solution _solution; private readonly ProjectState _projectState; private ImmutableHashMap _idToDocumentMap = ImmutableHashMap.Empty; + private ImmutableHashMap _idToSourceGeneratedDocumentMap = ImmutableHashMap.Empty; private ImmutableHashMap _idToAdditionalDocumentMap = ImmutableHashMap.Empty; private ImmutableHashMap _idToAnalyzerConfigDocumentMap = ImmutableHashMap.Empty; @@ -171,7 +173,8 @@ internal Project(Solution solution, ProjectState projectState) public IReadOnlyList AdditionalDocumentIds => _projectState.AdditionalDocumentIds; /// - /// All the documents associated with this project. + /// All the regular documents associated with this project. Documents produced from source generators are returned by + /// . /// public IEnumerable Documents => _projectState.DocumentIds.Select(GetDocument)!; @@ -253,6 +256,68 @@ public bool ContainsAnalyzerConfigDocument(DocumentId documentId) return ImmutableHashMapExtensions.GetOrAdd(ref _idToAnalyzerConfigDocumentMap, documentId, s_createAnalyzerConfigDocumentFunction, this); } + public async ValueTask> GetSourceGeneratedDocumentsAsync(CancellationToken cancellationToken = default) + { + var generatedDocumentStates = await _solution.State.GetSourceGeneratedDocumentStatesAsync(this.State, cancellationToken).ConfigureAwait(false); + using var _ = ArrayBuilder.GetInstance(generatedDocumentStates.Length, out var builder); + + foreach (var generatedDocumentState in generatedDocumentStates) + { + builder.Add(ImmutableHashMapExtensions.GetOrAdd(ref _idToSourceGeneratedDocumentMap, generatedDocumentState.Id, s_createSourceGeneratedDocumentFunction, (generatedDocumentState, this))); + } + + return builder.ToImmutable(); + } + + public async ValueTask GetSourceGeneratedDocumentAsync(DocumentId documentId, CancellationToken cancellationToken = default) + { + // Quick check first: if we already have created a SourceGeneratedDocument wrapper, we're good + if (_idToSourceGeneratedDocumentMap.TryGetValue(documentId, out var sourceGeneratedDocument)) + { + return sourceGeneratedDocument; + } + + // We'll have to run generators if we haven't already and now try to find it. + var generatedDocumentStates = await _solution.State.GetSourceGeneratedDocumentStatesAsync(this.State, cancellationToken).ConfigureAwait(false); + + foreach (var generatedDocumentState in generatedDocumentStates) + { + if (generatedDocumentState.Id == documentId) + { + return ImmutableHashMapExtensions.GetOrAdd(ref _idToSourceGeneratedDocumentMap, generatedDocumentState.Id, s_createSourceGeneratedDocumentFunction, (generatedDocumentState, this)); + } + } + + return null; + } + + /// + /// Returns the for a source generated document that has already been generated and observed. + /// + /// + /// This is only safe to call if you already have seen the SyntaxTree or equivalent that indicates the document state has already been + /// generated. This method exists to implement and is best avoided unless you're doing something + /// similarly tricky like that. + /// + internal SourceGeneratedDocument? TryGetSourceGeneratedDocumentForAlreadyGeneratedId(DocumentId documentId) + { + // Easy case: do we already have the SourceGeneratedDocument created? + if (_idToSourceGeneratedDocumentMap.TryGetValue(documentId, out var document)) + { + return document; + } + + // Trickier case now: it's possible we generated this, but we don't actually have the SourceGeneratedDocument for it, so let's go + // try to fetch the state. + var documentState = _solution.State.TryGetSourceGeneratedDocumentForAlreadyGeneratedId(documentId); + + if (documentState == null) + { + return null; + } + + return ImmutableHashMapExtensions.GetOrAdd(ref _idToSourceGeneratedDocumentMap, documentId, s_createSourceGeneratedDocumentFunction, (documentState, this)); + } internal DocumentState? GetDocumentState(DocumentId documentId) => _projectState.GetDocumentState(documentId); @@ -302,6 +367,12 @@ private static AnalyzerConfigDocument CreateAnalyzerConfigDocument(DocumentId do return new AnalyzerConfigDocument(project, state); } + private static readonly Func s_createSourceGeneratedDocumentFunction = CreateSourceGeneratedDocument; + private static SourceGeneratedDocument CreateSourceGeneratedDocument(DocumentId documentId, (SourceGeneratedDocumentState, Project) stateAndProject) + { + return new SourceGeneratedDocument(stateAndProject.Item2, stateAndProject.Item1); + } + /// /// Tries to get the cached for this project if it has already been created and is still cached. In almost all /// cases you should call which will either return the cached @@ -614,8 +685,5 @@ private string GetDebuggerDisplay() internal SkippedHostAnalyzersInfo GetSkippedAnalyzersInfo(DiagnosticAnalyzerInfoCache infoCache) => Solution.State.Analyzers.GetSkippedAnalyzersInfo(this, infoCache); - - internal Task GetGeneratorDriverRunResultAsync(CancellationToken cancellationToken) - => _solution.State.GetGeneratorDriverRunResultAsync(_projectState, cancellationToken); } } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs b/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs index 6eec01ac5cca3..e52a11837f0c9 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs @@ -235,6 +235,20 @@ private static Project CreateProject(ProjectId projectId, Solution solution) return null; } + public ValueTask GetSourceGeneratedDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) + { + var project = GetProject(documentId.ProjectId); + + if (project == null) + { + return new(result: null); + } + else + { + return project.GetSourceGeneratedDocumentAsync(documentId, cancellationToken); + } + } + /// /// Gets the document in this solution with the specified syntax tree. /// @@ -250,7 +264,9 @@ private static Project CreateProject(ProjectId projectId, Solution solution) if (docId != null && (projectId == null || docId.ProjectId == projectId)) { // does this solution even have the document? - var document = this.GetDocument(docId); + // We call TryGetSourceGeneratedDocumentForAlreadyGeneratedId if it's not a regular document; + // we know that if we already have the tree that means generation completed, so that's safe to call. + var document = this.GetDocument(docId) ?? this.GetProject(docId.ProjectId)?.TryGetSourceGeneratedDocumentForAlreadyGeneratedId(docId); if (document != null) { // does this document really have the syntax tree? diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationAndGeneratorDriverTranslationAction.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationAndGeneratorDriverTranslationAction.cs index 930db788e0408..f95effe3f3b8f 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationAndGeneratorDriverTranslationAction.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationAndGeneratorDriverTranslationAction.cs @@ -15,16 +15,6 @@ public virtual Task TransformCompilationAsync(Compilation oldCompil { return Task.FromResult(oldCompilation); } - - /// - /// Returns a new that can be used for future generator invocations. - /// - public virtual TrackedGeneratorDriver TransformGeneratorDriver(TrackedGeneratorDriver generatorDriver) - { - // Our default behavior is that any edit requires us to re-run a full generation pass, since anything - // could have changed. - return new TrackedGeneratorDriver(generatorDriver: null); - } } } } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationAndGeneratorDriverTranslationAction_Actions.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationAndGeneratorDriverTranslationAction_Actions.cs index 223d44bc97e86..ed80422e70d42 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationAndGeneratorDriverTranslationAction_Actions.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationAndGeneratorDriverTranslationAction_Actions.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Collections.Immutable; -using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; @@ -36,24 +35,17 @@ public override Task TransformCompilationAsync(Compilation oldCompi internal sealed class TouchAdditionalDocumentAction : CompilationAndGeneratorDriverTranslationAction { +#pragma warning disable IDE0052 // Remove unread private members + // https://github.com/dotnet/roslyn/issues/44161: right now there is no way to tell a GeneratorDriver that an additional document changed private readonly TextDocumentState _oldState; private readonly TextDocumentState _newState; +#pragma warning restore IDE0052 // Remove unread private members public TouchAdditionalDocumentAction(TextDocumentState oldState, TextDocumentState newState) { _oldState = oldState; _newState = newState; } - - public override TrackedGeneratorDriver TransformGeneratorDriver(TrackedGeneratorDriver generatorDriver) - { - // https://github.com/dotnet/roslyn/issues/44161: right now there is no way to tell a GeneratorDriver that an additional file has been changed - // to allow for incremental updates: our only option is to recreate the generator driver from scratch. - _ = _oldState; - _ = _newState; - - return new TrackedGeneratorDriver(generatorDriver: null); - } } internal sealed class RemoveDocumentsAction : CompilationAndGeneratorDriverTranslationAction @@ -155,33 +147,31 @@ public override Task TransformCompilationAsync(Compilation oldCompi internal sealed class AddAnalyzerReferencesAction : CompilationAndGeneratorDriverTranslationAction { +#pragma warning disable IDE0052 // Remove unread private members + // https://github.com/dotnet/roslyn/issues/44161: right now there is no way to tell a GeneratorDriver that an analyzer reference has been added private readonly ImmutableArray _analyzerReferences; + private readonly string _language; +#pragma warning restore IDE0052 // Remove unread private members - public AddAnalyzerReferencesAction(ImmutableArray analyzerReferences) + public AddAnalyzerReferencesAction(ImmutableArray analyzerReferences, string language) { _analyzerReferences = analyzerReferences; - } - - public override TrackedGeneratorDriver TransformGeneratorDriver(TrackedGeneratorDriver generatorDriver) - { - var generators = _analyzerReferences.SelectMany(a => a.GetGenerators()).ToImmutableArray(); - return new TrackedGeneratorDriver(generatorDriver.GeneratorDriver?.AddGenerators(generators)); + _language = language; } } internal sealed class RemoveAnalyzerReferencesAction : CompilationAndGeneratorDriverTranslationAction { +#pragma warning disable IDE0052 // Remove unread private members + // https://github.com/dotnet/roslyn/issues/44161: right now there is no way to tell a GeneratorDriver that an analyzer reference has been removed private readonly ImmutableArray _analyzerReferences; + private readonly string _language; +#pragma warning restore IDE0052 // Remove unread private members - public RemoveAnalyzerReferencesAction(ImmutableArray analyzerReferences) + public RemoveAnalyzerReferencesAction(ImmutableArray analyzerReferences, string language) { _analyzerReferences = analyzerReferences; - } - - public override TrackedGeneratorDriver TransformGeneratorDriver(TrackedGeneratorDriver generatorDriver) - { - var generators = _analyzerReferences.SelectMany(a => a.GetGenerators()).ToImmutableArray(); - return new TrackedGeneratorDriver(generatorDriver.GeneratorDriver?.RemoveGenerators(generators)); + _language = language; } } @@ -196,14 +186,6 @@ public AddAdditionalDocumentsAction(ImmutableArray additional { _additionalDocuments = additionalDocuments; } - - public override TrackedGeneratorDriver TransformGeneratorDriver(TrackedGeneratorDriver generatorDriver) - { - // https://github.com/dotnet/roslyn/issues/44161: right now there is no way to tell a GeneratorDriver that an additional file has been added - // to allow for incremental updates: our only option is to recreate the generator driver from scratch. - // return generatorDriver.WithPendingEdits(_additionalDocuments.SelectAsArray(a => (PendingEdit)new AdditionalFileAddedEdit(new AdditionalTextWithState(a)))); - return new TrackedGeneratorDriver(generatorDriver: null); - } } internal sealed class RemoveAdditionalDocumentsAction : CompilationAndGeneratorDriverTranslationAction @@ -217,14 +199,6 @@ public RemoveAdditionalDocumentsAction(ImmutableArray additio { _additionalDocuments = additionalDocuments; } - - public override TrackedGeneratorDriver TransformGeneratorDriver(TrackedGeneratorDriver generatorDriver) - { - // https://github.com/dotnet/roslyn/issues/44161: right now there is no way to tell a GeneratorDriver that an additional file has been removed - // to allow for incremental updates: our only option is to recreate the generator driver from scratch. - // return generatorDriver.WithPendingEdits(_additionalDocuments.SelectAsArray(a => (PendingEdit)new AdditionalFileRemovedEdit(...))); - return new TrackedGeneratorDriver(generatorDriver: null); - } } } } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationTracker.State.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationTracker.State.cs index b93a2d101e283..89711f96e8fdb 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationTracker.State.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationTracker.State.cs @@ -26,8 +26,10 @@ private class State /// The base that starts with everything empty. /// public static readonly State Empty = new( - compilation: null, declarationOnlyCompilation: null, - generatorDriver: new TrackedGeneratorDriver(null), + compilationWithoutGeneratedDocuments: null, + declarationOnlyCompilation: null, + generatedDocuments: ImmutableArray.Empty, + generatedDocumentsAreFinal: false, unrootedSymbolSet: null); /// @@ -37,12 +39,26 @@ private class State public Compilation? DeclarationOnlyCompilation { get; } /// - /// The best compilation that is available that source generators have not ran on. May be an in-progress, full declaration, - /// a final compilation, or . + /// The best compilation that is available that source generators have not ran on. May be an in-progress, + /// full declaration, a final compilation, or . + /// The value is an to represent the + /// possibility of the compilation already having been garabage collected. /// - public ValueSource>? Compilation { get; } + public ValueSource>? CompilationWithoutGeneratedDocuments { get; } - public TrackedGeneratorDriver GeneratorDriver { get; } + /// + /// The best generated documents we have for the current state. specifies whether the + /// documents are to be considered final and can be reused, or whether they're from a prior snapshot which needs to be recomputed. + /// + public ImmutableArray GeneratedDocuments { get; } + + /// + /// Whether the generated documents in are final and should not be regenerated. It's important + /// that once we've ran generators once we don't want to run them again. Once we've ran them the first time, those syntax trees + /// are visible from other parts of the Workspaces model; if we run them a second time we'd end up with new trees which would + /// confuse our snapshot model -- once the tree has been handed out we can't make a second tree later. + /// + public bool GeneratedDocumentsAreFinal { get; } /// /// Weak set of the assembly, module and dynamic symbols that this compilation tracker has created. @@ -53,44 +69,48 @@ private class State public readonly UnrootedSymbolSet? UnrootedSymbolSet; /// - /// Specifies whether and all compilations it depends on contain full information or not. This can return + /// Specifies whether and all compilations it depends on contain full information or not. This can return /// if the state isn't at the point where it would know, and it's necessary to transition to to figure that out. /// public virtual bool? HasSuccessfullyLoaded => null; /// - /// The final compilation if available, otherwise . + /// The final compilation is potentially available, otherwise . + /// The value is an to represent the + /// possibility of the compilation already having been garabage collected. /// - public virtual ValueSource>? FinalCompilation => null; + public virtual ValueSource>? FinalCompilationWithGeneratedDocuments => null; protected State( - ValueSource>? compilation, + ValueSource>? compilationWithoutGeneratedDocuments, Compilation? declarationOnlyCompilation, - TrackedGeneratorDriver generatorDriver, + ImmutableArray generatedDocuments, + bool generatedDocumentsAreFinal, UnrootedSymbolSet? unrootedSymbolSet) { // Declaration-only compilations should never have any references Contract.ThrowIfTrue(declarationOnlyCompilation != null && declarationOnlyCompilation.ExternalReferences.Any()); - Compilation = compilation; + CompilationWithoutGeneratedDocuments = compilationWithoutGeneratedDocuments; DeclarationOnlyCompilation = declarationOnlyCompilation; - GeneratorDriver = generatorDriver; + GeneratedDocuments = generatedDocuments; + GeneratedDocumentsAreFinal = generatedDocumentsAreFinal; UnrootedSymbolSet = unrootedSymbolSet; } public static State Create( Compilation compilation, - TrackedGeneratorDriver generatorDriver, + ImmutableArray generatedDocuments, ImmutableArray> intermediateProjects) { - Contract.ThrowIfNull(compilation); Contract.ThrowIfTrue(intermediateProjects.IsDefault); // If we don't have any intermediate projects to process, just initialize our - // DeclarationState now. + // DeclarationState now. We'll pass false for generatedDocumentsAreFinal because this is being called + // if our referenced projects are changing, so we'll have to rerun to consume changes. return intermediateProjects.Length == 0 - ? new FullDeclarationState(compilation, generatorDriver) - : (State)new InProgressState(compilation, generatorDriver, intermediateProjects); + ? new FullDeclarationState(compilation, generatedDocuments, generatedDocumentsAreFinal: false) + : (State)new InProgressState(compilation, generatedDocuments, intermediateProjects); } public static ValueSource> CreateValueSource( @@ -137,11 +157,12 @@ private sealed class InProgressState : State public InProgressState( Compilation inProgressCompilation, - TrackedGeneratorDriver inProgressGeneratorDriver, + ImmutableArray generatedDocuments, ImmutableArray<(ProjectState state, CompilationAndGeneratorDriverTranslationAction action)> intermediateProjects) - : base(compilation: new ConstantValueSource>(inProgressCompilation), + : base(compilationWithoutGeneratedDocuments: new ConstantValueSource>(inProgressCompilation), declarationOnlyCompilation: null, - generatorDriver: inProgressGeneratorDriver, + generatedDocuments, + generatedDocumentsAreFinal: false, // since we have a set of transformations to make, we'll always have to run generators again GetUnrootedSymbols(inProgressCompilation)) { Contract.ThrowIfTrue(intermediateProjects.IsDefault); @@ -156,10 +177,13 @@ public InProgressState( /// private sealed class LightDeclarationState : State { - public LightDeclarationState(Compilation declarationOnlyCompilation) - : base(compilation: null, - declarationOnlyCompilation: declarationOnlyCompilation, - generatorDriver: new TrackedGeneratorDriver(null), + public LightDeclarationState(Compilation declarationOnlyCompilation, + ImmutableArray generatedDocuments, + bool generatedDocumentsAreFinal) + : base(compilationWithoutGeneratedDocuments: null, + declarationOnlyCompilation, + generatedDocuments, + generatedDocumentsAreFinal, unrootedSymbolSet: null) { } @@ -171,10 +195,13 @@ public LightDeclarationState(Compilation declarationOnlyCompilation) /// private sealed class FullDeclarationState : State { - public FullDeclarationState(Compilation declarationCompilation, TrackedGeneratorDriver generatorDriver) + public FullDeclarationState(Compilation declarationCompilation, + ImmutableArray generatedDocuments, + bool generatedDocumentsAreFinal) : base(new WeakValueSource(declarationCompilation), declarationCompilation.Clone().RemoveAllReferences(), - generatorDriver, + generatedDocuments, + generatedDocumentsAreFinal, GetUnrootedSymbols(declarationCompilation)) { } @@ -182,7 +209,7 @@ public FullDeclarationState(Compilation declarationCompilation, TrackedGenerator /// /// The final state a compilation tracker reaches. The is available, - /// as well as the real . + /// as well as the real . /// private sealed class FinalState : State { @@ -195,24 +222,25 @@ private sealed class FinalState : State /// consumes which will avoid generators being ran a second time on a compilation that /// already contains the output of other generators. If source generators are not active, this is equal to . /// - public override ValueSource>? FinalCompilation { get; } + public override ValueSource> FinalCompilationWithGeneratedDocuments { get; } public FinalState( ValueSource> finalCompilationSource, ValueSource> compilationWithoutGeneratedFilesSource, Compilation compilationWithoutGeneratedFiles, - TrackedGeneratorDriver generatorDriver, bool hasSuccessfullyLoaded, + ImmutableArray generatedDocuments, UnrootedSymbolSet? unrootedSymbolSet) : base(compilationWithoutGeneratedFilesSource, compilationWithoutGeneratedFiles.Clone().RemoveAllReferences(), - generatorDriver, + generatedDocuments, + generatedDocumentsAreFinal: true, // when we're in a final state, we've ran generators and should not run again unrootedSymbolSet) { HasSuccessfullyLoaded = hasSuccessfullyLoaded; - FinalCompilation = finalCompilationSource; + FinalCompilationWithGeneratedDocuments = finalCompilationSource; - if (generatorDriver.GeneratorDriver == null) + if (GeneratedDocuments.IsEmpty) { // In this case, the finalCompilationSource and compilationWithoutGeneratedFilesSource should point to the // same Compilation, which should be compilationWithoutGeneratedFiles itself diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationTracker.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationTracker.cs index bf4cf28bb6ae8..110c6c0557248 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationTracker.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationTracker.cs @@ -8,6 +8,7 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; +using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; @@ -69,8 +70,10 @@ private void WriteState(State state, SolutionServices solutionServices) { if (solutionServices.SupportsCachingRecoverableObjects) { - // Allow the cache service to create a strong reference to the compilation - solutionServices.CacheService.CacheObjectIfCachingEnabledForKey(ProjectState.Id, state, state.Compilation?.GetValueOrNull()); + // Allow the cache service to create a strong reference to the compilation. We'll get the "furthest along" compilation we have + // and hold onto that. + var compilationToCache = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull() ?? state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(); + solutionServices.CacheService.CacheObjectIfCachingEnabledForKey(ProjectState.Id, state, compilationToCache); } Volatile.Write(ref _stateDoNotAccessDirectly, state); @@ -94,7 +97,7 @@ public bool HasCompilation get { var state = this.ReadState(); - return state.Compilation != null && state.Compilation.TryGetValue(out _) || state.DeclarationOnlyCompilation != null; + return state.CompilationWithoutGeneratedDocuments != null && state.CompilationWithoutGeneratedDocuments.TryGetValue(out _) || state.DeclarationOnlyCompilation != null; } } @@ -150,7 +153,7 @@ public CompilationTracker Fork( { var state = ReadState(); - var baseCompilation = state.Compilation?.GetValueOrNull(cancellationToken); + var baseCompilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); if (baseCompilation != null) { // We have some pre-calculated state to incrementally update @@ -166,7 +169,7 @@ public CompilationTracker Fork( ? intermediateProjects : intermediateProjects.Add((ProjectState, translate)); - var newState = State.Create(newInProgressCompilation, state.GeneratorDriver, newIntermediateProjects); + var newState = State.Create(newInProgressCompilation, state.GeneratedDocuments, newIntermediateProjects); return new CompilationTracker(newProject, newState); } @@ -177,10 +180,10 @@ public CompilationTracker Fork( if (translate != null) { var intermediateProjects = ImmutableArray.Create((this.ProjectState, translate)); - return new CompilationTracker(newProject, new InProgressState(declarationOnlyCompilation, state.GeneratorDriver, intermediateProjects)); + return new CompilationTracker(newProject, new InProgressState(declarationOnlyCompilation, state.GeneratedDocuments, intermediateProjects)); } - return new CompilationTracker(newProject, new LightDeclarationState(declarationOnlyCompilation)); + return new CompilationTracker(newProject, new LightDeclarationState(declarationOnlyCompilation, state.GeneratedDocuments, generatedDocumentsAreFinal: false)); } // We have nothing. Just make a tracker that only points to the new project. We'll have @@ -196,7 +199,7 @@ public CompilationTracker Clone() public CompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken) { - GetPartialCompilationState(solution, docState.Id, out var inProgressProject, out var inProgressCompilation, cancellationToken); + GetPartialCompilationState(solution, docState.Id, out var inProgressProject, out var inProgressCompilation, out var sourceGeneratedDocuments, cancellationToken); if (!inProgressCompilation.SyntaxTrees.Contains(tree)) { @@ -217,48 +220,54 @@ public CompilationTracker FreezePartialStateWithTree(SolutionState solution, Doc // The user is asking for an in progress snap. We don't want to create it and then // have the compilation immediately disappear. So we force it to stay around with a ConstantValueSource. // As a policy, all partial-state projects are said to have incomplete references, since the state has no guarantees. - // We also will drop our generator driver, since the in-progress state will simply have to be whatever we already had and - // we won't run any generators any further. return new CompilationTracker( inProgressProject, new FinalState( new ConstantValueSource>(inProgressCompilation), new ConstantValueSource>(inProgressCompilation), inProgressCompilation, - generatorDriver: new TrackedGeneratorDriver(null), hasSuccessfullyLoaded: false, + sourceGeneratedDocuments, State.GetUnrootedSymbols(inProgressCompilation))); } /// /// Tries to get the latest snapshot of the compilation without waiting for it to be /// fully built. This method takes advantage of the progress side-effect produced during - /// . It will either return the already built compilation, any + /// . + /// It will either return the already built compilation, any /// in-progress compilation or any known old compilation in that order of preference. /// The compilation state that is returned will have a compilation that is retained so /// that it cannot disappear. /// + /// The compilation to return. Contains any source generated documents that were available already added. private void GetPartialCompilationState( SolutionState solution, DocumentId id, out ProjectState inProgressProject, out Compilation inProgressCompilation, + out ImmutableArray sourceGeneratedDocuments, CancellationToken cancellationToken) { var state = ReadState(); - var compilation = state.Compilation?.GetValueOrNull(cancellationToken); + var compilationWithoutGeneratedDocuments = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); // check whether we can bail out quickly for typing case var inProgressState = state as InProgressState; + sourceGeneratedDocuments = state.GeneratedDocuments; + // all changes left for this document is modifying the given document. // we can use current state as it is since we will replace the document with latest document anyway. if (inProgressState != null && - compilation != null && + compilationWithoutGeneratedDocuments != null && inProgressState.IntermediateProjects.All(t => IsTouchDocumentActionForDocument(t.action, id))) { inProgressProject = ProjectState; - inProgressCompilation = compilation; + + // We'll add in whatever generated documents we do have; these may be from a prior run prior to some changes + // being made to the project, but it's the best we have so we'll use it. + inProgressCompilation = compilationWithoutGeneratedDocuments.AddSyntaxTrees(sourceGeneratedDocuments.Select(d => d.SyntaxTree)); SolutionLogger.UseExistingPartialProjectState(); return; @@ -267,27 +276,33 @@ private void GetPartialCompilationState( inProgressProject = inProgressState != null ? inProgressState.IntermediateProjects.First().state : this.ProjectState; // if we already have a final compilation we are done. - if (compilation != null && state is FinalState) + if (compilationWithoutGeneratedDocuments != null && state is FinalState finalState) { - inProgressCompilation = compilation; + var finalCompilation = finalState.FinalCompilationWithGeneratedDocuments.GetValueOrNull(cancellationToken); - SolutionLogger.UseExistingFullProjectState(); - return; + if (finalCompilation != null) + { + inProgressCompilation = finalCompilation; + SolutionLogger.UseExistingFullProjectState(); + return; + } } // 1) if we have an in-progress compilation use it. // 2) If we don't, then create a simple empty compilation/project. // 3) then, make sure that all it's p2p refs and whatnot are correct. - if (compilation == null) + if (compilationWithoutGeneratedDocuments == null) { inProgressProject = inProgressProject.RemoveAllDocuments(); inProgressCompilation = CreateEmptyCompilation(); } else { - inProgressCompilation = compilation; + inProgressCompilation = compilationWithoutGeneratedDocuments; } + inProgressCompilation = inProgressCompilation.AddSyntaxTrees(sourceGeneratedDocuments.Select(d => d.SyntaxTree)); + // Now add in back a consistent set of project references. For project references // try to get either a CompilationReference or a SkeletonReference. This ensures // that the in-progress project only reports a reference to another project if it @@ -357,7 +372,7 @@ private static bool IsTouchDocumentActionForDocument(CompilationAndGeneratorDriv public bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation) { var state = ReadState(); - if (state.FinalCompilation != null && state.FinalCompilation.TryGetValue(out var compilationOpt) && compilationOpt.HasValue) + if (state.FinalCompilationWithGeneratedDocuments != null && state.FinalCompilationWithGeneratedDocuments.TryGetValue(out var compilationOpt) && compilationOpt.HasValue) { compilation = compilationOpt.Value; return true; @@ -389,13 +404,6 @@ private async Task GetCompilationSlowAsync(SolutionState solution, return compilationInfo.Compilation; } - public async Task GetGeneratorDriverRunResultAsync(SolutionState solution, CancellationToken cancellationToken) - { - var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); - - return compilationInfo.GeneratorDriverRunResult; - } - private async Task GetOrBuildDeclarationCompilationAsync(SolutionServices solutionServices, CancellationToken cancellationToken) { try @@ -407,13 +415,13 @@ private async Task GetOrBuildDeclarationCompilationAsync(SolutionSe var state = ReadState(); // we are already in the final stage. just return it. - var compilation = state.FinalCompilation?.GetValueOrNull(cancellationToken); + var compilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation != null) { return compilation; } - compilation = state.Compilation?.GetValueOrNull(cancellationToken); + compilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation == null) { // let's see whether we have declaration only compilation @@ -422,7 +430,7 @@ private async Task GetOrBuildDeclarationCompilationAsync(SolutionSe // okay, move to full declaration state. do this so that declaration only compilation never // realize symbols. var declarationOnlyCompilation = state.DeclarationOnlyCompilation.Clone(); - WriteState(new FullDeclarationState(declarationOnlyCompilation, state.GeneratorDriver), solutionServices); + WriteState(new FullDeclarationState(declarationOnlyCompilation, state.GeneratedDocuments, state.GeneratedDocumentsAreFinal), solutionServices); return declarationOnlyCompilation; } @@ -430,14 +438,13 @@ private async Task GetOrBuildDeclarationCompilationAsync(SolutionSe return await BuildDeclarationCompilationFromScratchAsync(solutionServices, cancellationToken).ConfigureAwait(false); } - if (state is FullDeclarationState) + if (state is FullDeclarationState or FinalState) { // we have full declaration, just use it. return compilation; } - TrackedGeneratorDriver generatorDriver; - (compilation, generatorDriver) = await BuildDeclarationCompilationFromInProgressAsync(solutionServices, (InProgressState)state, compilation, cancellationToken).ConfigureAwait(false); + compilation = await BuildDeclarationCompilationFromInProgressAsync(solutionServices, (InProgressState)state, compilation, cancellationToken).ConfigureAwait(false); // We must have an in progress compilation. Build off of that. return compilation; @@ -464,11 +471,11 @@ private async Task GetOrBuildCompilationInfoAsync( var state = ReadState(); // Try to get the built compilation. If it exists, then we can just return that. - var finalCompilation = state.FinalCompilation?.GetValueOrNull(cancellationToken); + var finalCompilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (finalCompilation != null) { RoslynDebug.Assert(state.HasSuccessfullyLoaded.HasValue); - return new CompilationInfo(finalCompilation, state.HasSuccessfullyLoaded.Value, state.GeneratorDriver.GeneratorDriver?.GetRunResult()); + return new CompilationInfo(finalCompilation, state.HasSuccessfullyLoaded.Value, state.GeneratedDocuments); } // Otherwise, we actually have to build it. Ensure that only one thread is trying to @@ -506,14 +513,21 @@ private Task BuildCompilationInfoAsync( // if we already have a compilation, we must be already done! This can happen if two // threads were waiting to build, and we came in after the other succeeded. - var compilation = state.FinalCompilation?.GetValueOrNull(cancellationToken); + var compilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation != null) { RoslynDebug.Assert(state.HasSuccessfullyLoaded.HasValue); - return Task.FromResult(new CompilationInfo(compilation, state.HasSuccessfullyLoaded.Value, state.GeneratorDriver.GeneratorDriver?.GetRunResult())); + return Task.FromResult(new CompilationInfo(compilation, state.HasSuccessfullyLoaded.Value, state.GeneratedDocuments)); } - compilation = state.Compilation?.GetValueOrNull(cancellationToken); + compilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); + + // If we have already reached FinalState in the past but the compilation was garbage collected, we still have the generated documents + // so we can pass those to FinalizeCompilationAsync to avoid the recomputation. This is necessary for correctness as otherwise + // we'd be reparsing trees which could result in generated documents changing identity. + ImmutableArray? authoritativeGeneratedDocuments = + state.GeneratedDocumentsAreFinal ? state.GeneratedDocuments : null; + if (compilation == null) { // this can happen if compilation is already kicked out from the cache. @@ -521,17 +535,17 @@ private Task BuildCompilationInfoAsync( if (state.DeclarationOnlyCompilation != null) { // we have declaration only compilation. build final one from it. - return FinalizeCompilationAsync(solution, state.DeclarationOnlyCompilation, state.GeneratorDriver, cancellationToken); + return FinalizeCompilationAsync(solution, state.DeclarationOnlyCompilation, authoritativeGeneratedDocuments, cancellationToken); } // We've got nothing. Build it from scratch :( return BuildCompilationInfoFromScratchAsync(solution, cancellationToken); } - if (state is FullDeclarationState || state is FinalState) + if (state is FullDeclarationState or FinalState) { // We have a declaration compilation, use it to reconstruct the final compilation - return FinalizeCompilationAsync(solution, compilation, state.GeneratorDriver, cancellationToken); + return FinalizeCompilationAsync(solution, compilation, authoritativeGeneratedDocuments, cancellationToken); } else { @@ -547,9 +561,7 @@ private async Task BuildCompilationInfoFromScratchAsync( { var compilation = await BuildDeclarationCompilationFromScratchAsync(solution.Services, cancellationToken).ConfigureAwait(false); - // Since we're building one from scratch, we don't have a generator that represents this state; we'll start with - // null and then we'll have to create a generator inside the finalization process. - return await FinalizeCompilationAsync(solution, compilation, new TrackedGeneratorDriver(null), cancellationToken).ConfigureAwait(false); + return await FinalizeCompilationAsync(solution, compilation, authoritativeGeneratedDocuments: null, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e)) { @@ -578,7 +590,7 @@ private async Task BuildDeclarationCompilationFromScratchAsync( compilation = compilation.AddSyntaxTrees(trees); trees.Free(); - WriteState(new FullDeclarationState(compilation, new TrackedGeneratorDriver(generatorDriver: null)), solutionServices); + WriteState(new FullDeclarationState(compilation, ImmutableArray.Empty, generatedDocumentsAreFinal: false), solutionServices); return compilation; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e)) @@ -611,8 +623,8 @@ private async Task BuildFinalStateFromInProgressStateAsync( { try { - var (compilation, generatorDriver) = await BuildDeclarationCompilationFromInProgressAsync(solution.Services, state, inProgressCompilation, cancellationToken).ConfigureAwait(false); - return await FinalizeCompilationAsync(solution, compilation, generatorDriver, cancellationToken).ConfigureAwait(false); + var compilation = await BuildDeclarationCompilationFromInProgressAsync(solution.Services, state, inProgressCompilation, cancellationToken).ConfigureAwait(false); + return await FinalizeCompilationAsync(solution, compilation, authoritativeGeneratedDocuments: null, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e)) { @@ -620,13 +632,12 @@ private async Task BuildFinalStateFromInProgressStateAsync( } } - private async Task<(Compilation, TrackedGeneratorDriver)> BuildDeclarationCompilationFromInProgressAsync( + private async Task BuildDeclarationCompilationFromInProgressAsync( SolutionServices solutionServices, InProgressState state, Compilation inProgressCompilation, CancellationToken cancellationToken) { try { var intermediateProjects = state.IntermediateProjects; - var inProgressGeneratorDriver = state.GeneratorDriver; while (intermediateProjects.Length > 0) { @@ -634,13 +645,12 @@ private async Task BuildFinalStateFromInProgressStateAsync( var compilationTranslationAction = intermediateProjects[0].action; inProgressCompilation = await compilationTranslationAction.TransformCompilationAsync(inProgressCompilation, cancellationToken).ConfigureAwait(false); - inProgressGeneratorDriver = compilationTranslationAction.TransformGeneratorDriver(inProgressGeneratorDriver); intermediateProjects = intermediateProjects.RemoveAt(0); - this.WriteState(State.Create(inProgressCompilation, inProgressGeneratorDriver, intermediateProjects), solutionServices); + this.WriteState(State.Create(inProgressCompilation, state.GeneratedDocuments, intermediateProjects), solutionServices); } - return (inProgressCompilation, inProgressGeneratorDriver); + return inProgressCompilation; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e)) { @@ -652,13 +662,13 @@ private struct CompilationInfo { public Compilation Compilation { get; } public bool HasSuccessfullyLoaded { get; } - public GeneratorDriverRunResult? GeneratorDriverRunResult { get; } + public ImmutableArray GeneratedDocuments { get; } - public CompilationInfo(Compilation compilation, bool hasSuccessfullyLoaded, GeneratorDriverRunResult? generatorDriverRunResult) + public CompilationInfo(Compilation compilation, bool hasSuccessfullyLoaded, ImmutableArray generatedDocuments) { Compilation = compilation; HasSuccessfullyLoaded = hasSuccessfullyLoaded; - GeneratorDriverRunResult = generatorDriverRunResult; + GeneratedDocuments = generatedDocuments; } } @@ -666,10 +676,14 @@ public CompilationInfo(Compilation compilation, bool hasSuccessfullyLoaded, Gene /// Add all appropriate references to the compilation and set it as our final compilation /// state. ///
+ /// The generated documents that can be used since they are already + /// known to be correct for the given state. This would be non-null in cases where we had computed everything and + /// ran generators, but then the compilation was garbage collected and are re-creating a compilation but we + /// still had the prior generated result available. private async Task FinalizeCompilationAsync( SolutionState solution, Compilation compilation, - TrackedGeneratorDriver generatorDriver, + ImmutableArray? authoritativeGeneratedDocuments, CancellationToken cancellationToken) { try @@ -726,32 +740,59 @@ private async Task FinalizeCompilationAsync( compilation = compilation.WithReferences(newReferences); } - // Now we run generators; if we don't have a generator driver at all, we must try create one - if (generatorDriver.GeneratorDriver == null) - { - var generators = this.ProjectState.AnalyzerReferences.SelectMany(a => a.GetGenerators()).ToImmutableArray(); - var additionalTexts = this.ProjectState.AdditionalDocumentStates.Values.SelectAsArray(a => (AdditionalText)new AdditionalTextWithState(a)); - var compilationFactory = this.ProjectState.LanguageServices.GetRequiredService(); - - generatorDriver = new TrackedGeneratorDriver( - compilationFactory.CreateGeneratorDriver( - this.ProjectState.ParseOptions!, - generators, - this.ProjectState.AnalyzerOptions.AnalyzerConfigOptionsProvider, - additionalTexts)); - } + var generators = this.ProjectState.AnalyzerReferences.SelectMany(a => a.GetGenerators(this.ProjectState.Language)).ToImmutableArray(); // We will finalize the compilation by adding full contents here. // TODO: allow finalize compilation to incrementally update a prior version // https://github.com/dotnet/roslyn/issues/46418 var compilationWithoutGeneratedFiles = compilation; - if (generatorDriver.GeneratorDriver != null) + ImmutableArray generatedDocuments; + + if (authoritativeGeneratedDocuments != null) + { + generatedDocuments = authoritativeGeneratedDocuments.Value; + } + else { - // https://github.com/dotnet/roslyn/issues/44163: make an API to expose these diagnostics - generatorDriver = new TrackedGeneratorDriver(generatorDriver.GeneratorDriver.RunGeneratorsAndUpdateCompilation(compilation, out compilation, out var diagnostics, cancellationToken)); + var _ = ArrayBuilder.GetInstance(out var generatedDocumentsBuilder); + + if (generators.Any()) + { + var additionalTexts = this.ProjectState.AdditionalDocumentStates.Values.SelectAsArray(a => (AdditionalText)new AdditionalTextWithState(a)); + var compilationFactory = this.ProjectState.LanguageServices.GetRequiredService(); + + var generatorDriver = compilationFactory.CreateGeneratorDriver( + this.ProjectState.ParseOptions!, + generators, + this.ProjectState.AnalyzerOptions.AnalyzerConfigOptionsProvider, + additionalTexts); + + if (generatorDriver != null) + { + generatorDriver = generatorDriver.RunGenerators(compilationWithoutGeneratedFiles); + + foreach (var generatorResult in generatorDriver.GetRunResult().Results) + { + foreach (var generatedSource in generatorResult.GeneratedSources) + { + generatedDocumentsBuilder.Add( + SourceGeneratedDocumentState.Create( + generatedSource, + CreateStableSourceGeneratedDocumentId(ProjectState.Id, generatorResult.Generator, generatedSource.HintName), + generatorResult.Generator, + this.ProjectState.LanguageServices, + solution.Services)); + } + } + } + } + + generatedDocuments = generatedDocumentsBuilder.ToImmutable(); } + compilation = compilation.AddSyntaxTrees(generatedDocuments.Select(d => d.SyntaxTree)); + RecordAssemblySymbols(compilation, metadataReferenceToProjectId); this.WriteState( @@ -759,12 +800,12 @@ private async Task FinalizeCompilationAsync( State.CreateValueSource(compilation, solution.Services), State.CreateValueSource(compilationWithoutGeneratedFiles, solution.Services), compilationWithoutGeneratedFiles, - generatorDriver, hasSuccessfullyLoaded, + generatedDocuments, State.GetUnrootedSymbols(compilation)), solution.Services); - return new CompilationInfo(compilation, hasSuccessfullyLoaded, generatorDriver.GeneratorDriver?.GetRunResult()); + return new CompilationInfo(compilation, hasSuccessfullyLoaded, generatedDocuments); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e)) { @@ -772,6 +813,33 @@ private async Task FinalizeCompilationAsync( } } + private static DocumentId CreateStableSourceGeneratedDocumentId(ProjectId projectId, ISourceGenerator generator, string hintName) + { + // We want the DocumentId generated for a generated output to be stable between Compilations; this is so features that track + // a document by DocumentId can find it after some change has happened that requires generators to run again. + // To achieve this we'll just do a crytographic hash of the generator name and hint name; the choice of a cryptographic hash + // as opposed to a more generic string hash is we actually want to ensure we don't have collisions. + var generatorName = generator.GetType().FullName; + Contract.ThrowIfNull(generatorName); + + // Combine the strings together; we'll use Encoding.Unicode since that'll match the underlying format; this can be made much + // faster once we're on .NET Core since we could directly treat the strings as ReadOnlySpan. + using var _ = ArrayBuilder.GetInstance(capacity: (generatorName.Length + hintName.Length + 1) * 2, out var hashInput); + hashInput.AddRange(Encoding.Unicode.GetBytes(generatorName)); + + // Add a null to separate the generator name and hint name; since this is effectively a joining of UTF-16 bytes + // we'll use a UTF-16 null just to make sure there's absolutely no risk of collision. + hashInput.AddRange(0, 0); + hashInput.AddRange(Encoding.Unicode.GetBytes(hintName)); + + // The particular choice of crypto algorithm here is arbitrary and can be always changed as necessary. + var hash = System.Security.Cryptography.SHA256.Create().ComputeHash(hashInput.ToArray()); + Array.Resize(ref hash, 16); + var guid = new Guid(hash); + + return DocumentId.CreateFromSerialized(projectId, guid, hintName); + } + private void RecordAssemblySymbols(Compilation compilation, Dictionary metadataReferenceToProjectId) { RecordSourceOfAssemblySymbol(compilation.Assembly, this.ProjectState.Id); @@ -838,8 +906,8 @@ public async Task GetMetadataReferenceAsync( var state = ReadState(); // get compilation in any state it happens to be in right now. - if (state.Compilation != null && - state.Compilation.TryGetValue(out var compilationOpt) && + if (state.CompilationWithoutGeneratedDocuments != null && + state.CompilationWithoutGeneratedDocuments.TryGetValue(out var compilationOpt) && compilationOpt.HasValue && ProjectState.LanguageServices == fromProject.LanguageServices) { @@ -955,6 +1023,27 @@ private async Task HasSuccessfullyLoadedSlowAsync(SolutionState solution, return compilationInfo.HasSuccessfullyLoaded; } + public async Task> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken) + { + var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); + return compilationInfo.GeneratedDocuments; + } + + public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentForAlreadyGeneratedId(DocumentId documentId) + { + var state = ReadState(); + + // If we are in FinalState, then we have correctly ran generators and then know the final contents of the + // Compilation. The GeneratedDocuments can be filled for intermediate states, but those aren't guaranteed to be + // correct and can be re-ran later. + if (state is FinalState finalState) + { + return finalState.GeneratedDocuments.SingleOrDefault(d => d.Id == documentId); + } + + return null; + } + #region Versions // Dependent Versions are stored on compilation tracker so they are more likely to survive when unrelated solution branching occurs. diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.TrackedGeneratorDriver.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.TrackedGeneratorDriver.cs deleted file mode 100644 index 7712379df4861..0000000000000 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.TrackedGeneratorDriver.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace Microsoft.CodeAnalysis -{ - internal partial class SolutionState - { - // TODO: this mostly exists as a way to track if a GeneratorDriver has been mutated in a way - // which TryApplyEdit can no longer be used. We should just revise GeneratorDriver to better handle - // this pattern. https://github.com/dotnet/roslyn/issues/42815 tracks updating an API to allow this. - public readonly struct TrackedGeneratorDriver - { - public TrackedGeneratorDriver(GeneratorDriver? generatorDriver) - { - GeneratorDriver = generatorDriver; - NeedsFullGeneration = true; - } - - internal TrackedGeneratorDriver(GeneratorDriver generatorDriver, bool needsFullGeneration) - { - GeneratorDriver = generatorDriver; - NeedsFullGeneration = needsFullGeneration; - } - - public GeneratorDriver? GeneratorDriver { get; } - public bool NeedsFullGeneration { get; } - - // TODO: re-enable when PendingEdit is public again - // https://github.com/dotnet/roslyn/issues/46419 -#if false - - public TrackedGeneratorDriver WithPendingEdit(PendingEdit pendingEdit) - { - return WithPendingEdits(ImmutableArray.Create(pendingEdit)); - } - - public TrackedGeneratorDriver WithPendingEdits(ImmutableArray pendingEdits) - { - if (GeneratorDriver == null) - { - return this; - } - - // We are able to incrementally update the generator driver then - return new TrackedGeneratorDriver( - GeneratorDriver.WithPendingEdits(pendingEdits), - needsFullGeneration: false); - } - -#endif - } - } -} diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.cs index 134be5e611f0b..3d0aa1f8f6786 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.cs @@ -981,7 +981,7 @@ public SolutionState AddAnalyzerReferences(ProjectId projectId, ImmutableArray @@ -1000,7 +1000,7 @@ public SolutionState RemoveAnalyzerReference(ProjectId projectId, AnalyzerRefere return ForkProject( oldProject.WithAnalyzerReferences(newReferences), - new CompilationAndGeneratorDriverTranslationAction.RemoveAnalyzerReferencesAction(ImmutableArray.Create(analyzerReference))); + new CompilationAndGeneratorDriverTranslationAction.RemoveAnalyzerReferencesAction(ImmutableArray.Create(analyzerReference), oldProject.Language)); } /// @@ -1738,9 +1738,6 @@ public bool TryGetCompilation(ProjectId projectId, [NotNullWhen(returnValue: tru : SpecializedTasks.Null(); } - internal Task GetGeneratorDriverRunResultAsync(ProjectState projectState, CancellationToken cancellationToken) - => GetCompilationTracker(projectState.Id).GetGeneratorDriverRunResultAsync(this, cancellationToken); - /// /// Return reference completeness for the given project and all projects this references. /// @@ -1753,6 +1750,29 @@ public Task HasSuccessfullyLoadedAsync(ProjectState project, CancellationT : project.HasAllInformation ? SpecializedTasks.True : SpecializedTasks.False; } + /// + /// Returns the generated document states for source generated documents. + /// + public Task> GetSourceGeneratedDocumentStatesAsync(ProjectState project, CancellationToken cancellationToken) + { + return project.SupportsCompilation + ? GetCompilationTracker(project.Id).GetSourceGeneratedDocumentStatesAsync(this, cancellationToken) + : SpecializedTasks.EmptyImmutableArray(); + } + + /// + /// Returns the for a source generated document that has already been generated and observed. + /// + /// + /// This is only safe to call if you already have seen the SyntaxTree or equivalent that indicates the document state has already been + /// generated. This method exists to implement and is best avoided unless you're doing something + /// similarly tricky like that. + /// + public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentForAlreadyGeneratedId(DocumentId documentId) + { + return GetCompilationTracker(documentId.ProjectId).TryGetSourceGeneratedDocumentForAlreadyGeneratedId(documentId); + } + /// /// Symbols need to be either or . /// diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SourceGeneratedDocument.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SourceGeneratedDocument.cs new file mode 100644 index 0000000000000..bc02184cf39bb --- /dev/null +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SourceGeneratedDocument.cs @@ -0,0 +1,22 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace Microsoft.CodeAnalysis +{ + /// + /// A that was generated by an . + /// + public sealed class SourceGeneratedDocument : Document + { + internal SourceGeneratedDocument(Project project, SourceGeneratedDocumentState state) + : base(project, state) + { + } + + private new SourceGeneratedDocumentState State => (SourceGeneratedDocumentState)base.State; + + public ISourceGenerator SourceGenerator => State.SourceGenerator; + public string HintName => State.HintName; + } +} diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SourceGeneratedDocumentState.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SourceGeneratedDocumentState.cs new file mode 100644 index 0000000000000..90e404cc4c439 --- /dev/null +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SourceGeneratedDocumentState.cs @@ -0,0 +1,111 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Threading; +using Microsoft.CodeAnalysis.Host; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis +{ + internal sealed class SourceGeneratedDocumentState : DocumentState + { + public string HintName { get; } + public ISourceGenerator SourceGenerator { get; } + + public static SourceGeneratedDocumentState Create( + GeneratedSourceResult generatedSourceResult, + DocumentId documentId, + ISourceGenerator sourceGenerator, + HostLanguageServices languageServices, + SolutionServices solutionServices) + { + var textAndVersion = TextAndVersion.Create(generatedSourceResult.SourceText, VersionStamp.Create()); + ValueSource textSource = new ConstantValueSource(textAndVersion); + + var tree = generatedSourceResult.SyntaxTree; + + // Since the tree is coming directly from the generator, this tree is strongly held so GetRoot() doesn't need a CancellationToken. + var root = tree.GetRoot(CancellationToken.None); + Contract.ThrowIfNull(languageServices.SyntaxTreeFactory, "We should not have a generated syntax tree for a language that doesn't support trees."); + + if (languageServices.SyntaxTreeFactory.CanCreateRecoverableTree(root)) + { + // We will only create recoverable text if we can create a recoverable tree; if we created a recoverable text + // but not a new tree, it would mean tree.GetText() could still potentially return the non-recoverable text, + // but asking the document directly for it's text would give a recoverable text with a different object identity. + textSource = CreateRecoverableText(textAndVersion, solutionServices); + tree = languageServices.SyntaxTreeFactory.CreateRecoverableTree( + documentId.ProjectId, + filePath: tree.FilePath, + tree.Options, + textSource, + generatedSourceResult.SourceText.Encoding, + root); + } + + var treeAndVersion = TreeAndVersion.Create(tree, textAndVersion.Version); + + return new SourceGeneratedDocumentState( + languageServices, + solutionServices, + documentServiceProvider: null, + new DocumentInfo.DocumentAttributes( + documentId, + name: generatedSourceResult.HintName, + folders: SpecializedCollections.EmptyReadOnlyList(), + tree.Options.Kind, + filePath: tree.FilePath, + isGenerated: true, + designTimeOnly: false), + tree.Options, + sourceText: null, // don't strongly hold the text + textSource, + treeAndVersion, + sourceGenerator, + generatedSourceResult.HintName); + } + + private SourceGeneratedDocumentState( + HostLanguageServices languageServices, + SolutionServices solutionServices, + IDocumentServiceProvider? documentServiceProvider, + DocumentInfo.DocumentAttributes attributes, + ParseOptions? options, + SourceText? sourceText, + ValueSource textSource, + TreeAndVersion treeAndVersion, + ISourceGenerator sourceGenerator, + string hintName) + : base(languageServices, solutionServices, documentServiceProvider, attributes, options, sourceText, textSource, new ConstantValueSource(treeAndVersion)) + { + SourceGenerator = sourceGenerator; + HintName = hintName; + } + + /// + /// Equivalent to calling , but avoids the implicit requirement of a cancellation token since + /// we can always get the tree right away. + /// + /// + /// We won't expose this through in case the implementation changes. + /// + public SyntaxTree SyntaxTree + { + get + { + // We are always holding onto the SyntaxTree object with a ConstantValueSource, so we can just fetch this + // without any extra work. Unlike normal documents where we don't even have a tree object until we've fetched text and + // the tree the first time, the generated case we start with a tree and text and then wrap it. + return GetSyntaxTree(CancellationToken.None); + } + } + + protected override TextDocumentState UpdateText(ValueSource newTextSource, PreservationMode mode, bool incremental) + { + throw new NotSupportedException(WorkspacesResources.The_contents_of_a_SourceGeneratedDocument_may_not_be_changed); + } + } +} diff --git a/src/Workspaces/Core/Portable/Workspace/Workspace.cs b/src/Workspaces/Core/Portable/Workspace/Workspace.cs index 239a174cc3bf6..623a380dfc742 100644 --- a/src/Workspaces/Core/Portable/Workspace/Workspace.cs +++ b/src/Workspaces/Core/Portable/Workspace/Workspace.cs @@ -1161,8 +1161,8 @@ public virtual bool CanApplyChange(ApplyChangesKind feature) /// Returns if a reference to referencedProject can be added to /// referencingProject. otherwise. /// - internal virtual Task CanAddProjectReferenceAsync(ProjectId referencingProject, ProjectId referencedProject, CancellationToken cancellationToken) - => SpecializedTasks.False; + internal virtual bool CanAddProjectReference(ProjectId referencingProject, ProjectId referencedProject) + => false; /// /// Apply changes made to a solution back to the workspace. @@ -1670,7 +1670,11 @@ internal static DocumentInfo CreateDocumentInfoWithoutText(TextDocument doc) doc.Name, doc.Folders, sourceDoc != null ? sourceDoc.SourceCodeKind : SourceCodeKind.Regular, - filePath: doc.FilePath); + loader: null, + filePath: doc.FilePath, + isGenerated: false, + designTimeOnly: false, + doc.Services); } /// diff --git a/src/Workspaces/Core/Portable/WorkspacesResources.resx b/src/Workspaces/Core/Portable/WorkspacesResources.resx index cc037f4c4dd3f..eeb6d7a224261 100644 --- a/src/Workspaces/Core/Portable/WorkspacesResources.resx +++ b/src/Workspaces/Core/Portable/WorkspacesResources.resx @@ -559,10 +559,18 @@ Symbol's project could not be found in the provided solution + + The contents of a SourceGeneratedDocument may not be changed. + {locked:SourceGeneratedDocument} + Rename '{0}' to '{1}' Sync namespace to folder structure + + CodeAction '{0}' did not produce a changed solution + "CodeAction" is a specific type, and {0} represents the title shown by the action. + \ No newline at end of file diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.cs.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.cs.xlf index d065cad642a1c..ac3b248ebc86c 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.cs.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.cs.xlf @@ -32,6 +32,11 @@ Změna dokumentu {0} není podporovaná. + + CodeAction '{0}' did not produce a changed solution + CodeAction '{0}' did not produce a changed solution + "CodeAction" is a specific type, and {0} represents the title shown by the action. + Core EditorConfig Options Základní možnosti pro EditorConfig @@ -192,6 +197,11 @@ Synchronizovat obor názvů se strukturou složek + + The contents of a SourceGeneratedDocument may not be changed. + The contents of a SourceGeneratedDocument may not be changed. + {locked:SourceGeneratedDocument} + The project already contains the specified reference. Projekt už zadaný odkaz obsahuje. @@ -234,12 +244,12 @@ '{0}' is not part of the workspace. - '{0} není součástí pracovního prostoru. + {0} není součástí pracovního prostoru. '{0}' is already part of the workspace. - '{0} je už součástí pracovního prostoru. + {0} je už součástí pracovního prostoru. @@ -319,7 +329,7 @@ '{0}' is not open. - '{0} není otevřený. + {0} není otevřený. @@ -664,7 +674,7 @@ '{0}' returned an uninitialized ImmutableArray - '{0} vrací neinicializované ImmutableArray. + {0} vrací neinicializované ImmutableArray. diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.de.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.de.xlf index 95acb742a0300..738bd81c57704 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.de.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.de.xlf @@ -32,6 +32,11 @@ Das Ändern des Dokuments "{0}" wird nicht unterstützt. + + CodeAction '{0}' did not produce a changed solution + CodeAction '{0}' did not produce a changed solution + "CodeAction" is a specific type, and {0} represents the title shown by the action. + Core EditorConfig Options Wichtige EditorConfig-Optionen @@ -192,6 +197,11 @@ Namespace mit Ordnerstruktur synchronisieren + + The contents of a SourceGeneratedDocument may not be changed. + The contents of a SourceGeneratedDocument may not be changed. + {locked:SourceGeneratedDocument} + The project already contains the specified reference. Im Projekt ist der angegebene Verweis bereits enthalten. @@ -234,7 +244,7 @@ '{0}' is not part of the workspace. - '"{0}" ist nicht Teil des Arbeitsbereichs. + "{0}" ist nicht Teil des Arbeitsbereichs. @@ -244,12 +254,12 @@ '{0}' is not referenced. - '"{0}" ist nicht referenziert. + "{0}" ist nicht referenziert. '{0}' is already referenced. - '"{0}" ist bereits referenziert. + "{0}" ist bereits referenziert. @@ -319,7 +329,7 @@ '{0}' is not open. - '"{0}" ist nicht geöffnet. + "{0}" ist nicht geöffnet. @@ -664,7 +674,7 @@ '{0}' returned an uninitialized ImmutableArray - '"{0}" hat ein nicht initialisiertes "ImmutableArray" zurückgegeben. + "{0}" hat ein nicht initialisiertes "ImmutableArray" zurückgegeben. @@ -689,7 +699,7 @@ '{0}' encountered an error and has been disabled. - '"{0}" hat einen Fehler festgestellt und wurde deaktiviert. + "{0}" hat einen Fehler festgestellt und wurde deaktiviert. diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.es.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.es.xlf index d5302f3d0179f..34c743172cd6c 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.es.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.es.xlf @@ -32,6 +32,11 @@ Documento cambiante '{0}' no es compatible. + + CodeAction '{0}' did not produce a changed solution + CodeAction '{0}' did not produce a changed solution + "CodeAction" is a specific type, and {0} represents the title shown by the action. + Core EditorConfig Options Opciones principales de EditorConfig @@ -192,6 +197,11 @@ Sincronizar espacio de nombres con estructura de carpetas + + The contents of a SourceGeneratedDocument may not be changed. + The contents of a SourceGeneratedDocument may not be changed. + {locked:SourceGeneratedDocument} + The project already contains the specified reference. El proyecto ya contiene la referencia especificada. diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.fr.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.fr.xlf index 1ba90d4b09e8b..10b3877e88bbb 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.fr.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.fr.xlf @@ -32,6 +32,11 @@ Le changement du document '{0}' n'est pas pris en charge. + + CodeAction '{0}' did not produce a changed solution + CodeAction '{0}' did not produce a changed solution + "CodeAction" is a specific type, and {0} represents the title shown by the action. + Core EditorConfig Options Options EditorConfig principales @@ -192,6 +197,11 @@ Synchroniser l'espace de noms avec la structure de dossier + + The contents of a SourceGeneratedDocument may not be changed. + The contents of a SourceGeneratedDocument may not be changed. + {locked:SourceGeneratedDocument} + The project already contains the specified reference. Le projet contient déjà la référence spécifiée. diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.it.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.it.xlf index a749ea7426984..5973c34a70277 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.it.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.it.xlf @@ -32,6 +32,11 @@ La modifica del documento '{0}' non è supportata. + + CodeAction '{0}' did not produce a changed solution + CodeAction '{0}' did not produce a changed solution + "CodeAction" is a specific type, and {0} represents the title shown by the action. + Core EditorConfig Options Opzioni EditorConfig di base @@ -192,6 +197,11 @@ Sincronizza lo spazio dei nomi con la struttura di cartelle + + The contents of a SourceGeneratedDocument may not be changed. + The contents of a SourceGeneratedDocument may not be changed. + {locked:SourceGeneratedDocument} + The project already contains the specified reference. Il progetto contiene già il riferimento specificato. diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ja.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ja.xlf index 61534f3ec6d42..471af97557a45 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ja.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ja.xlf @@ -32,6 +32,11 @@ ドキュメント '{0}' の変更はサポートされていません。 + + CodeAction '{0}' did not produce a changed solution + CodeAction '{0}' did not produce a changed solution + "CodeAction" is a specific type, and {0} represents the title shown by the action. + Core EditorConfig Options コア EditorConfig オプション @@ -99,7 +104,7 @@ Rename '{0}' to '{1}' - {0}' を '{1}' に名前変更 + '{0}' を '{1}' に名前変更 @@ -192,6 +197,11 @@ 名前空間とフォルダー構造の同期 + + The contents of a SourceGeneratedDocument may not be changed. + The contents of a SourceGeneratedDocument may not be changed. + {locked:SourceGeneratedDocument} + The project already contains the specified reference. このプロジェクトには、指定された参照が既に含まれています。 @@ -629,7 +639,7 @@ The position is not within the symbol's declaration - シンボルの宣言内に配置されていません。 + シンボルの宣言内に配置されていません @@ -704,7 +714,7 @@ Deserialization reader for '{0}' read incorrect number of values. - {0}' の逆シリアル化のリーダーが、正しくない数の値を読み取りました。 + '{0}' の逆シリアル化のリーダーが、正しくない数の値を読み取りました。 diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ko.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ko.xlf index d9b1250578e08..2aac6ca30fbbc 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ko.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ko.xlf @@ -32,6 +32,11 @@ '{0}' 문서 변경은 지원되지 않습니다. + + CodeAction '{0}' did not produce a changed solution + CodeAction '{0}' did not produce a changed solution + "CodeAction" is a specific type, and {0} represents the title shown by the action. + Core EditorConfig Options 코어 EditorConfig 옵션 @@ -99,7 +104,7 @@ Rename '{0}' to '{1}' - {1}'(으)로 '{0}' 이름 바꾸기 + '{1}'(으)로 '{0}' 이름 바꾸기 @@ -169,7 +174,7 @@ Duplicate source file '{0}' in project '{1}' - {1}' 프로젝트에서 중복된 '{0}' 소스 파일입니다. + '{1}' 프로젝트에서 중복된 '{0}' 소스 파일입니다. @@ -192,6 +197,11 @@ 네임스페이스를 폴더 구조로 동기화 + + The contents of a SourceGeneratedDocument may not be changed. + The contents of a SourceGeneratedDocument may not be changed. + {locked:SourceGeneratedDocument} + The project already contains the specified reference. 지정된 참조가 이미 프로젝트에 포함되어 있습니다. @@ -254,7 +264,7 @@ Adding project reference from '{0}' to '{1}' will cause a circular reference. - {0}'에서 '{1}'(으)로 프로젝트 참조를 추가하면 순환 참조가 됩니다. + '{0}'에서 '{1}'(으)로 프로젝트 참조를 추가하면 순환 참조가 됩니다. @@ -284,7 +294,7 @@ The language '{0}' is not supported. - {0}' 언어는 지원되지 않습니다. + '{0}' 언어는 지원되지 않습니다. @@ -449,12 +459,12 @@ Cannot open project '{0}' because the file extension '{1}' is not associated with a language. - {1}' 파일 확장명이 언어에 연결되어 있지 않아 '{0}' 프로젝트를 열 수 없습니다. + '{1}' 파일 확장명이 언어에 연결되어 있지 않아 '{0}' 프로젝트를 열 수 없습니다. Cannot open project '{0}' because the language '{1}' is not supported. - {1}' 언어를 지원하지 않아 '{0}' 프로젝트를 열 수 없습니다. + '{1}' 언어를 지원하지 않아 '{0}' 프로젝트를 열 수 없습니다. @@ -469,17 +479,17 @@ Project file not found: '{0}' - {0}' 프로젝트 파일을 찾을 수 없습니다. + '{0}' 프로젝트 파일을 찾을 수 없습니다. Solution file not found: '{0}' - {0}' 솔루션 파일을 찾을 수 없습니다. + '{0}' 솔루션 파일을 찾을 수 없습니다. Unmerged change from project '{0}' - {0}' 프로젝트에서 병합되지 않은 변경 내용 + '{0}' 프로젝트에서 병합되지 않은 변경 내용 @@ -574,7 +584,7 @@ Service of type '{0}' is required to accomplish the task but is not available from the workspace. - {0}' 유형의 서비스가 작업을 수행하는 데 필요하지만 작업 영역에서 사용할 수 없습니다. + '{0}' 유형의 서비스가 작업을 수행하는 데 필요하지만 작업 영역에서 사용할 수 없습니다. @@ -589,12 +599,12 @@ Cannot deserialize type '{0}'. - {0}' 형식을 역직렬화할 수 없습니다. + '{0}' 형식을 역직렬화할 수 없습니다. Cannot serialize type '{0}'. - {0}' 형식을 직렬화할 수 없습니다. + '{0}' 형식을 직렬화할 수 없습니다. @@ -604,7 +614,7 @@ Label for node '{0}' is invalid, it must be within [0, {1}). - {0}' 노드의 레이블이 잘못되었습니다. [0, {1}) 내에 있어야 합니다. + '{0}' 노드의 레이블이 잘못되었습니다. [0, {1}) 내에 있어야 합니다. @@ -614,17 +624,17 @@ Node '{0}' must be contained in the new tree. - {0}' 노드가 새 트리에 포함되어야 합니다. + '{0}' 노드가 새 트리에 포함되어야 합니다. Node '{0}' must be contained in the old tree. - {0}' 노드가 이전 트리에 포함되어야 합니다. + '{0}' 노드가 이전 트리에 포함되어야 합니다. The member '{0}' is not declared within the declaration of the symbol. - {0}' 멤버가 기호의 선언 내에서 선언되지 않았습니다. + '{0}' 멤버가 기호의 선언 내에서 선언되지 않았습니다. @@ -704,7 +714,7 @@ Deserialization reader for '{0}' read incorrect number of values. - {0}'에 대한 역직렬화 판독기가 잘못된 숫자 값을 읽습니다. + '{0}'에 대한 역직렬화 판독기가 잘못된 숫자 값을 읽습니다. diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.pl.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.pl.xlf index efab0c575d8ae..c91797580c66c 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.pl.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.pl.xlf @@ -32,6 +32,11 @@ Zmiana dokumentu „{0}” nie jest obsługiwana. + + CodeAction '{0}' did not produce a changed solution + CodeAction '{0}' did not produce a changed solution + "CodeAction" is a specific type, and {0} represents the title shown by the action. + Core EditorConfig Options Podstawowe opcje EditorConfig @@ -192,6 +197,11 @@ Synchronizuj przestrzeń nazw ze strukturą folderów + + The contents of a SourceGeneratedDocument may not be changed. + The contents of a SourceGeneratedDocument may not be changed. + {locked:SourceGeneratedDocument} + The project already contains the specified reference. Projekt już zawiera określone odwołanie. diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.pt-BR.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.pt-BR.xlf index 0ff4ce0ebeee6..b48c061ca0819 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.pt-BR.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.pt-BR.xlf @@ -32,6 +32,11 @@ Não há suporte para alterar o documento '{0}'. + + CodeAction '{0}' did not produce a changed solution + CodeAction '{0}' did not produce a changed solution + "CodeAction" is a specific type, and {0} represents the title shown by the action. + Core EditorConfig Options Opções Principais do EditorConfig @@ -192,6 +197,11 @@ Sincronizar namespace com a estrutura de pasta + + The contents of a SourceGeneratedDocument may not be changed. + The contents of a SourceGeneratedDocument may not be changed. + {locked:SourceGeneratedDocument} + The project already contains the specified reference. O projeto já contém a referência especificada. @@ -244,12 +254,12 @@ '{0}' is not referenced. - '"{0}" não é referenciado. + "{0}" não é referenciado. '{0}' is already referenced. - '"{0}" já está referenciado. + "{0}" já está referenciado. @@ -319,7 +329,7 @@ '{0}' is not open. - '"{0}" não está aberto. + "{0}" não está aberto. diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ru.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ru.xlf index 71d63131a9925..4632f6b2f19bf 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ru.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ru.xlf @@ -32,6 +32,11 @@ Изменение документа "{0}" не поддерживается. + + CodeAction '{0}' did not produce a changed solution + CodeAction '{0}' did not produce a changed solution + "CodeAction" is a specific type, and {0} represents the title shown by the action. + Core EditorConfig Options Основные параметры EditorConfig @@ -192,6 +197,11 @@ Синхронизировать пространство имен со структурой папок + + The contents of a SourceGeneratedDocument may not be changed. + The contents of a SourceGeneratedDocument may not be changed. + {locked:SourceGeneratedDocument} + The project already contains the specified reference. Проект уже содержит указанную ссылку. @@ -234,22 +244,22 @@ '{0}' is not part of the workspace. - '"{0}" не является частью рабочей области. + "{0}" не является частью рабочей области. '{0}' is already part of the workspace. - '"{0}" уже является частью рабочей области. + "{0}" уже является частью рабочей области. '{0}' is not referenced. - '"{0}" не объявлен. + "{0}" не объявлен. '{0}' is already referenced. - '"{0}" уже объявлен. + "{0}" уже объявлен. @@ -319,7 +329,7 @@ '{0}' is not open. - '"{0}" не открыт. + "{0}" не открыт. @@ -664,7 +674,7 @@ '{0}' returned an uninitialized ImmutableArray - '"{0}" возвратил неинициализированный ImmutableArray + "{0}" возвратил неинициализированный ImmutableArray diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.tr.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.tr.xlf index 55cc8ae778057..c19cc959f4d90 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.tr.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.tr.xlf @@ -32,6 +32,11 @@ Değişen belge '{0}' desteklenmiyor. + + CodeAction '{0}' did not produce a changed solution + CodeAction '{0}' did not produce a changed solution + "CodeAction" is a specific type, and {0} represents the title shown by the action. + Core EditorConfig Options Çekirdek EditorConfig seçenekleri @@ -99,7 +104,7 @@ Rename '{0}' to '{1}' - {0}' öğesini '{1}' olarak yeniden adlandır + '{0}' öğesini '{1}' olarak yeniden adlandır @@ -169,7 +174,7 @@ Duplicate source file '{0}' in project '{1}' - {1}' projesinde yinelenen kaynak dosyası '{0}' + '{1}' projesinde yinelenen kaynak dosyası '{0}' @@ -192,6 +197,11 @@ Ad alanını klasör yapısına eşitle + + The contents of a SourceGeneratedDocument may not be changed. + The contents of a SourceGeneratedDocument may not be changed. + {locked:SourceGeneratedDocument} + The project already contains the specified reference. Proje belirtilen başvuruyu zaten içeriyor. @@ -284,7 +294,7 @@ The language '{0}' is not supported. - {0}' dili desteklenmiyor. + '{0}' dili desteklenmiyor. @@ -454,7 +464,7 @@ Cannot open project '{0}' because the language '{1}' is not supported. - {1}' dili desteklenmediği için '{0}' projesi açılamıyor. + '{1}' dili desteklenmediği için '{0}' projesi açılamıyor. @@ -479,7 +489,7 @@ Unmerged change from project '{0}' - {0}' projesinden birleştirilmemiş değişiklik + '{0}' projesinden birleştirilmemiş değişiklik @@ -589,22 +599,22 @@ Cannot deserialize type '{0}'. - {0}' türü seri durumdan çıkarılamıyor. + '{0}' türü seri durumdan çıkarılamıyor. Cannot serialize type '{0}'. - {0}' türü seri hale getirilemiyor. + '{0}' türü seri hale getirilemiyor. The type '{0}' is not understood by the serialization binder. - {0}' türü, serileştirme bağlayıcısı tarafından anlaşılamıyor. + '{0}' türü, serileştirme bağlayıcısı tarafından anlaşılamıyor. Label for node '{0}' is invalid, it must be within [0, {1}). - {0}' düğümünün etiketi geçersiz, etiket [0, {1}) içerisinde olmalıdır. + '{0}' düğümünün etiketi geçersiz, etiket [0, {1}) içerisinde olmalıdır. @@ -624,7 +634,7 @@ The member '{0}' is not declared within the declaration of the symbol. - {0}' üyesi, sembolün bildirimi içerisinde bildirilmedi. + '{0}' üyesi, sembolün bildirimi içerisinde bildirilmedi. @@ -634,7 +644,7 @@ The symbol '{0}' cannot be located within the current solution. - {0}' sembolü geçerli çözümde bulunamaz. + '{0}' sembolü geçerli çözümde bulunamaz. @@ -704,7 +714,7 @@ Deserialization reader for '{0}' read incorrect number of values. - {0}' türünün seri durumdan çıkarma okuyucusu, yanlış sayıda değer okudu. + '{0}' türünün seri durumdan çıkarma okuyucusu, yanlış sayıda değer okudu. @@ -729,7 +739,7 @@ File '{0}' size of {1} exceeds maximum allowed size of {2} - {0}' adlı dosyanın boyutu ({1}), izin verilen üst sınırı ({2}) aşıyor + '{0}' adlı dosyanın boyutu ({1}), izin verilen üst sınırı ({2}) aşıyor diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.zh-Hans.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.zh-Hans.xlf index 64670e86b2761..16925917d3755 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.zh-Hans.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Adding analyzer config documents is not supported. @@ -32,6 +32,11 @@ 不支持更改文档“{0}”。 + + CodeAction '{0}' did not produce a changed solution + CodeAction '{0}' did not produce a changed solution + "CodeAction" is a specific type, and {0} represents the title shown by the action. + Core EditorConfig Options Core EditorConfig 选项 @@ -192,6 +197,11 @@ 将命名空间同步到文件夹结构 + + The contents of a SourceGeneratedDocument may not be changed. + The contents of a SourceGeneratedDocument may not be changed. + {locked:SourceGeneratedDocument} + The project already contains the specified reference. 项目已包含指定的引用。 @@ -234,12 +244,12 @@ '{0}' is not part of the workspace. - '“{0}”不是工作区的一部分。 + “{0}”不是工作区的一部分。 '{0}' is already part of the workspace. - '“{0}”已经是工作区的一部分。 + “{0}”已经是工作区的一部分。 @@ -434,7 +444,7 @@ Cannot generate code for unsupported operator '{0}' - 无法为不受支持的运算符“{0}”生成代码。 + 无法为不受支持的运算符“{0}”生成代码 @@ -689,7 +699,7 @@ '{0}' encountered an error and has been disabled. - '“{0}”遇到了错误,且已被禁用。 + “{0}”遇到了错误,且已被禁用。 diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.zh-Hant.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.zh-Hant.xlf index 8ce3ada1259e1..17c965543d517 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.zh-Hant.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Adding analyzer config documents is not supported. @@ -32,6 +32,11 @@ 不支援變更文件 '{0}'。 + + CodeAction '{0}' did not produce a changed solution + CodeAction '{0}' did not produce a changed solution + "CodeAction" is a specific type, and {0} represents the title shown by the action. + Core EditorConfig Options 核心 EditorConfig 選項 @@ -192,6 +197,11 @@ 將命名空間同步到資料夾結構 + + The contents of a SourceGeneratedDocument may not be changed. + The contents of a SourceGeneratedDocument may not be changed. + {locked:SourceGeneratedDocument} + The project already contains the specified reference. 專案已包含指定的參考。 @@ -629,7 +639,7 @@ The position is not within the symbol's declaration - 位置不在符號的宣告中。 + 位置不在符號的宣告中 @@ -704,7 +714,7 @@ Deserialization reader for '{0}' read incorrect number of values. - {0}' 的還原序列化讀取器所讀取的值數目不正確。 + '{0}' 的還原序列化讀取器所讀取的值數目不正確。 diff --git a/src/Workspaces/CoreTest/SolutionTests/SolutionWithSourceGeneratorTests.cs b/src/Workspaces/CoreTest/SolutionTests/SolutionWithSourceGeneratorTests.cs index 48210ac15ad95..9f7093b9648f6 100644 --- a/src/Workspaces/CoreTest/SolutionTests/SolutionWithSourceGeneratorTests.cs +++ b/src/Workspaces/CoreTest/SolutionTests/SolutionWithSourceGeneratorTests.cs @@ -2,15 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; @@ -37,9 +34,10 @@ private static Project AddEmptyProject(Solution solution) [Theory] [CombinatorialData] public async Task SourceGeneratorBasedOnAdditionalFileGeneratesSyntaxTreesOnce( - bool fetchCompilationBeforeAddingGenerator) + bool fetchCompilationBeforeAddingGenerator, + bool useRecoverableTrees) { - using var workspace = new AdhocWorkspace(); + using var workspace = useRecoverableTrees ? AdhocWorkspaceTests.CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations() : new AdhocWorkspace(); var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented() { }); var project = AddEmptyProject(workspace.CurrentSolution) .AddAnalyzerReference(analyzerReference); @@ -60,6 +58,9 @@ public async Task SourceGeneratorBasedOnAdditionalFileGeneratesSyntaxTreesOnce( Assert.NotSame(originalCompilation, newCompilation); var generatedTree = Assert.Single(newCompilation.SyntaxTrees); Assert.Equal("Microsoft.CodeAnalysis.Workspaces.UnitTests\\Microsoft.CodeAnalysis.UnitTests.SolutionWithSourceGeneratorTests+GenerateFileForEachAdditionalFileWithContentsCommented\\Test.generated.cs", generatedTree.FilePath); + + var generatedDocument = Assert.Single(await project.GetSourceGeneratedDocumentsAsync()); + Assert.Same(generatedTree, await generatedDocument.GetSyntaxTreeAsync()); } [Fact] @@ -88,7 +89,7 @@ static async Task AssertCompilationContainsOneRegularAndOneGeneratedFile(Project Assert.Contains(regularDocumentSyntaxTree, compilation.SyntaxTrees); var generatedSyntaxTree = Assert.Single(compilation.SyntaxTrees.Where(t => t != regularDocumentSyntaxTree)); - Assert.Null(project.GetDocument(generatedSyntaxTree)); + Assert.IsType(project.GetDocument(generatedSyntaxTree)); Assert.Equal(expectedGeneratedContents, generatedSyntaxTree.GetText().ToString()); } @@ -116,7 +117,7 @@ static async Task AssertCompilationContainsGeneratedFile(Project project, string var compilation = await project.GetRequiredCompilationAsync(CancellationToken.None); var generatedSyntaxTree = Assert.Single(compilation.SyntaxTrees); - Assert.Null(project.GetDocument(generatedSyntaxTree)); + Assert.IsType(project.GetDocument(generatedSyntaxTree)); Assert.Equal(expectedGeneratedContents, generatedSyntaxTree.GetText().ToString()); } @@ -142,6 +143,28 @@ public async Task PartialCompilationsIncludeGeneratedFilesAfterFullGeneration() Assert.Same(fullCompilation, partialCompilation); } + [Fact] + public async Task DocumentIdOfGeneratedDocumentsIsStable() + { + using var workspace = new AdhocWorkspace(); + var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); + var projectBeforeChange = AddEmptyProject(workspace.CurrentSolution) + .AddAnalyzerReference(analyzerReference) + .AddAdditionalDocument("Test.txt", "Hello, world!").Project; + + var generatedDocumentBeforeChange = Assert.Single(await projectBeforeChange.GetSourceGeneratedDocumentsAsync()); + + var projectAfterChange = + projectBeforeChange.Solution.WithAdditionalDocumentText( + projectBeforeChange.AdditionalDocumentIds.Single(), + SourceText.From("Hello, world!!!!")).Projects.Single(); + + var generatedDocumentAfterChange = Assert.Single(await projectAfterChange.GetSourceGeneratedDocumentsAsync()); + + Assert.NotSame(generatedDocumentBeforeChange, generatedDocumentAfterChange); + Assert.Equal(generatedDocumentBeforeChange.Id, generatedDocumentAfterChange.Id); + } + [Fact] public async Task CompilationsInCompilationReferencesIncludeGeneratedSourceFiles() { @@ -166,21 +189,65 @@ public async Task CompilationsInCompilationReferencesIncludeGeneratedSourceFiles Assert.Same(compilationWithGenerator, compilationReference.Compilation); } - private sealed class TestGeneratorReference : AnalyzerReference + [Fact] + public async Task RequestingGeneratedDocumentsTwiceGivesSameInstance() { - private readonly ISourceGenerator _generator; + using var workspace = AdhocWorkspaceTests.CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); + var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); + var project = AddEmptyProject(workspace.CurrentSolution) + .AddAnalyzerReference(analyzerReference) + .AddAdditionalDocument("Test.txt", "Hello, world!").Project; - public TestGeneratorReference(ISourceGenerator generator) - { - _generator = generator; - } + var generatedDocumentFirstTime = Assert.Single(await project.GetSourceGeneratedDocumentsAsync()); + var tree = await generatedDocumentFirstTime.GetSyntaxTreeAsync(); + + // Fetch the compilation, and then wait for it to be GC'ed, then fetch it again. This ensures that + // finalizing a compilation more than once doesn't recreate things incorrectly. + var compilationReference = ObjectReference.CreateFromFactory(() => project.GetCompilationAsync().Result); + compilationReference.AssertReleased(); + var secondCompilation = await project.GetRequiredCompilationAsync(CancellationToken.None); + + var generatedDocumentSecondTime = Assert.Single(await project.GetSourceGeneratedDocumentsAsync()); + + Assert.Same(generatedDocumentFirstTime, generatedDocumentSecondTime); + Assert.Same(tree, secondCompilation.SyntaxTrees.Single()); + } + + [Fact] + public async Task GetDocumentWithGeneratedTreeReturnsGeneratedDocument() + { + using var workspace = new AdhocWorkspace(); + var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); + var project = AddEmptyProject(workspace.CurrentSolution) + .AddAnalyzerReference(analyzerReference) + .AddAdditionalDocument("Test.txt", "Hello, world!").Project; + + var syntaxTree = Assert.Single((await project.GetRequiredCompilationAsync(CancellationToken.None)).SyntaxTrees); + var generatedDocument = Assert.IsType(project.GetDocument(syntaxTree)); + Assert.Same(syntaxTree, await generatedDocument.GetSyntaxTreeAsync()); + } + + [Fact] + public async Task GetDocumentWithGeneratedTreeForInProgressReturnsGeneratedDocument() + { + using var workspace = new AdhocWorkspace(); + var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); + var project = AddEmptyProject(workspace.CurrentSolution) + .AddAnalyzerReference(analyzerReference) + .AddDocument("RegularDocument.cs", "// Source File", filePath: "RegularDocument.cs").Project + .AddAdditionalDocument("Test.txt", "Hello, world!").Project; + + // Ensure we've ran generators at least once + await project.GetCompilationAsync(); - public override string? FullPath => null; - public override object Id => this; + // Produce an in-progress snapshot + project = project.Documents.Single(d => d.Name == "RegularDocument.cs").WithFrozenPartialSemantics(CancellationToken.None).Project; - public override ImmutableArray GetAnalyzers(string language) => ImmutableArray.Empty; - public override ImmutableArray GetAnalyzersForAllLanguages() => ImmutableArray.Empty; - public override ImmutableArray GetGenerators() => ImmutableArray.Create(_generator); + // The generated tree should still be there; even if the regular compilation fell away we've now cached the + // generated trees. + var syntaxTree = Assert.Single((await project.GetRequiredCompilationAsync(CancellationToken.None)).SyntaxTrees, t => t.FilePath != "RegularDocument.cs"); + var generatedDocument = Assert.IsType(project.GetDocument(syntaxTree)); + Assert.Same(syntaxTree, await generatedDocument.GetSyntaxTreeAsync()); } private sealed class GenerateFileForEachAdditionalFileWithContentsCommented : ISourceGenerator diff --git a/src/Workspaces/CoreTest/WorkspaceTests/AdhocWorkspaceTests.cs b/src/Workspaces/CoreTest/WorkspaceTests/AdhocWorkspaceTests.cs index 63ebb1dbeecc3..9b2f300c1a08a 100644 --- a/src/Workspaces/CoreTest/WorkspaceTests/AdhocWorkspaceTests.cs +++ b/src/Workspaces/CoreTest/WorkspaceTests/AdhocWorkspaceTests.cs @@ -27,7 +27,7 @@ public partial class AdhocWorkspaceTests : TestBase private static AdhocWorkspace CreateWorkspace(Type[] additionalParts = null) => new AdhocWorkspace(FeaturesTestCompositions.Features.AddParts(additionalParts).GetHostServices()); - private static AdhocWorkspace CreateWorkspaceWithRecoverableSyntaxTrees() + public static AdhocWorkspace CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations() { var workspace = CreateWorkspace(new[] { @@ -414,7 +414,7 @@ public async Task TestUpdatedDocumentHasTextVersionAsync() [CombinatorialData] public async Task TestUpdatedDocumentTextIsObservablyConstantAsync(bool recoverable) { - var workspace = recoverable ? CreateWorkspaceWithRecoverableSyntaxTrees() : CreateWorkspace(); + var workspace = recoverable ? CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations() : CreateWorkspace(); await CheckUpdatedDocumentTextIsObservablyConstantAsync(workspace); } diff --git a/src/Workspaces/CoreTestUtilities/Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj b/src/Workspaces/CoreTestUtilities/Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj index 3c9bfd646d77b..547a45c1ad232 100644 --- a/src/Workspaces/CoreTestUtilities/Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj +++ b/src/Workspaces/CoreTestUtilities/Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj @@ -4,7 +4,7 @@ Library Microsoft.CodeAnalysis.UnitTests - net5.0-windows;netcoreapp3.1;net472 + net5.0-windows7.0;netcoreapp3.1;net472 true false true diff --git a/src/Workspaces/CoreTestUtilities/TestGeneratorReference.cs b/src/Workspaces/CoreTestUtilities/TestGeneratorReference.cs new file mode 100644 index 0000000000000..657e1d805378d --- /dev/null +++ b/src/Workspaces/CoreTestUtilities/TestGeneratorReference.cs @@ -0,0 +1,31 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; + +namespace Roslyn.Test.Utilities +{ + /// + /// A simple deriviation of that returns the source generator + /// passed, for ease in unit tests. + /// + public sealed class TestGeneratorReference : AnalyzerReference + { + private readonly ISourceGenerator _generator; + + public TestGeneratorReference(ISourceGenerator generator) + { + _generator = generator; + } + + public override string? FullPath => null; + public override object Id => this; + + public override ImmutableArray GetAnalyzers(string language) => ImmutableArray.Empty; + public override ImmutableArray GetAnalyzersForAllLanguages() => ImmutableArray.Empty; + public override ImmutableArray GetGenerators(string language) => ImmutableArray.Create(_generator); + } +} diff --git a/src/Workspaces/Remote/Core/RemoteEndPoint.cs b/src/Workspaces/Remote/Core/RemoteEndPoint.cs index e1acb34d6dc47..559ec56238683 100644 --- a/src/Workspaces/Remote/Core/RemoteEndPoint.cs +++ b/src/Workspaces/Remote/Core/RemoteEndPoint.cs @@ -174,7 +174,10 @@ public async Task InvokeAsync(string targetName, IReadOnlyList ar // if this end-point is already disconnected do not log more errors: var logError = _disconnectedReason == null; - using var linkedCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + // Create a separate cancellation token for the reader, which we keep open until after the call to invoke + // completes. If we close the reader before cancellation is processed by the remote call, it might block + // (deadlock) while writing to a stream which is no longer processing data. + using var readerCancellationSource = new CancellationTokenSource(); var pipeName = Guid.NewGuid().ToString(); @@ -182,23 +185,23 @@ public async Task InvokeAsync(string targetName, IReadOnlyList ar try { - // Transfer ownership of the pipe to BufferedStream, it will dispose it: - using var stream = new BufferedStream(pipe, BufferSize); - // send request to asset source var task = _rpc.InvokeWithCancellationAsync(targetName, arguments.Concat(pipeName).ToArray(), cancellationToken); // if invoke throws an exception, make sure we raise cancellation. - RaiseCancellationIfInvokeFailed(task, linkedCancellationSource, cancellationToken); + RaiseCancellationIfInvokeFailed(task, readerCancellationSource); var task2 = Task.Run(async () => { + // Transfer ownership of the pipe to BufferedStream, it will dispose it: + using var stream = new BufferedStream(pipe, BufferSize); + // wait for asset source to respond - await pipe.WaitForConnectionAsync(linkedCancellationSource.Token).ConfigureAwait(false); + await pipe.WaitForConnectionAsync(readerCancellationSource.Token).ConfigureAwait(false); // run user task with direct stream - return await dataReader(stream, linkedCancellationSource.Token).ConfigureAwait(false); - }, linkedCancellationSource.Token); + return await dataReader(stream, readerCancellationSource.Token).ConfigureAwait(false); + }, readerCancellationSource.Token); // Wait for all tasks to finish. If we return while one of the tasks is still in flight, the task would // operate as a fire-and-forget operation where the caller might release state objects still in use by @@ -208,7 +211,7 @@ public async Task InvokeAsync(string targetName, IReadOnlyList ar Debug.Assert(task2.Status == TaskStatus.RanToCompletion); return task2.Result; } - catch (Exception ex) when (!logError || ReportUnlessCanceled(ex, linkedCancellationSource.Token, cancellationToken)) + catch (Exception ex) when (!logError || ReportUnlessCanceled(ex, readerCancellationSource.Token, cancellationToken)) { // Remote call may fail with different exception even when our cancellation token is signaled // (e.g. on shutdown if the connection is dropped). @@ -305,7 +308,7 @@ private static async Task ConnectPipeAsync(NamedPipeClientStream pipe, Cancellat } } - private static void RaiseCancellationIfInvokeFailed(Task task, CancellationTokenSource linkedCancellationSource, CancellationToken cancellationToken) + private static void RaiseCancellationIfInvokeFailed(Task task, CancellationTokenSource linkedCancellationSource) { // if invoke throws an exception, make sure we raise cancellation _ = task.ContinueWith(p => @@ -322,7 +325,7 @@ private static void RaiseCancellationIfInvokeFailed(Task task, CancellationToken { // merged cancellation is already disposed } - }, cancellationToken, TaskContinuationOptions.NotOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + }, CancellationToken.None, TaskContinuationOptions.NotOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } private static bool ReportUnlessCanceled(Exception ex, CancellationToken linkedCancellationToken, CancellationToken cancellationToken) diff --git a/src/Workspaces/Remote/Core/ServiceHubRemoteHostClient.cs b/src/Workspaces/Remote/Core/ServiceHubRemoteHostClient.cs index 44df16de0fe40..45b33544e51e7 100644 --- a/src/Workspaces/Remote/Core/ServiceHubRemoteHostClient.cs +++ b/src/Workspaces/Remote/Core/ServiceHubRemoteHostClient.cs @@ -116,28 +116,13 @@ await client._endPoint.InvokeAsync( new object?[] { uiCultureLCID, cultureLCID }, cancellationToken).ConfigureAwait(false); - if (AsynchronousOperationListenerProvider.IsEnabled && !IsRpsMachine()) - { - await client.TryInvokeAsync( - (service, cancellationToken) => service.EnableAsync(AsynchronousOperationListenerProvider.IsEnabled, listenerProvider.DiagnosticTokensEnabled, cancellationToken), - cancellationToken).ConfigureAwait(false); - } + await client.TryInvokeAsync( + (service, cancellationToken) => service.EnableAsync(AsynchronousOperationListenerProvider.IsEnabled, listenerProvider.DiagnosticTokensEnabled, cancellationToken), + cancellationToken).ConfigureAwait(false); client.Started(); return client; } - - static bool IsRpsMachine() - { - try - { - return Environment.MachineName.StartsWith("dtl-"); - } - catch - { - return false; - } - } } public static async Task RequestServiceAsync( diff --git a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.cs.xlf b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.cs.xlf index c7dac4d65d346..198a2abd4bd95 100644 --- a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.cs.xlf +++ b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.cs.xlf @@ -4,127 +4,127 @@ Asset synchronization - Asset synchronization + Synchronizace prostředků Asynchronous operation listener - Asynchronous operation listener + Naslouchací proces asynchronní operace CodeLens references - CodeLens references + Odkazy CodeLens Convert tuple to struct refactoring - Convert tuple to struct refactoring + Převést řazenou kolekci členů na refaktoring struktury Dependent type finder - Dependent type finder + Vyhledávání závislých typů DesignerAttribute discovery - DesignerAttribute discovery + Zjišťování DesignerAttribute Diagnostic analyzer runner - Diagnostic analyzer runner + Spouštěč diagnostického analyzátoru Document higlights - Document higlights + Hlavní body dokumentu Encapsulate field refactoring - Encapsulate field refactoring + Zabalit refaktoring pole Extension method import completion - Extension method import completion + Dokončení importu metody rozšíření Find usages - Find usages + Vyhledat využití Global notification delivery - Global notification delivery + Doručování globálních oznámení Missing import discovery - Missing import discovery + Chybí zjišťování importů Navigate to - Navigate to + Přejít na Project telemetry collection - Project telemetry collection + Shromažďování telemetrie projektu Rename - Rename + Přejmenovat Semantic classification - Semantic classification + Sémantická klasifikace Semantic classification cache - Semantic classification cache + Mezipaměť sémantické klasifikace Asset provider - Asset provider + Poskytovatel prostředků Symbol finder - Symbol finder + Vyhledávání symbolů Symbol search - Symbol search + Hledání symbolů TODO comments discovery - TODO comments discovery + TODO zjišťování komentářů Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' - Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' + Kvůli přechodné chybě není funkce {0} momentálně k dispozici. Zkuste to prosím znovu později: {1} Feature '{0}' is currently unavailable due to an internal error. - Feature '{0}' is currently unavailable due to an internal error. + Kvůli vnitřní chybě není funkce {0} momentálně k dispozici. Feature '{0}' is currently unavailable since {1} is shutting down. - Feature '{0}' is currently unavailable since {1} is shutting down. + Funkce {0} není momentálně k dispozici, protože {1} se vypíná. diff --git a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.de.xlf b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.de.xlf index 09bfcfea811cf..e9639a40c3cc7 100644 --- a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.de.xlf +++ b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.de.xlf @@ -4,127 +4,127 @@ Asset synchronization - Asset synchronization + Objektsynchronisierung Asynchronous operation listener - Asynchronous operation listener + Listener für asynchrone Vorgänge CodeLens references - CodeLens references + CodeLens-Verweise Convert tuple to struct refactoring - Convert tuple to struct refactoring + Tupel in Strukturrefactoring konvertieren Dependent type finder - Dependent type finder + Suche nach abhängigen Typen DesignerAttribute discovery - DesignerAttribute discovery + DesignerAttribute-Ermittlung Diagnostic analyzer runner - Diagnostic analyzer runner + Runner für Diagnoseanalysetool Document higlights - Document higlights + Dokumenthighlights Encapsulate field refactoring - Encapsulate field refactoring + Feldrefactoring kapseln Extension method import completion - Extension method import completion + Erweiterungsmethodenimporte vervollständigen Find usages - Find usages + Verwendungen suchen Global notification delivery - Global notification delivery + Globale Benachrichtigungsübermittlung Missing import discovery - Missing import discovery + Fehlende Importermittlung Navigate to - Navigate to + Navigieren zu Project telemetry collection - Project telemetry collection + Projekttelemetriesammlung Rename - Rename + Umbenennen Semantic classification - Semantic classification + Semantische Klassifizierung Semantic classification cache - Semantic classification cache + Cache für semantische Klassifizierung Asset provider - Asset provider + Objektanbieter Symbol finder - Symbol finder + Symbolsuche Symbol search - Symbol search + Symbolsuche TODO comments discovery - TODO comments discovery + TODO Kommentarermittlung Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' - Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' + Das Feature "{0}" ist aufgrund eines zeitweiligen Fehlers momentan nicht verfügbar. Versuchen Sie es später noch mal: "{1}" Feature '{0}' is currently unavailable due to an internal error. - Feature '{0}' is currently unavailable due to an internal error. + Das Feature "{0}" ist aufgrund eines internen Fehlers momentan nicht verfügbar. Feature '{0}' is currently unavailable since {1} is shutting down. - Feature '{0}' is currently unavailable since {1} is shutting down. + Das Feature "{0}" ist momentan nicht verfügbar, weil "{1}" heruntergefahren wird. diff --git a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.es.xlf b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.es.xlf index cf070718cdddd..f9dfbeaeb1bfe 100644 --- a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.es.xlf +++ b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.es.xlf @@ -4,127 +4,127 @@ Asset synchronization - Asset synchronization + Sincronización de recursos Asynchronous operation listener - Asynchronous operation listener + Cliente de escucha de operaciones asincrónicas CodeLens references - CodeLens references + Referencias de CodeLens Convert tuple to struct refactoring - Convert tuple to struct refactoring + Convertir tupla en refactorización de estructura Dependent type finder - Dependent type finder + Localizador de tipos dependientes DesignerAttribute discovery - DesignerAttribute discovery + Detección de DesignerAttribute Diagnostic analyzer runner - Diagnostic analyzer runner + Ejecutor del analizador de diagnóstico Document higlights - Document higlights + Contenidos destacados del documento Encapsulate field refactoring - Encapsulate field refactoring + Encapsular la refactorización de campo Extension method import completion - Extension method import completion + Finalización de la importación del método de extensión Find usages - Find usages + Buscar usos Global notification delivery - Global notification delivery + Entrega de notificaciones globales Missing import discovery - Missing import discovery + Detección de importaciones que faltan Navigate to - Navigate to + Navegar a Project telemetry collection - Project telemetry collection + Recopilación de telemetría del proyecto Rename - Rename + Cambiar nombre Semantic classification - Semantic classification + Clasificación semántica Semantic classification cache - Semantic classification cache + Caché de clasificación semántica Asset provider - Asset provider + Proveedor de recursos Symbol finder - Symbol finder + Localizador de símbolos Symbol search - Symbol search + Búsqueda de símbolos TODO comments discovery - TODO comments discovery + Detección de comentarios TODO Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' - Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' + La característica "{0}" no está disponible debido a un error intermitente; vuelva a intentarlo más tarde: "{1}" Feature '{0}' is currently unavailable due to an internal error. - Feature '{0}' is currently unavailable due to an internal error. + La característica "{0}" no está disponible debido a un error interno. Feature '{0}' is currently unavailable since {1} is shutting down. - Feature '{0}' is currently unavailable since {1} is shutting down. + La característica "{0}" no está disponible porque {1} se está apagando. diff --git a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.fr.xlf b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.fr.xlf index e9a6e18a209c8..fb0db8d999273 100644 --- a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.fr.xlf +++ b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.fr.xlf @@ -4,127 +4,127 @@ Asset synchronization - Asset synchronization + Synchronisation des ressources Asynchronous operation listener - Asynchronous operation listener + Écouteur d'opérations asynchrones CodeLens references - CodeLens references + Références CodeLens Convert tuple to struct refactoring - Convert tuple to struct refactoring + Refactorisation de la conversion de tuple en struct Dependent type finder - Dependent type finder + Outil de recherche de type dépendant DesignerAttribute discovery - DesignerAttribute discovery + Détection de DesignerAttribute Diagnostic analyzer runner - Diagnostic analyzer runner + Exécuteur d'analyseur de diagnostic Document higlights - Document higlights + Colorations de documents Encapsulate field refactoring - Encapsulate field refactoring + Refactorisation de l'encapsulation de champ Extension method import completion - Extension method import completion + Exécution de l'importation de méthode d'extension Find usages - Find usages + Recherche d'usages Global notification delivery - Global notification delivery + Remise de notification globale Missing import discovery - Missing import discovery + Détection d'importation manquante Navigate to - Navigate to + Accéder à Project telemetry collection - Project telemetry collection + Collecte de la télémétrie du projet Rename - Rename + Renommer Semantic classification - Semantic classification + Classification sémantique Semantic classification cache - Semantic classification cache + Cache de classification sémantique Asset provider - Asset provider + Fournisseur de ressources Symbol finder - Symbol finder + Outil de recherche de symboles Symbol search - Symbol search + Recherche de symboles TODO comments discovery - TODO comments discovery + Détection de commentaires TODO Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' - Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' + La fonctionnalité '{0}' est non disponible en raison d'une erreur intermittente. Réessayez plus tard : '{1}' Feature '{0}' is currently unavailable due to an internal error. - Feature '{0}' is currently unavailable due to an internal error. + La fonctionnalité '{0}' est non disponible en raison d'une erreur interne. Feature '{0}' is currently unavailable since {1} is shutting down. - Feature '{0}' is currently unavailable since {1} is shutting down. + La fonctionnalité '{0}' est non disponible, car {1} est en cours d'arrêt. diff --git a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.it.xlf b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.it.xlf index 57fe69b8a16e4..0130eba262ffe 100644 --- a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.it.xlf +++ b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.it.xlf @@ -4,127 +4,127 @@ Asset synchronization - Asset synchronization + Sincronizzazione degli asset Asynchronous operation listener - Asynchronous operation listener + Listener di operazioni asincrone CodeLens references - CodeLens references + Riferimenti a CodeLens Convert tuple to struct refactoring - Convert tuple to struct refactoring + Conversione della tupla nel refactoring dello struct Dependent type finder - Dependent type finder + Strumento di ricerca tipi dipendenti DesignerAttribute discovery - DesignerAttribute discovery + Individuazione di DesignerAttribute Diagnostic analyzer runner - Diagnostic analyzer runner + Strumento di esecuzione dell'analizzatore diagnostico Document higlights - Document higlights + Evidenziazioni del documento Encapsulate field refactoring - Encapsulate field refactoring + Refactoring di Incapsula campo Extension method import completion - Extension method import completion + Completamento dell'importazione del metodo di estensione Find usages - Find usages + Utilizzi di Trova Global notification delivery - Global notification delivery + Recapito delle notifiche globali Missing import discovery - Missing import discovery + Individuazione delle importazioni mancanti Navigate to - Navigate to + Passa a Project telemetry collection - Project telemetry collection + Raccolta dei dati di telemetria del progetto Rename - Rename + Rinomina Semantic classification - Semantic classification + Classificazione semantica Semantic classification cache - Semantic classification cache + Cache della classificazione semantica Asset provider - Asset provider + Provider di asset Symbol finder - Symbol finder + Strumento di ricerca simboli Symbol search - Symbol search + Ricerca simboli TODO comments discovery - TODO comments discovery + Individuazione dei commenti TODO Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' - Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' + La funzionalità '{0}' non è attualmente disponibile a causa di un errore intermittente. Riprovare più tardi: '{1}' Feature '{0}' is currently unavailable due to an internal error. - Feature '{0}' is currently unavailable due to an internal error. + La funzionalità '{0}' non è attualmente disponibile a causa di un errore interno. Feature '{0}' is currently unavailable since {1} is shutting down. - Feature '{0}' is currently unavailable since {1} is shutting down. + La funzionalità '{0}' non è attualmente disponibile perché è in corso l'arresto di {1}. diff --git a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.ja.xlf b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.ja.xlf index ad90d9ea7072b..eb4049380b08e 100644 --- a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.ja.xlf +++ b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.ja.xlf @@ -4,127 +4,127 @@ Asset synchronization - Asset synchronization + 資産の同期 Asynchronous operation listener - Asynchronous operation listener + 非同期操作リスナー CodeLens references - CodeLens references + CodeLens の参照 Convert tuple to struct refactoring - Convert tuple to struct refactoring + タプルを構造体のリファクタリングに変換する Dependent type finder - Dependent type finder + 依存型の検索 DesignerAttribute discovery - DesignerAttribute discovery + DesignerAttribute の検出 Diagnostic analyzer runner - Diagnostic analyzer runner + 診断アナライザー ランナー Document higlights - Document higlights + ドキュメント強調表示 Encapsulate field refactoring - Encapsulate field refactoring + フィールドのカプセル化のリファクタリング Extension method import completion - Extension method import completion + 拡張メソッドのインポート完了 Find usages - Find usages + 使用状況の検索 Global notification delivery - Global notification delivery + グローバル通知の配信 Missing import discovery - Missing import discovery + 不足しているインポートの検出 Navigate to - Navigate to + 移動 Project telemetry collection - Project telemetry collection + プロジェクト テレメトリ コレクション Rename - Rename + 名前の変更 Semantic classification - Semantic classification + セマンティック分類 Semantic classification cache - Semantic classification cache + セマンティック分類キャッシュ Asset provider - Asset provider + 資産プロバイダー Symbol finder - Symbol finder + シンボル検索 Symbol search - Symbol search + シンボルの検索 TODO comments discovery - TODO comments discovery + TODO コメント検出 Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' - Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' + 間欠的なエラーのため、機能 '{0}' は現在使用できません。後でもう一度お試しください: '{1}' Feature '{0}' is currently unavailable due to an internal error. - Feature '{0}' is currently unavailable due to an internal error. + 内部エラーのため、機能 '{0}' は現在使用できません。 Feature '{0}' is currently unavailable since {1} is shutting down. - Feature '{0}' is currently unavailable since {1} is shutting down. + {1} がシャットダウン中のため、機能 '{0}' は現在使用できません。 diff --git a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.ko.xlf b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.ko.xlf index bb7f592a3bb50..438c0c63453e4 100644 --- a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.ko.xlf +++ b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.ko.xlf @@ -4,127 +4,127 @@ Asset synchronization - Asset synchronization + 자산 동기화 Asynchronous operation listener - Asynchronous operation listener + 비동기 작업 수신기 CodeLens references - CodeLens references + CodeLens 참조 Convert tuple to struct refactoring - Convert tuple to struct refactoring + 튜플을 구조체 리팩터링으로 변환 Dependent type finder - Dependent type finder + 종속 형식 찾기 DesignerAttribute discovery - DesignerAttribute discovery + DesignerAttribute 검색 Diagnostic analyzer runner - Diagnostic analyzer runner + 진단 분석기 실행기 Document higlights - Document higlights + 문서 하이라이트 Encapsulate field refactoring - Encapsulate field refactoring + 필드 리팩터링 캡슐화 Extension method import completion - Extension method import completion + 확장 메서드 가져오기 완료 Find usages - Find usages + 사용량 찾기 Global notification delivery - Global notification delivery + 전역 알림 배달 Missing import discovery - Missing import discovery + 가져오기 검색 없음 Navigate to - Navigate to + 다음 탐색 Project telemetry collection - Project telemetry collection + 프로젝트 원격 분석 컬렉션 Rename - Rename + 이름 바꾸기 Semantic classification - Semantic classification + 의미 체계 분류 Semantic classification cache - Semantic classification cache + 의미 체계 분류 캐시 Asset provider - Asset provider + 자산 공급자 Symbol finder - Symbol finder + 기호 찾기 Symbol search - Symbol search + 기호 검색 TODO comments discovery - TODO comments discovery + TODO 주석 검색 Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' - Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' + 일시적 오류로 인해 기능 '{0}'을(를) 현재 사용할 수 없습니다. 나중에 다시 시도하세요. '{1}' Feature '{0}' is currently unavailable due to an internal error. - Feature '{0}' is currently unavailable due to an internal error. + 내부 오류로 인해 현재 기능 '{0}'을(를) 사용할 수 없습니다. Feature '{0}' is currently unavailable since {1} is shutting down. - Feature '{0}' is currently unavailable since {1} is shutting down. + {1}을(를) 종료하는 중이므로 현재 기능 '{0}'을(를) 사용할 수 없습니다. diff --git a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.pl.xlf b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.pl.xlf index c3b88eefd3ced..fffaf2db5fbcf 100644 --- a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.pl.xlf +++ b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.pl.xlf @@ -4,127 +4,127 @@ Asset synchronization - Asset synchronization + Synchronizacja elementów zawartości Asynchronous operation listener - Asynchronous operation listener + Odbiornik operacji asynchronicznej CodeLens references - CodeLens references + Odwołania CodeLens Convert tuple to struct refactoring - Convert tuple to struct refactoring + Refaktoryzacja konwersji krotki na strukturę Dependent type finder - Dependent type finder + Wyszukiwanie typów zależnych DesignerAttribute discovery - DesignerAttribute discovery + Odnajdywanie elementu DesignerAttribute Diagnostic analyzer runner - Diagnostic analyzer runner + Moduł uruchamiający analizatora diagnostyki Document higlights - Document higlights + Wyróżnienia dokumentów Encapsulate field refactoring - Encapsulate field refactoring + Refaktoryzacja hermetyzacji pola Extension method import completion - Extension method import completion + Uzupełnianie importu metody rozszerzenia Find usages - Find usages + Znajdź użycia Global notification delivery - Global notification delivery + Dostarczanie powiadomień globalnych Missing import discovery - Missing import discovery + Odnajdywanie brakujących importów Navigate to - Navigate to + Przejdź do Project telemetry collection - Project telemetry collection + Kolekcja telemetrii projektu Rename - Rename + Zmień nazwę Semantic classification - Semantic classification + Klasyfikacja semantyczna Semantic classification cache - Semantic classification cache + Pamięć podręczna klasyfikacji semantycznej Asset provider - Asset provider + Dostawca elementów zawartości Symbol finder - Symbol finder + Wyszukiwanie symboli Symbol search - Symbol search + Wyszukiwanie symboli TODO comments discovery - TODO comments discovery + Odnajdywanie komentarzy TODO Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' - Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' + Funkcja „{0}” jest obecnie niedostępna z powodu sporadycznego błędu, spróbuj ponownie później: „{1}” Feature '{0}' is currently unavailable due to an internal error. - Feature '{0}' is currently unavailable due to an internal error. + Funkcja „{0}” jest obecnie niedostępna z powodu błędu wewnętrznego. Feature '{0}' is currently unavailable since {1} is shutting down. - Feature '{0}' is currently unavailable since {1} is shutting down. + Funkcja „{0}” jest obecnie niedostępna, ponieważ host {1} jest zamykany. diff --git a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.pt-BR.xlf b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.pt-BR.xlf index 34e6c6840b7d9..25ea356cf0590 100644 --- a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.pt-BR.xlf +++ b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.pt-BR.xlf @@ -4,127 +4,127 @@ Asset synchronization - Asset synchronization + Sincronização de ativos Asynchronous operation listener - Asynchronous operation listener + Ouvinte de operação assíncrona CodeLens references - CodeLens references + Referências CodeLens Convert tuple to struct refactoring - Convert tuple to struct refactoring + Converter a tupla em refatoração de struct Dependent type finder - Dependent type finder + Localizador de tipo dependente DesignerAttribute discovery - DesignerAttribute discovery + Descoberta de DesignerAttribute Diagnostic analyzer runner - Diagnostic analyzer runner + Executor do analisador de diagnóstico Document higlights - Document higlights + Destaques do documento Encapsulate field refactoring - Encapsulate field refactoring + Encapsular a refatoração de campo Extension method import completion - Extension method import completion + Conclusão da importação do método de extensão Find usages - Find usages + Localizar usos Global notification delivery - Global notification delivery + Entrega de notificação global Missing import discovery - Missing import discovery + Descoberta de importação ausente Navigate to - Navigate to + Navegar para Project telemetry collection - Project telemetry collection + Coleção de telemetria do projeto Rename - Rename + Renomear Semantic classification - Semantic classification + Classificação semântica Semantic classification cache - Semantic classification cache + Cache de classificação semântica Asset provider - Asset provider + Provedor de ativos Symbol finder - Symbol finder + Localizador de símbolo Symbol search - Symbol search + Pesquisa de símbolo TODO comments discovery - TODO comments discovery + Descoberta de comentários TODO Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' - Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' + O recurso '{0}' não está disponível no momento devido a um erro intermitente. Faça uma nova tentativa mais tarde: '{1}' Feature '{0}' is currently unavailable due to an internal error. - Feature '{0}' is currently unavailable due to an internal error. + O recurso '{0}' não está disponível no momento devido a um erro interno. Feature '{0}' is currently unavailable since {1} is shutting down. - Feature '{0}' is currently unavailable since {1} is shutting down. + O recurso '{0}' não está disponível no momento porque o {1} está sendo desligado. diff --git a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.ru.xlf b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.ru.xlf index eed1e24dadf30..267b5f1aa7df1 100644 --- a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.ru.xlf +++ b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.ru.xlf @@ -4,127 +4,127 @@ Asset synchronization - Asset synchronization + Синхронизация ресурсов Asynchronous operation listener - Asynchronous operation listener + Прослушиватель асинхронных операций CodeLens references - CodeLens references + Ссылки на CodeLens Convert tuple to struct refactoring - Convert tuple to struct refactoring + Преобразовать кортеж в рефакторинг структуры Dependent type finder - Dependent type finder + Поиск зависимых типов DesignerAttribute discovery - DesignerAttribute discovery + Обнаружение DesignerAttribute Diagnostic analyzer runner - Diagnostic analyzer runner + Средство запуска диагностического анализатора Document higlights - Document higlights + Выделения в документе Encapsulate field refactoring - Encapsulate field refactoring + Рефакторинг инкапсуляции поля Extension method import completion - Extension method import completion + Завершение импорта метода расширения Find usages - Find usages + Поиск использований Global notification delivery - Global notification delivery + Доставка глобальных уведомлений Missing import discovery - Missing import discovery + Отсутствует обнаружение импорта Navigate to - Navigate to + Перейти к Project telemetry collection - Project telemetry collection + Сбор данных телеметрии проекта Rename - Rename + Переименовать Semantic classification - Semantic classification + Семантическая классификация Semantic classification cache - Semantic classification cache + Кэш семантической классификации Asset provider - Asset provider + Поставщик ресурсов Symbol finder - Symbol finder + Поиск символов Symbol search - Symbol search + Поиск символов TODO comments discovery - TODO comments discovery + Обнаружение комментариев TODO Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' - Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' + Функция "{0}" сейчас недоступна из-за временной ошибки. Повторите попытку позже: "{1}". Feature '{0}' is currently unavailable due to an internal error. - Feature '{0}' is currently unavailable due to an internal error. + Функция "{0}" сейчас недоступна из-за внутренней ошибки. Feature '{0}' is currently unavailable since {1} is shutting down. - Feature '{0}' is currently unavailable since {1} is shutting down. + Функция "{0}" сейчас недоступна, так как {1} завершает работу. diff --git a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.tr.xlf b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.tr.xlf index 70196a17b930a..a5d98a2e65887 100644 --- a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.tr.xlf +++ b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.tr.xlf @@ -4,127 +4,127 @@ Asset synchronization - Asset synchronization + Varlık eşitleme Asynchronous operation listener - Asynchronous operation listener + Asenkron işlem dinleyicisi CodeLens references - CodeLens references + CodeLens başvuruları Convert tuple to struct refactoring - Convert tuple to struct refactoring + Demeti yapıya dönüştürme yeniden düzenlemesi Dependent type finder - Dependent type finder + Bağımlı tür bulucu DesignerAttribute discovery - DesignerAttribute discovery + DesignerAttribute bulma Diagnostic analyzer runner - Diagnostic analyzer runner + Tanılama çözümleyicisi çalıştırıcı Document higlights - Document higlights + Belgedeki önemli noktalar Encapsulate field refactoring - Encapsulate field refactoring + Alanı kapsülleme yeniden düzenlemesi Extension method import completion - Extension method import completion + Genişletme yöntemini içeri aktarma işlemi tamamlandı Find usages - Find usages + Kullanımları bul Global notification delivery - Global notification delivery + Genel bildirim teslimi Missing import discovery - Missing import discovery + İçeri aktarma bulma eksik Navigate to - Navigate to + Şuraya gidin: Project telemetry collection - Project telemetry collection + Proje telemetri koleksiyonu Rename - Rename + Yeniden adlandır Semantic classification - Semantic classification + Anlamsal sınıflandırma Semantic classification cache - Semantic classification cache + Anlamsal sınıflandırma önbelleği Asset provider - Asset provider + Varlık sağlayıcısı Symbol finder - Symbol finder + Sembol bulucu Symbol search - Symbol search + Sembol araması TODO comments discovery - TODO comments discovery + TODO açıklamalarını bulma Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' - Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' + '{0}' özelliği, aralıklı bir hata nedeniyle şu anda kullanılamıyor. Lütfen daha sonra yeniden deneyin: '{1}' Feature '{0}' is currently unavailable due to an internal error. - Feature '{0}' is currently unavailable due to an internal error. + '{0}' özelliği bir iç hata nedeniyle şu anda kullanılamıyor. Feature '{0}' is currently unavailable since {1} is shutting down. - Feature '{0}' is currently unavailable since {1} is shutting down. + {1} kapanmakta olduğundan '{0}' özelliği şu anda kullanılamıyor. diff --git a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.zh-Hans.xlf b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.zh-Hans.xlf index b3d3f59356af1..c7089647d197e 100644 --- a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.zh-Hans.xlf +++ b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.zh-Hans.xlf @@ -1,130 +1,130 @@  - + Asset synchronization - Asset synchronization + 资产同步 Asynchronous operation listener - Asynchronous operation listener + 异步操作侦听器 CodeLens references - CodeLens references + CodeLens 引用 Convert tuple to struct refactoring - Convert tuple to struct refactoring + 将元组转换为结构重构 Dependent type finder - Dependent type finder + 依赖类型查找器 DesignerAttribute discovery - DesignerAttribute discovery + DesignerAttribute 发现 Diagnostic analyzer runner - Diagnostic analyzer runner + 诊断分析器运行程序 Document higlights - Document higlights + 文档亮点 Encapsulate field refactoring - Encapsulate field refactoring + 封装字段重构 Extension method import completion - Extension method import completion + 扩展方法导入完成 Find usages - Find usages + 查找使用情况 Global notification delivery - Global notification delivery + 全局通知传送 Missing import discovery - Missing import discovery + 缺少导入发现 Navigate to - Navigate to + 导航到 Project telemetry collection - Project telemetry collection + 项目遥测集合 Rename - Rename + 重命名 Semantic classification - Semantic classification + 语义分类 Semantic classification cache - Semantic classification cache + 语义分类缓存 Asset provider - Asset provider + 资产提供商 Symbol finder - Symbol finder + 符号查找器 Symbol search - Symbol search + 符号搜索 TODO comments discovery - TODO comments discovery + TODO 注释发现 Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' - Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' + 功能“{0}”当前不可用,因为出现间歇性错误,请稍后重试:“{1}” Feature '{0}' is currently unavailable due to an internal error. - Feature '{0}' is currently unavailable due to an internal error. + 由于内部错误,功能“{0}”当前不可用。 Feature '{0}' is currently unavailable since {1} is shutting down. - Feature '{0}' is currently unavailable since {1} is shutting down. + 功能“{0}”当前不可用,因为 {1} 正在关闭。 diff --git a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.zh-Hant.xlf b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.zh-Hant.xlf index 292c057d1f281..06e84486b2465 100644 --- a/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.zh-Hant.xlf +++ b/src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.zh-Hant.xlf @@ -1,130 +1,130 @@  - + Asset synchronization - Asset synchronization + 資產同步 Asynchronous operation listener - Asynchronous operation listener + 非同步作業接聽程式 CodeLens references - CodeLens references + CodeLens 參考 Convert tuple to struct refactoring - Convert tuple to struct refactoring + 將元組轉換為結構重構 Dependent type finder - Dependent type finder + 相依類型尋找工具 DesignerAttribute discovery - DesignerAttribute discovery + DesignerAttribute 探索 Diagnostic analyzer runner - Diagnostic analyzer runner + 診斷分析器執行器 Document higlights - Document higlights + 文件重點 Encapsulate field refactoring - Encapsulate field refactoring + 封裝欄位重構 Extension method import completion - Extension method import completion + 擴充方法匯入完成 Find usages - Find usages + 尋找使用方式 Global notification delivery - Global notification delivery + 全域通知傳遞 Missing import discovery - Missing import discovery + 缺少匯入探索 Navigate to - Navigate to + 導覽至 Project telemetry collection - Project telemetry collection + 專案遙測集合 Rename - Rename + 重新命名 Semantic classification - Semantic classification + 語意分類 Semantic classification cache - Semantic classification cache + 語意分類快取 Asset provider - Asset provider + 資產提供者 Symbol finder - Symbol finder + 符號尋找工具 Symbol search - Symbol search + 符號搜尋 TODO comments discovery - TODO comments discovery + TODO 註解探索 Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' - Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}' + 因為發生間歇性錯誤,所以 '{0}' 功能目前無法使用,請稍後再試: '{1}' Feature '{0}' is currently unavailable due to an internal error. - Feature '{0}' is currently unavailable due to an internal error. + 因為發生內部錯誤,所以 '{0}' 功能目前無法使用。 Feature '{0}' is currently unavailable since {1} is shutting down. - Feature '{0}' is currently unavailable since {1} is shutting down. + 因為 {1} 正在關閉,所以 '{0}' 功能目前無法使用。 diff --git a/src/Workspaces/Remote/ServiceHub/Services/SemanticClassification/RemoteSemanticClassificationService.cs b/src/Workspaces/Remote/ServiceHub/Services/SemanticClassification/RemoteSemanticClassificationService.cs index bab9509db11f8..aa47a1773faf6 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/SemanticClassification/RemoteSemanticClassificationService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/SemanticClassification/RemoteSemanticClassificationService.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable - using System; using System.Threading; using System.Threading.Tasks; @@ -11,6 +9,7 @@ using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Microsoft.ServiceHub.Framework; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { @@ -36,7 +35,8 @@ public ValueTask GetSemanticClassificationsAsync( using (UserOperationBooster.Boost()) { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); - var document = solution.GetDocument(documentId); + var document = solution.GetDocument(documentId) ?? await solution.GetSourceGeneratedDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); + Contract.ThrowIfNull(document); using var _ = ArrayBuilder.GetInstance(out var temp); await AbstractClassificationService.AddSemanticClassificationsInCurrentProcessAsync( diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/CSharpTriviaFormatter.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/CSharpTriviaFormatter.cs index 89561c2624d54..69db054a73b53 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/CSharpTriviaFormatter.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/CSharpTriviaFormatter.cs @@ -180,32 +180,33 @@ private static bool IsMultilineComment(SyntaxTrivia trivia1) private bool TryFormatMultiLineCommentTrivia(LineColumn lineColumn, SyntaxTrivia trivia, out SyntaxTrivia result) { - result = default; - - if (trivia.Kind() != SyntaxKind.MultiLineCommentTrivia) - { - return false; - } - - var indentation = lineColumn.Column; - var indentationDelta = indentation - GetExistingIndentation(trivia); - if (indentationDelta != 0) + if (trivia.Kind() == SyntaxKind.MultiLineCommentTrivia) { - var multiLineComment = trivia.ToFullString().ReindentStartOfXmlDocumentationComment( - false /* forceIndentation */, - indentation, - indentationDelta, - this.Options.GetOption(FormattingOptions2.UseTabs), - this.Options.GetOption(FormattingOptions2.TabSize), - this.Options.GetOption(FormattingOptions2.NewLine)); - - var multilineCommentTrivia = SyntaxFactory.ParseLeadingTrivia(multiLineComment); - Contract.ThrowIfFalse(multilineCommentTrivia.Count == 1); - - result = multilineCommentTrivia.ElementAt(0); - return true; + var indentation = lineColumn.Column; + var indentationDelta = indentation - GetExistingIndentation(trivia); + if (indentationDelta != 0) + { + var multiLineComment = trivia.ToFullString().ReindentStartOfXmlDocumentationComment( + false /* forceIndentation */, + indentation, + indentationDelta, + this.Options.GetOption(FormattingOptions2.UseTabs), + this.Options.GetOption(FormattingOptions2.TabSize), + this.Options.GetOption(FormattingOptions2.NewLine)); + + var multilineCommentTrivia = SyntaxFactory.ParseLeadingTrivia(multiLineComment); + Contract.ThrowIfFalse(multilineCommentTrivia.Count == 1); + + // Preserve annotations on this comment as the formatter is only supposed to touch whitespace, and + // thus should make it appear as if the original comment trivia (with annotations) is still there in + // the resultant formatted tree. + var firstTrivia = multilineCommentTrivia.First(); + result = trivia.CopyAnnotationsTo(firstTrivia); + return true; + } } + result = default; return false; } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpSyntaxFacts.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpSyntaxFacts.cs index 1a419942eb87d..d6d0957424204 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpSyntaxFacts.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpSyntaxFacts.cs @@ -667,27 +667,35 @@ public bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node) public bool IsPropertyPatternClause(SyntaxNode node) => node.Kind() == SyntaxKind.PropertyPatternClause; - public bool IsObjectInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node) - => IsObjectInitializerNamedAssignmentIdentifier(node, out _); + public bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node) + => IsMemberInitializerNamedAssignmentIdentifier(node, out _); - public bool IsObjectInitializerNamedAssignmentIdentifier( + public bool IsMemberInitializerNamedAssignmentIdentifier( [NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance) { initializedInstance = null; if (node is IdentifierNameSyntax identifier && - identifier.IsLeftSideOfAssignExpression() && - identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression)) + identifier.IsLeftSideOfAssignExpression()) { - var objectInitializer = identifier.Parent.Parent; - if (objectInitializer.IsParentKind(SyntaxKind.ObjectCreationExpression)) + if (identifier.Parent.IsParentKind(SyntaxKind.WithInitializerExpression)) { - initializedInstance = objectInitializer.Parent!; + var withInitializer = identifier.Parent.GetRequiredParent(); + initializedInstance = withInitializer.GetRequiredParent(); return true; } - else if (objectInitializer.IsParentKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment)) + else if (identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression)) { - initializedInstance = assignment.Left; - return true; + var objectInitializer = identifier.Parent.GetRequiredParent(); + if (objectInitializer.Parent is BaseObjectCreationExpressionSyntax) + { + initializedInstance = objectInitializer.Parent; + return true; + } + else if (objectInitializer.IsParentKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment)) + { + initializedInstance = assignment.Left; + return true; + } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Simplification/Simplifiers/CastSimplifier.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Simplification/Simplifiers/CastSimplifier.cs index a0ff555bd023e..a67a759a2d2a3 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Simplification/Simplifiers/CastSimplifier.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Simplification/Simplifiers/CastSimplifier.cs @@ -476,9 +476,33 @@ private static bool CastMustBePreserved( if (IsIntPtrToNativeIntegerNestedCast(castNode, castType, castedExpressionType, semanticModel, cancellationToken)) return true; + // If we have `~(ulong)uintVal` then we have to preserve the `(ulong)` cast. Otherwise, the `~` will + // operate on the shorter-bit value, before being extended out to the full length, rather than operating on + // the full length. + if (IsBitwiseNotOfExtendedUnsignedValue(castNode, conversion, castType, castedExpressionType)) + return true; + return false; } + private static bool IsBitwiseNotOfExtendedUnsignedValue(ExpressionSyntax castNode, Conversion conversion, ITypeSymbol castType, ITypeSymbol castedExressionType) + { + if (castNode.WalkUpParentheses().IsParentKind(SyntaxKind.BitwiseNotExpression) && + conversion.IsImplicit && + conversion.IsNumeric) + { + return IsUnsigned(castType) || IsUnsigned(castedExressionType); + } + + return false; + } + + private static bool IsUnsigned(ITypeSymbol type) + => type.SpecialType.IsUnsignedIntegralType() || IsNuint(type); + + private static bool IsNuint(ITypeSymbol type) + => type.SpecialType == SpecialType.System_UIntPtr && type.IsNativeIntegerType; + private static bool IsIntPtrToNativeIntegerNestedCast(ExpressionSyntax castNode, ITypeSymbol castType, ITypeSymbol castedExpressionType, SemanticModel semanticModel, CancellationToken cancellationToken) { if (castedExpressionType == null) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/xlf/CSharpCompilerExtensionsResources.zh-Hans.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/xlf/CSharpCompilerExtensionsResources.zh-Hans.xlf index 3291ff4c83c99..1e0ff32ca744e 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/xlf/CSharpCompilerExtensionsResources.zh-Hans.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/xlf/CSharpCompilerExtensionsResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Code-block preferences diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/xlf/CSharpCompilerExtensionsResources.zh-Hant.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/xlf/CSharpCompilerExtensionsResources.zh-Hant.xlf index 2e381709df945..2e71efe3e915c 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/xlf/CSharpCompilerExtensionsResources.zh-Hant.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/xlf/CSharpCompilerExtensionsResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Code-block preferences diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SyntaxNodeExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SyntaxNodeExtensions.cs index bc027756bb417..9c3274e0e2f6a 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SyntaxNodeExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SyntaxNodeExtensions.cs @@ -18,6 +18,9 @@ namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class SyntaxNodeExtensions { + public static SyntaxNode GetRequiredParent(this SyntaxNode node) + => node.Parent ?? throw new InvalidOperationException("Node's parent was null"); + public static IEnumerable DepthFirstTraversal(this SyntaxNode node) => SyntaxNodeOrTokenExtensions.DepthFirstTraversal(node); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ISyntaxFacts.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ISyntaxFacts.cs index 60df87d9ee826..1e79558e19ef6 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ISyntaxFacts.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ISyntaxFacts.cs @@ -275,8 +275,8 @@ void GetPartsOfTupleExpression(SyntaxNode node, SyntaxList GetAttributeLists(SyntaxNode? node); bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node); - bool IsObjectInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node); - bool IsObjectInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance); + bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node); + bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance); bool IsDirective([NotNullWhen(true)] SyntaxNode? node); bool IsStatement([NotNullWhen(true)] SyntaxNode? node); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.de.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.de.xlf index ead0c4bc2cddf..4cb0c3e798300 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.de.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.de.xlf @@ -194,7 +194,7 @@ Suppression preferences - Suppression preferences + Unterdrückungseinstellungen diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.es.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.es.xlf index fb1ebcd378b5c..83281cd650a18 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.es.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.es.xlf @@ -194,7 +194,7 @@ Suppression preferences - Suppression preferences + Preferencias de eliminación diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.fr.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.fr.xlf index d79a98ad31066..26e830b32c47d 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.fr.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.fr.xlf @@ -194,7 +194,7 @@ Suppression preferences - Suppression preferences + Préférences de suppression diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.it.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.it.xlf index 11de26a8a38e4..ed7e10f933053 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.it.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.it.xlf @@ -194,7 +194,7 @@ Suppression preferences - Suppression preferences + Preferenze per eliminazione diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.ja.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.ja.xlf index 1a51e44329ca0..6cd4886fe9621 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.ja.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.ja.xlf @@ -194,7 +194,7 @@ Suppression preferences - Suppression preferences + 抑制の設定 diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.ko.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.ko.xlf index a4b06690cf653..524d6892a43c5 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.ko.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.ko.xlf @@ -194,7 +194,7 @@ Suppression preferences - Suppression preferences + 비표시 오류(Suppression) 기본 설정 diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.pl.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.pl.xlf index b572328b6ac79..2e588c91b4943 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.pl.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.pl.xlf @@ -194,7 +194,7 @@ Suppression preferences - Suppression preferences + Preferencje pomijania diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.pt-BR.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.pt-BR.xlf index 5dd5b85d87774..01a47b0ea2453 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.pt-BR.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.pt-BR.xlf @@ -194,7 +194,7 @@ Suppression preferences - Suppression preferences + Preferências de supressão diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.ru.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.ru.xlf index cb890487ae04f..ec6cd61033d75 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.ru.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.ru.xlf @@ -194,7 +194,7 @@ Suppression preferences - Suppression preferences + Параметры подавления diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.tr.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.tr.xlf index c3fb2d1c0ea99..104240d2f0978 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.tr.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.tr.xlf @@ -194,7 +194,7 @@ Suppression preferences - Suppression preferences + Gizleme tercihleri diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.zh-Hans.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.zh-Hans.xlf index 705b4c23dac97..cfcb8744965a8 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.zh-Hans.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Absolute path expected. diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.zh-Hant.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.zh-Hant.xlf index 4b74202ab3576..cfa5a2b75ca3a 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.zh-Hant.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Absolute path expected. @@ -194,7 +194,7 @@ Suppression preferences - Suppression preferences + 隱藏項目喜好設定 diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxFacts.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxFacts.vb index f6501a78b3097..f90a13ee38095 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxFacts.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxFacts.vb @@ -685,14 +685,14 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageServices Return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments) End Function - Public Function IsObjectInitializerNamedAssignmentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsObjectInitializerNamedAssignmentIdentifier + Public Function IsMemberInitializerNamedAssignmentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier Dim unused As SyntaxNode = Nothing - Return IsObjectInitializerNamedAssignmentIdentifier(node, unused) + Return IsMemberInitializerNamedAssignmentIdentifier(node, unused) End Function - Public Function IsObjectInitializerNamedAssignmentIdentifier( + Public Function IsMemberInitializerNamedAssignmentIdentifier( node As SyntaxNode, - ByRef initializedInstance As SyntaxNode) As Boolean Implements ISyntaxFacts.IsObjectInitializerNamedAssignmentIdentifier + ByRef initializedInstance As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier Dim identifier = TryCast(node, IdentifierNameSyntax) If identifier?.IsChildNode(Of NamedFieldInitializerSyntax)(Function(n) n.Name) Then diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/xlf/VisualBasicCompilerExtensionsResources.zh-Hans.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/xlf/VisualBasicCompilerExtensionsResources.zh-Hans.xlf index 39fa79607f3aa..155ea86197fdf 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/xlf/VisualBasicCompilerExtensionsResources.zh-Hans.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/xlf/VisualBasicCompilerExtensionsResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Remove this value when another is added. diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/xlf/VisualBasicCompilerExtensionsResources.zh-Hant.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/xlf/VisualBasicCompilerExtensionsResources.zh-Hant.xlf index ff3682d48f3af..f55bfe6f436cb 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/xlf/VisualBasicCompilerExtensionsResources.zh-Hant.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/xlf/VisualBasicCompilerExtensionsResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Remove this value when another is added. diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeSymbolExtensions.TypeSyntaxGeneratorVisitor.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeSymbolExtensions.TypeSyntaxGeneratorVisitor.cs index 7737317cd6429..6fb64a1a79f57 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeSymbolExtensions.TypeSyntaxGeneratorVisitor.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeSymbolExtensions.TypeSyntaxGeneratorVisitor.cs @@ -300,7 +300,8 @@ public override TypeSyntax VisitNamedType(INamedTypeSymbol symbol) } } - if (symbol.NullableAnnotation == NullableAnnotation.Annotated) + if (symbol.NullableAnnotation == NullableAnnotation.Annotated && + !symbol.IsValueType) { typeSyntax = AddInformationTo(SyntaxFactory.NullableType(typeSyntax), symbol); } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/xlf/CSharpWorkspaceExtensionsResources.zh-Hans.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/xlf/CSharpWorkspaceExtensionsResources.zh-Hans.xlf index 0c1c5879521dc..67c1d38fbe4d9 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/xlf/CSharpWorkspaceExtensionsResources.zh-Hans.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/xlf/CSharpWorkspaceExtensionsResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Remove this value when another is added. diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/xlf/CSharpWorkspaceExtensionsResources.zh-Hant.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/xlf/CSharpWorkspaceExtensionsResources.zh-Hant.xlf index d9e152f5c39e1..ea787c014c254 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/xlf/CSharpWorkspaceExtensionsResources.zh-Hant.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/xlf/CSharpWorkspaceExtensionsResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Remove this value when another is added. diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/DocumentExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/DocumentExtensions.cs index 402feabbc3eaa..32219b7797f2f 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/DocumentExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/DocumentExtensions.cs @@ -74,7 +74,7 @@ public static SyntaxNode GetRequiredSyntaxRootSynchronously(this Document docume public static bool IsOpen(this TextDocument document) { - var workspace = document.Project.Solution.Workspace as Workspace; + var workspace = document.Project.Solution.Workspace; return workspace != null && workspace.IsDocumentOpen(document.Id); } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/xlf/WorkspaceExtensionsResources.ja.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/xlf/WorkspaceExtensionsResources.ja.xlf index d0441234eaba7..878a0817f7cb4 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/xlf/WorkspaceExtensionsResources.ja.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/xlf/WorkspaceExtensionsResources.ja.xlf @@ -14,7 +14,7 @@ Fix all '{0}' in '{1}' - {1}' に含まれているすべての '{0}' を修正します + '{1}' に含まれているすべての '{0}' を修正します diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/xlf/WorkspaceExtensionsResources.ko.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/xlf/WorkspaceExtensionsResources.ko.xlf index 899a43b88a4b4..b7893a187a979 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/xlf/WorkspaceExtensionsResources.ko.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/xlf/WorkspaceExtensionsResources.ko.xlf @@ -14,7 +14,7 @@ Fix all '{0}' in '{1}' - {1}'의 모든 '{0}' 수정 + '{1}'의 모든 '{0}' 수정 diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/xlf/WorkspaceExtensionsResources.tr.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/xlf/WorkspaceExtensionsResources.tr.xlf index 1e56b8a05175f..befe4cda1ace2 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/xlf/WorkspaceExtensionsResources.tr.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/xlf/WorkspaceExtensionsResources.tr.xlf @@ -14,7 +14,7 @@ Fix all '{0}' in '{1}' - {1}' içinde geçtiği her yerde '{0}' ifadesini düzelt + '{1}' içinde geçtiği her yerde '{0}' ifadesini düzelt diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/xlf/WorkspaceExtensionsResources.zh-Hans.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/xlf/WorkspaceExtensionsResources.zh-Hans.xlf index 6196afb3309a9..47db64935218e 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/xlf/WorkspaceExtensionsResources.zh-Hans.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/xlf/WorkspaceExtensionsResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Compilation is required to accomplish the task but is not supported by project {0}. diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/xlf/WorkspaceExtensionsResources.zh-Hant.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/xlf/WorkspaceExtensionsResources.zh-Hant.xlf index 726bc7c6fa2ab..80993bd8ba7b4 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/xlf/WorkspaceExtensionsResources.zh-Hant.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/xlf/WorkspaceExtensionsResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Compilation is required to accomplish the task but is not supported by project {0}. diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/xlf/VisualBasicWorkspaceExtensionsResources.zh-Hans.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/xlf/VisualBasicWorkspaceExtensionsResources.zh-Hans.xlf index e6b6b44b58aaf..52ae731275e8d 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/xlf/VisualBasicWorkspaceExtensionsResources.zh-Hans.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/xlf/VisualBasicWorkspaceExtensionsResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Remove this value when another is added. diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/xlf/VisualBasicWorkspaceExtensionsResources.zh-Hant.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/xlf/VisualBasicWorkspaceExtensionsResources.zh-Hant.xlf index 68339b2513640..bf9f43e07b96d 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/xlf/VisualBasicWorkspaceExtensionsResources.zh-Hant.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/xlf/VisualBasicWorkspaceExtensionsResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Remove this value when another is added. diff --git a/src/VisualStudio/IntegrationTest/IntegrationTests/IntegrationTestSourceGenerator.cs b/src/Workspaces/TestSourceGenerator/HelloWorldGenerator.cs similarity index 75% rename from src/VisualStudio/IntegrationTest/IntegrationTests/IntegrationTestSourceGenerator.cs rename to src/Workspaces/TestSourceGenerator/HelloWorldGenerator.cs index f52f33fb13a3b..f524eb6283cd3 100644 --- a/src/VisualStudio/IntegrationTest/IntegrationTests/IntegrationTestSourceGenerator.cs +++ b/src/Workspaces/TestSourceGenerator/HelloWorldGenerator.cs @@ -2,18 +2,16 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable - using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; -namespace Roslyn.VisualStudio.IntegrationTests +namespace Microsoft.CodeAnalysis.TestSourceGenerator { [Generator] - internal sealed class IntegrationTestSourceGenerator : ISourceGenerator + public sealed class HelloWorldGenerator : ISourceGenerator { - public const string GeneratedClassName = nameof(IntegrationTestSourceGenerator) + "Output"; + public const string GeneratedClassName = "HelloWorld"; public void Initialize(GeneratorInitializationContext context) { diff --git a/src/Workspaces/TestSourceGenerator/Microsoft.CodeAnalysis.TestSourceGenerator.csproj b/src/Workspaces/TestSourceGenerator/Microsoft.CodeAnalysis.TestSourceGenerator.csproj new file mode 100644 index 0000000000000..4422150f411dd --- /dev/null +++ b/src/Workspaces/TestSourceGenerator/Microsoft.CodeAnalysis.TestSourceGenerator.csproj @@ -0,0 +1,10 @@ + + + + + netstandard2.0 + + + + + diff --git a/src/Workspaces/VisualBasic/Portable/Workspace/LanguageServices/VisualBasicCompilationFactoryService.vb b/src/Workspaces/VisualBasic/Portable/Workspace/LanguageServices/VisualBasicCompilationFactoryService.vb index f9cb3c279408c..36838a5068ed8 100644 --- a/src/Workspaces/VisualBasic/Portable/Workspace/LanguageServices/VisualBasicCompilationFactoryService.vb +++ b/src/Workspaces/VisualBasic/Portable/Workspace/LanguageServices/VisualBasicCompilationFactoryService.vb @@ -49,7 +49,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic End Function Public Function CreateGeneratorDriver(parseOptions As ParseOptions, generators As ImmutableArray(Of ISourceGenerator), optionsProvider As AnalyzerConfigOptionsProvider, additionalTexts As ImmutableArray(Of AdditionalText)) As GeneratorDriver Implements ICompilationFactoryService.CreateGeneratorDriver - Return Nothing + Return VisualBasicGeneratorDriver.Create(generators, additionalTexts, DirectCast(parseOptions, VisualBasicParseOptions), optionsProvider) End Function End Class End Namespace diff --git a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.zh-Hans.xlf b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.zh-Hans.xlf index 27dbcabbc879b..0fa6305596f0b 100644 --- a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.zh-Hans.xlf +++ b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.zh-Hans.xlf @@ -1,6 +1,6 @@  - + Namespace can not be added in this destination. diff --git a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.zh-Hant.xlf b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.zh-Hant.xlf index c23b2176313c7..62c089f1c52fb 100644 --- a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.zh-Hant.xlf +++ b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.zh-Hant.xlf @@ -1,6 +1,6 @@  - + Namespace can not be added in this destination.