repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/ExpressionEvaluator/VisualBasic/Source/ResultProvider/NetFX20/AssemblyInfo.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. <Assembly: System.Runtime.Versioning.TargetFramework(".NETFramework,Version=v2.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. <Assembly: System.Runtime.Versioning.TargetFramework(".NETFramework,Version=v2.0")>
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Workspaces/MSBuildTest/Resources/SourceFiles/VisualBasic/Application.Designer.vb
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.235 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.235 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/VisualStudio/Core/Def/Implementation/TableDataSource/MiscellaneousDiagnosticListTable.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.Shell.TableManager; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { [ExportEventListener(WellKnownEventListeners.DiagnosticService, WorkspaceKind.MiscellaneousFiles), Shared] internal sealed class MiscellaneousDiagnosticListTableWorkspaceEventListener : IEventListener<IDiagnosticService> { internal const string IdentifierString = nameof(MiscellaneousDiagnosticListTable); private readonly ITableManagerProvider _tableManagerProvider; private readonly IGlobalOptionService _globalOptions; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MiscellaneousDiagnosticListTableWorkspaceEventListener( ITableManagerProvider tableManagerProvider, IGlobalOptionService globalOptions) { _tableManagerProvider = tableManagerProvider; _globalOptions = globalOptions; } public void StartListening(Workspace workspace, IDiagnosticService diagnosticService) => new MiscellaneousDiagnosticListTable(workspace, _globalOptions, diagnosticService, _tableManagerProvider); private sealed class MiscellaneousDiagnosticListTable : VisualStudioBaseDiagnosticListTable { private readonly LiveTableDataSource _source; public MiscellaneousDiagnosticListTable(Workspace workspace, IGlobalOptionService globalOptions, IDiagnosticService diagnosticService, ITableManagerProvider provider) : base(workspace, provider) { _source = new LiveTableDataSource(workspace, globalOptions, diagnosticService, IdentifierString); AddInitialTableSource(workspace.CurrentSolution, _source); ConnectWorkspaceEvents(); } protected override void AddTableSourceIfNecessary(Solution solution) { if (solution.ProjectIds.Count == 0 || this.TableManager.Sources.Any(s => s == _source)) { return; } AddTableSource(_source); } protected override void RemoveTableSourceIfNecessary(Solution solution) { if (solution.ProjectIds.Count > 0 || !this.TableManager.Sources.Any(s => s == _source)) { return; } this.TableManager.RemoveSource(_source); } protected override void ShutdownSource() => _source.Shutdown(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.Shell.TableManager; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { [ExportEventListener(WellKnownEventListeners.DiagnosticService, WorkspaceKind.MiscellaneousFiles), Shared] internal sealed class MiscellaneousDiagnosticListTableWorkspaceEventListener : IEventListener<IDiagnosticService> { internal const string IdentifierString = nameof(MiscellaneousDiagnosticListTable); private readonly ITableManagerProvider _tableManagerProvider; private readonly IGlobalOptionService _globalOptions; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MiscellaneousDiagnosticListTableWorkspaceEventListener( ITableManagerProvider tableManagerProvider, IGlobalOptionService globalOptions) { _tableManagerProvider = tableManagerProvider; _globalOptions = globalOptions; } public void StartListening(Workspace workspace, IDiagnosticService diagnosticService) => new MiscellaneousDiagnosticListTable(workspace, _globalOptions, diagnosticService, _tableManagerProvider); private sealed class MiscellaneousDiagnosticListTable : VisualStudioBaseDiagnosticListTable { private readonly LiveTableDataSource _source; public MiscellaneousDiagnosticListTable(Workspace workspace, IGlobalOptionService globalOptions, IDiagnosticService diagnosticService, ITableManagerProvider provider) : base(workspace, provider) { _source = new LiveTableDataSource(workspace, globalOptions, diagnosticService, IdentifierString); AddInitialTableSource(workspace.CurrentSolution, _source); ConnectWorkspaceEvents(); } protected override void AddTableSourceIfNecessary(Solution solution) { if (solution.ProjectIds.Count == 0 || this.TableManager.Sources.Any(s => s == _source)) { return; } AddTableSource(_source); } protected override void RemoveTableSourceIfNecessary(Solution solution) { if (solution.ProjectIds.Count > 0 || !this.TableManager.Sources.Any(s => s == _source)) { return; } this.TableManager.RemoveSource(_source); } protected override void ShutdownSource() => _source.Shutdown(); } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Tools/ExternalAccess/FSharp/Internal/CommentSelection/FSharpCommentSelectionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommentSelection; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.CommentSelection { [Shared] [ExportLanguageService(typeof(ICommentSelectionService), LanguageNames.FSharp)] internal class FSharpCommentSelectionService : ICommentSelectionService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpCommentSelectionService() { } public Task<Document> FormatAsync(Document document, ImmutableArray<TextSpan> changes, CancellationToken cancellationToken) { return Task.FromResult(document); } public Task<CommentSelectionInfo> GetInfoAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken) { return Task.FromResult(new CommentSelectionInfo( supportsSingleLineComment: true, supportsBlockComment: true, singleLineCommentString: "//", blockCommentStartString: "(*", blockCommentEndString: "*)")); } } }
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommentSelection; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.CommentSelection { [Shared] [ExportLanguageService(typeof(ICommentSelectionService), LanguageNames.FSharp)] internal class FSharpCommentSelectionService : ICommentSelectionService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpCommentSelectionService() { } public Task<Document> FormatAsync(Document document, ImmutableArray<TextSpan> changes, CancellationToken cancellationToken) { return Task.FromResult(document); } public Task<CommentSelectionInfo> GetInfoAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken) { return Task.FromResult(new CommentSelectionInfo( supportsSingleLineComment: true, supportsBlockComment: true, singleLineCommentString: "//", blockCommentStartString: "(*", blockCommentEndString: "*)")); } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.es.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="es" original="../CSharpCodeFixesResources.resx"> <body> <trans-unit id="Add_this"> <source>Add 'this.'</source> <target state="translated">Agregar "this."</target> <note /> </trans-unit> <trans-unit id="Convert_typeof_to_nameof"> <source>Convert 'typeof' to 'nameof'</source> <target state="translated">Convertir "typeof" en "nameof"</target> <note /> </trans-unit> <trans-unit id="Pass_in_captured_variables_as_arguments"> <source>Pass in captured variables as arguments</source> <target state="translated">Pasar variables capturadas como argumentos</target> <note /> </trans-unit> <trans-unit id="Place_colon_on_following_line"> <source>Place colon on following line</source> <target state="translated">Colocar dos puntos en la línea siguiente</target> <note /> </trans-unit> <trans-unit id="Place_statement_on_following_line"> <source>Place statement on following line</source> <target state="translated">Instrucción de colocación en la línea siguiente</target> <note /> </trans-unit> <trans-unit id="Remove_Unnecessary_Usings"> <source>Remove Unnecessary Usings</source> <target state="translated">Eliminar instrucciones Using innecesarias</target> <note /> </trans-unit> <trans-unit id="Remove_blank_lines_between_braces"> <source>Remove blank line between braces</source> <target state="translated">Quitar línea en blanco entre llaves</target> <note /> </trans-unit> <trans-unit id="Remove_unreachable_code"> <source>Remove unreachable code</source> <target state="translated">Quitar código inaccesible</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Adding_parameters_to_local_function_declaration_may_produce_invalid_code"> <source>Warning: Adding parameters to local function declaration may produce invalid code.</source> <target state="translated">Advertencia: Agregar parámetros a la declaración de función local puede generar código no válido.</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="es" original="../CSharpCodeFixesResources.resx"> <body> <trans-unit id="Add_this"> <source>Add 'this.'</source> <target state="translated">Agregar "this."</target> <note /> </trans-unit> <trans-unit id="Convert_typeof_to_nameof"> <source>Convert 'typeof' to 'nameof'</source> <target state="translated">Convertir "typeof" en "nameof"</target> <note /> </trans-unit> <trans-unit id="Pass_in_captured_variables_as_arguments"> <source>Pass in captured variables as arguments</source> <target state="translated">Pasar variables capturadas como argumentos</target> <note /> </trans-unit> <trans-unit id="Place_colon_on_following_line"> <source>Place colon on following line</source> <target state="translated">Colocar dos puntos en la línea siguiente</target> <note /> </trans-unit> <trans-unit id="Place_statement_on_following_line"> <source>Place statement on following line</source> <target state="translated">Instrucción de colocación en la línea siguiente</target> <note /> </trans-unit> <trans-unit id="Remove_Unnecessary_Usings"> <source>Remove Unnecessary Usings</source> <target state="translated">Eliminar instrucciones Using innecesarias</target> <note /> </trans-unit> <trans-unit id="Remove_blank_lines_between_braces"> <source>Remove blank line between braces</source> <target state="translated">Quitar línea en blanco entre llaves</target> <note /> </trans-unit> <trans-unit id="Remove_unreachable_code"> <source>Remove unreachable code</source> <target state="translated">Quitar código inaccesible</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Adding_parameters_to_local_function_declaration_may_produce_invalid_code"> <source>Warning: Adding parameters to local function declaration may produce invalid code.</source> <target state="translated">Advertencia: Agregar parámetros a la declaración de función local puede generar código no válido.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/SuppressFormattingRule.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal class SuppressFormattingRule : BaseFormattingRule { internal const string Name = "CSharp Suppress Formatting Rule"; public override void AddSuppressOperations(List<SuppressOperation> list, SyntaxNode node, in NextSuppressOperationAction nextOperation) { nextOperation.Invoke(); AddFormatSuppressOperations(list, node); AddInitializerSuppressOperations(list, node); AddBraceSuppressOperations(list, node); AddStatementExceptBlockSuppressOperations(list, node); AddSpecificNodesSuppressOperations(list, node); } private static void AddSpecificNodesSuppressOperations(List<SuppressOperation> list, SyntaxNode node) { if (node is IfStatementSyntax ifStatementNode) { AddSuppressWrappingIfOnSingleLineOperation(list, ifStatementNode.IfKeyword, ifStatementNode.Statement.GetLastToken(includeZeroWidth: true)); if (ifStatementNode.Else != null) { AddSuppressWrappingIfOnSingleLineOperation(list, ifStatementNode.Else.ElseKeyword, ifStatementNode.Else.Statement.GetLastToken(includeZeroWidth: true)); } return; } // ex: `e is Type ( /* positional */ )` if (node.IsKind(SyntaxKind.RecursivePattern, out RecursivePatternSyntax? recursivePattern)) { var positional = recursivePattern.PositionalPatternClause; var property = recursivePattern.PropertyPatternClause; if (positional != null) { var openParenToken = positional.OpenParenToken; var closeParenToken = positional.CloseParenToken; // Formatting should refrain from inserting new lines, unless the user already split across multiple lines AddSuppressWrappingIfOnSingleLineOperation(list, openParenToken, closeParenToken); if (property != null) { AddSuppressWrappingIfOnSingleLineOperation(list, openParenToken, property.GetLastToken()); } } // ex: `Property: <pattern>` inside a recursive pattern, such as `e is { Property: <pattern>, ... }` else if (property != null) { var openBraceToken = property.OpenBraceToken; var closeBraceToken = property.CloseBraceToken; // Formatting should refrain from inserting new lines, unless the user already split across multiple lines AddSuppressWrappingIfOnSingleLineOperation(list, openBraceToken, closeBraceToken); } return; } // ex: `<pattern>: expression` inside a switch expression, such as `e switch { <pattern>: expression, ... }` if (node.IsKind(SyntaxKind.SwitchExpressionArm)) { // Formatting should refrain from inserting new lines, unless the user already split across multiple lines AddSuppressWrappingIfOnSingleLineOperation(list, node.GetFirstToken(), node.GetLastToken()); return; } // ex: `e switch { <pattern>: expression, ... }` if (node.IsKind(SyntaxKind.SwitchExpression)) { // Formatting should refrain from inserting new lines, unless the user already split across multiple lines AddSuppressWrappingIfOnSingleLineOperation(list, node.GetFirstToken(), node.GetLastToken()); return; } // ex: `case <pattern>:` inside a switch statement if (node is CasePatternSwitchLabelSyntax casePattern) { // Formatting should refrain from inserting new lines, unless the user already split across multiple lines AddSuppressWrappingIfOnSingleLineOperation(list, casePattern.GetFirstToken(), casePattern.GetLastToken()); return; } // ex: `expression is <pattern>` if (node is IsPatternExpressionSyntax isPattern) { // Formatting should refrain from inserting new lines, unless the user already split across multiple lines AddSuppressWrappingIfOnSingleLineOperation(list, isPattern.GetFirstToken(), isPattern.GetLastToken()); if (isPattern.Pattern.IsKind(SyntaxKind.RecursivePattern, out recursivePattern)) { // ex: // ``` // _ = expr is (1, 2) { }$$ // M(); // ``` // or: // ``` // _ = expr is { }$$ // M(); // ``` var propertyPatternClause = recursivePattern.PropertyPatternClause; if (propertyPatternClause != null) { AddSuppressWrappingIfOnSingleLineOperation(list, isPattern.IsKeyword, propertyPatternClause.GetLastToken()); } } return; } if (node is ConstructorInitializerSyntax constructorInitializerNode) { var constructorDeclarationNode = constructorInitializerNode.Parent as ConstructorDeclarationSyntax; if (constructorDeclarationNode?.Body != null) { AddSuppressWrappingIfOnSingleLineOperation(list, constructorInitializerNode.ColonToken, constructorDeclarationNode.Body.CloseBraceToken); } return; } if (node is DoStatementSyntax whileStatementNode) { AddSuppressWrappingIfOnSingleLineOperation(list, whileStatementNode.GetFirstToken(includeZeroWidth: true), whileStatementNode.Statement.GetLastToken(includeZeroWidth: true)); return; } if (node is MemberDeclarationSyntax memberDeclNode) { // Attempt to keep the part of a member that follows the attributes on a single // line if that's how it's currently written. var (firstToken, lastToken) = memberDeclNode.GetFirstAndLastMemberDeclarationTokensAfterAttributes(); AddSuppressWrappingIfOnSingleLineOperation(list, firstToken, lastToken); // Also, If the member is on single line with its attributes on it, then keep // it on a single line. This is for code like the following: // // [Import] public int Field1; // [Import] public int Field2; var attributes = memberDeclNode.GetAttributes(); var endToken = node.GetLastToken(includeZeroWidth: true); for (var i = 0; i < attributes.Count; ++i) { AddSuppressWrappingIfOnSingleLineOperation(list, attributes[i].GetFirstToken(includeZeroWidth: true), endToken); } var propertyDeclNode = node as PropertyDeclarationSyntax; if (propertyDeclNode?.Initializer != null && propertyDeclNode?.AccessorList != null) { AddSuppressWrappingIfOnSingleLineOperation(list, firstToken, propertyDeclNode.AccessorList.GetLastToken()); } return; } if (node is AccessorDeclarationSyntax accessorDeclNode) { AddSuppressWrappingIfOnSingleLineOperation(list, accessorDeclNode.Keyword, accessorDeclNode.GetLastToken(includeZeroWidth: true)); return; } if (node is SwitchSectionSyntax switchSection) { if (switchSection.Labels.Count < 2) { AddSuppressWrappingIfOnSingleLineOperation(list, switchSection.GetFirstToken(includeZeroWidth: true), switchSection.GetLastToken(includeZeroWidth: true)); return; } else { // Add Separate suppression for each Label and for the last label, add the <> for (var i = 0; i < switchSection.Labels.Count - 1; ++i) { if (switchSection.Labels[i] != null) { AddSuppressWrappingIfOnSingleLineOperation(list, switchSection.Labels[i].GetFirstToken(includeZeroWidth: true), switchSection.Labels[i].GetLastToken(includeZeroWidth: true)); } } // For the last label add the rest of the statements of the switch if (switchSection.Labels[switchSection.Labels.Count - 1] != null) { AddSuppressWrappingIfOnSingleLineOperation(list, switchSection.Labels[switchSection.Labels.Count - 1].GetFirstToken(includeZeroWidth: true), switchSection.GetLastToken(includeZeroWidth: true)); } return; } } if (node is AnonymousFunctionExpressionSyntax or LocalFunctionStatementSyntax) { AddSuppressWrappingIfOnSingleLineOperation(list, node.GetFirstToken(includeZeroWidth: true), node.GetLastToken(includeZeroWidth: true), SuppressOption.IgnoreElasticWrapping); return; } if (node is ParameterSyntax parameterNode) { if (parameterNode.AttributeLists.Count != 0) { var anchorToken = parameterNode.AttributeLists.First().OpenBracketToken; AddSuppressAllOperationIfOnMultipleLine(list, anchorToken, parameterNode.GetLastToken()); } } if (node is TryStatementSyntax tryStatement) { // Add a suppression operation if the try keyword and the block are in the same line if (!tryStatement.TryKeyword.IsMissing && tryStatement.Block != null && !tryStatement.Block.CloseBraceToken.IsMissing) { AddSuppressWrappingIfOnSingleLineOperation(list, tryStatement.TryKeyword, tryStatement.Block.CloseBraceToken); } } if (node is CatchClauseSyntax catchClause) { // Add a suppression operation if the catch keyword and the corresponding block are in the same line if (!catchClause.CatchKeyword.IsMissing && catchClause.Block != null && !catchClause.Block.CloseBraceToken.IsMissing) { AddSuppressWrappingIfOnSingleLineOperation(list, catchClause.CatchKeyword, catchClause.Block.CloseBraceToken); } } if (node is FinallyClauseSyntax finallyClause) { // Add a suppression operation if the finally keyword and the corresponding block are in the same line if (!finallyClause.FinallyKeyword.IsMissing && finallyClause.Block != null && !finallyClause.Block.CloseBraceToken.IsMissing) { AddSuppressWrappingIfOnSingleLineOperation(list, finallyClause.FinallyKeyword, finallyClause.Block.CloseBraceToken); } } if (node is InterpolatedStringExpressionSyntax interpolatedStringExpression) { AddSuppressWrappingIfOnSingleLineOperation(list, interpolatedStringExpression.StringStartToken, interpolatedStringExpression.StringEndToken); } } private static void AddStatementExceptBlockSuppressOperations(List<SuppressOperation> list, SyntaxNode node) { if (node is not StatementSyntax statementNode || statementNode.Kind() == SyntaxKind.Block) { return; } var firstToken = statementNode.GetFirstToken(includeZeroWidth: true); var lastToken = statementNode.GetLastToken(includeZeroWidth: true); AddSuppressWrappingIfOnSingleLineOperation(list, firstToken, lastToken); } private static void AddFormatSuppressOperations(List<SuppressOperation> list, SyntaxNode node) { if (!node.ContainsDirectives) { return; } foreach (var child in node.ChildNodesAndTokens()) { if (!child.IsToken) { continue; } ProcessTriviaList(list, child.AsToken().LeadingTrivia); ProcessTriviaList(list, child.AsToken().TrailingTrivia); } return; // Local functions static void ProcessTriviaList(List<SuppressOperation> list, SyntaxTriviaList triviaList) { foreach (var trivia in triviaList) { ProcessTrivia(list, trivia); } } static void ProcessTrivia(List<SuppressOperation> list, SyntaxTrivia trivia) { if (!(trivia.HasStructure)) { return; } ProcessStructuredTrivia(list, trivia.GetStructure()!); } static void ProcessStructuredTrivia(List<SuppressOperation> list, SyntaxNode structure) { if (structure is not PragmaWarningDirectiveTriviaSyntax pragmaWarningDirectiveTrivia) { return; } if (!IsFormatDirective(pragmaWarningDirectiveTrivia, SyntaxKind.DisableKeyword)) { return; } var startToken = pragmaWarningDirectiveTrivia.GetLastToken(includeZeroWidth: true, includeDirectives: true); var endDirective = pragmaWarningDirectiveTrivia.GetNextDirective(trivia => IsFormatDirective(trivia, SyntaxKind.RestoreKeyword)); var endToken = endDirective is null ? ((CompilationUnitSyntax)structure.SyntaxTree.GetRoot(CancellationToken.None)).EndOfFileToken : endDirective.GetFirstToken(includeDirectives: true); Debug.Assert(!startToken.IsKind(SyntaxKind.None) && !endToken.IsKind(SyntaxKind.None)); var textSpan = TextSpan.FromBounds(startToken.Span.End, endToken.SpanStart); list.Add(new SuppressOperation(startToken, endToken, textSpan, SuppressOption.DisableFormatting)); } } private static bool IsFormatDirective(DirectiveTriviaSyntax? trivia, SyntaxKind disableOrRestoreKeyword) { if (trivia is not PragmaWarningDirectiveTriviaSyntax pragmaWarningDirectiveTrivia) { return false; } if (!pragmaWarningDirectiveTrivia.DisableOrRestoreKeyword.IsKind(disableOrRestoreKeyword)) { return false; } foreach (var errorCode in pragmaWarningDirectiveTrivia.ErrorCodes) { if (errorCode is not IdentifierNameSyntax identifierName) { continue; } if (identifierName.Identifier.ValueText.Equals(FormattingDiagnosticIds.FormatDocumentControlDiagnosticId) || identifierName.Identifier.ValueText.Equals(FormattingDiagnosticIds.FormattingDiagnosticId)) { return true; } } return false; } private static void AddInitializerSuppressOperations(List<SuppressOperation> list, SyntaxNode node) { // array or collection initializer case if (node.IsInitializerForArrayOrCollectionCreationExpression()) { var arrayOrCollectionInitializer = (InitializerExpressionSyntax)node; AddSuppressAllOperationIfOnMultipleLine(list, arrayOrCollectionInitializer.OpenBraceToken.GetPreviousToken(includeZeroWidth: true), arrayOrCollectionInitializer.CloseBraceToken); return; } var initializer = GetInitializerNode(node); if (initializer is { Parent: { } }) { AddInitializerSuppressOperations(list, initializer.Parent, initializer.Expressions); return; } if (node is AnonymousObjectCreationExpressionSyntax anonymousCreationNode) { AddInitializerSuppressOperations(list, anonymousCreationNode, anonymousCreationNode.Initializers); return; } } private static void AddInitializerSuppressOperations(List<SuppressOperation> list, SyntaxNode parent, IEnumerable<SyntaxNode> items) { // make creation node itself to not break into multiple line, if it is on same line AddSuppressWrappingIfOnSingleLineOperation(list, parent.GetFirstToken(includeZeroWidth: true), parent.GetLastToken(includeZeroWidth: true)); // make each initializer expression to not break into multiple line if it is on same line foreach (var item in items) { var firstToken = item.GetFirstToken(includeZeroWidth: true); var lastToken = item.GetLastToken(includeZeroWidth: true); if (!firstToken.Equals(lastToken)) { AddSuppressWrappingIfOnSingleLineOperation(list, firstToken, lastToken); } } } private static InitializerExpressionSyntax? GetInitializerNode(SyntaxNode node) => node switch { ObjectCreationExpressionSyntax objectCreationNode => objectCreationNode.Initializer, ArrayCreationExpressionSyntax arrayCreationNode => arrayCreationNode.Initializer, ImplicitArrayCreationExpressionSyntax implicitArrayNode => implicitArrayNode.Initializer, _ => null, }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal class SuppressFormattingRule : BaseFormattingRule { internal const string Name = "CSharp Suppress Formatting Rule"; public override void AddSuppressOperations(List<SuppressOperation> list, SyntaxNode node, in NextSuppressOperationAction nextOperation) { nextOperation.Invoke(); AddFormatSuppressOperations(list, node); AddInitializerSuppressOperations(list, node); AddBraceSuppressOperations(list, node); AddStatementExceptBlockSuppressOperations(list, node); AddSpecificNodesSuppressOperations(list, node); } private static void AddSpecificNodesSuppressOperations(List<SuppressOperation> list, SyntaxNode node) { if (node is IfStatementSyntax ifStatementNode) { AddSuppressWrappingIfOnSingleLineOperation(list, ifStatementNode.IfKeyword, ifStatementNode.Statement.GetLastToken(includeZeroWidth: true)); if (ifStatementNode.Else != null) { AddSuppressWrappingIfOnSingleLineOperation(list, ifStatementNode.Else.ElseKeyword, ifStatementNode.Else.Statement.GetLastToken(includeZeroWidth: true)); } return; } // ex: `e is Type ( /* positional */ )` if (node.IsKind(SyntaxKind.RecursivePattern, out RecursivePatternSyntax? recursivePattern)) { var positional = recursivePattern.PositionalPatternClause; var property = recursivePattern.PropertyPatternClause; if (positional != null) { var openParenToken = positional.OpenParenToken; var closeParenToken = positional.CloseParenToken; // Formatting should refrain from inserting new lines, unless the user already split across multiple lines AddSuppressWrappingIfOnSingleLineOperation(list, openParenToken, closeParenToken); if (property != null) { AddSuppressWrappingIfOnSingleLineOperation(list, openParenToken, property.GetLastToken()); } } // ex: `Property: <pattern>` inside a recursive pattern, such as `e is { Property: <pattern>, ... }` else if (property != null) { var openBraceToken = property.OpenBraceToken; var closeBraceToken = property.CloseBraceToken; // Formatting should refrain from inserting new lines, unless the user already split across multiple lines AddSuppressWrappingIfOnSingleLineOperation(list, openBraceToken, closeBraceToken); } return; } // ex: `<pattern>: expression` inside a switch expression, such as `e switch { <pattern>: expression, ... }` if (node.IsKind(SyntaxKind.SwitchExpressionArm)) { // Formatting should refrain from inserting new lines, unless the user already split across multiple lines AddSuppressWrappingIfOnSingleLineOperation(list, node.GetFirstToken(), node.GetLastToken()); return; } // ex: `e switch { <pattern>: expression, ... }` if (node.IsKind(SyntaxKind.SwitchExpression)) { // Formatting should refrain from inserting new lines, unless the user already split across multiple lines AddSuppressWrappingIfOnSingleLineOperation(list, node.GetFirstToken(), node.GetLastToken()); return; } // ex: `case <pattern>:` inside a switch statement if (node is CasePatternSwitchLabelSyntax casePattern) { // Formatting should refrain from inserting new lines, unless the user already split across multiple lines AddSuppressWrappingIfOnSingleLineOperation(list, casePattern.GetFirstToken(), casePattern.GetLastToken()); return; } // ex: `expression is <pattern>` if (node is IsPatternExpressionSyntax isPattern) { // Formatting should refrain from inserting new lines, unless the user already split across multiple lines AddSuppressWrappingIfOnSingleLineOperation(list, isPattern.GetFirstToken(), isPattern.GetLastToken()); if (isPattern.Pattern.IsKind(SyntaxKind.RecursivePattern, out recursivePattern)) { // ex: // ``` // _ = expr is (1, 2) { }$$ // M(); // ``` // or: // ``` // _ = expr is { }$$ // M(); // ``` var propertyPatternClause = recursivePattern.PropertyPatternClause; if (propertyPatternClause != null) { AddSuppressWrappingIfOnSingleLineOperation(list, isPattern.IsKeyword, propertyPatternClause.GetLastToken()); } } return; } if (node is ConstructorInitializerSyntax constructorInitializerNode) { var constructorDeclarationNode = constructorInitializerNode.Parent as ConstructorDeclarationSyntax; if (constructorDeclarationNode?.Body != null) { AddSuppressWrappingIfOnSingleLineOperation(list, constructorInitializerNode.ColonToken, constructorDeclarationNode.Body.CloseBraceToken); } return; } if (node is DoStatementSyntax whileStatementNode) { AddSuppressWrappingIfOnSingleLineOperation(list, whileStatementNode.GetFirstToken(includeZeroWidth: true), whileStatementNode.Statement.GetLastToken(includeZeroWidth: true)); return; } if (node is MemberDeclarationSyntax memberDeclNode) { // Attempt to keep the part of a member that follows the attributes on a single // line if that's how it's currently written. var (firstToken, lastToken) = memberDeclNode.GetFirstAndLastMemberDeclarationTokensAfterAttributes(); AddSuppressWrappingIfOnSingleLineOperation(list, firstToken, lastToken); // Also, If the member is on single line with its attributes on it, then keep // it on a single line. This is for code like the following: // // [Import] public int Field1; // [Import] public int Field2; var attributes = memberDeclNode.GetAttributes(); var endToken = node.GetLastToken(includeZeroWidth: true); for (var i = 0; i < attributes.Count; ++i) { AddSuppressWrappingIfOnSingleLineOperation(list, attributes[i].GetFirstToken(includeZeroWidth: true), endToken); } var propertyDeclNode = node as PropertyDeclarationSyntax; if (propertyDeclNode?.Initializer != null && propertyDeclNode?.AccessorList != null) { AddSuppressWrappingIfOnSingleLineOperation(list, firstToken, propertyDeclNode.AccessorList.GetLastToken()); } return; } if (node is AccessorDeclarationSyntax accessorDeclNode) { AddSuppressWrappingIfOnSingleLineOperation(list, accessorDeclNode.Keyword, accessorDeclNode.GetLastToken(includeZeroWidth: true)); return; } if (node is SwitchSectionSyntax switchSection) { if (switchSection.Labels.Count < 2) { AddSuppressWrappingIfOnSingleLineOperation(list, switchSection.GetFirstToken(includeZeroWidth: true), switchSection.GetLastToken(includeZeroWidth: true)); return; } else { // Add Separate suppression for each Label and for the last label, add the <> for (var i = 0; i < switchSection.Labels.Count - 1; ++i) { if (switchSection.Labels[i] != null) { AddSuppressWrappingIfOnSingleLineOperation(list, switchSection.Labels[i].GetFirstToken(includeZeroWidth: true), switchSection.Labels[i].GetLastToken(includeZeroWidth: true)); } } // For the last label add the rest of the statements of the switch if (switchSection.Labels[switchSection.Labels.Count - 1] != null) { AddSuppressWrappingIfOnSingleLineOperation(list, switchSection.Labels[switchSection.Labels.Count - 1].GetFirstToken(includeZeroWidth: true), switchSection.GetLastToken(includeZeroWidth: true)); } return; } } if (node is AnonymousFunctionExpressionSyntax or LocalFunctionStatementSyntax) { AddSuppressWrappingIfOnSingleLineOperation(list, node.GetFirstToken(includeZeroWidth: true), node.GetLastToken(includeZeroWidth: true), SuppressOption.IgnoreElasticWrapping); return; } if (node is ParameterSyntax parameterNode) { if (parameterNode.AttributeLists.Count != 0) { var anchorToken = parameterNode.AttributeLists.First().OpenBracketToken; AddSuppressAllOperationIfOnMultipleLine(list, anchorToken, parameterNode.GetLastToken()); } } if (node is TryStatementSyntax tryStatement) { // Add a suppression operation if the try keyword and the block are in the same line if (!tryStatement.TryKeyword.IsMissing && tryStatement.Block != null && !tryStatement.Block.CloseBraceToken.IsMissing) { AddSuppressWrappingIfOnSingleLineOperation(list, tryStatement.TryKeyword, tryStatement.Block.CloseBraceToken); } } if (node is CatchClauseSyntax catchClause) { // Add a suppression operation if the catch keyword and the corresponding block are in the same line if (!catchClause.CatchKeyword.IsMissing && catchClause.Block != null && !catchClause.Block.CloseBraceToken.IsMissing) { AddSuppressWrappingIfOnSingleLineOperation(list, catchClause.CatchKeyword, catchClause.Block.CloseBraceToken); } } if (node is FinallyClauseSyntax finallyClause) { // Add a suppression operation if the finally keyword and the corresponding block are in the same line if (!finallyClause.FinallyKeyword.IsMissing && finallyClause.Block != null && !finallyClause.Block.CloseBraceToken.IsMissing) { AddSuppressWrappingIfOnSingleLineOperation(list, finallyClause.FinallyKeyword, finallyClause.Block.CloseBraceToken); } } if (node is InterpolatedStringExpressionSyntax interpolatedStringExpression) { AddSuppressWrappingIfOnSingleLineOperation(list, interpolatedStringExpression.StringStartToken, interpolatedStringExpression.StringEndToken); } } private static void AddStatementExceptBlockSuppressOperations(List<SuppressOperation> list, SyntaxNode node) { if (node is not StatementSyntax statementNode || statementNode.Kind() == SyntaxKind.Block) { return; } var firstToken = statementNode.GetFirstToken(includeZeroWidth: true); var lastToken = statementNode.GetLastToken(includeZeroWidth: true); AddSuppressWrappingIfOnSingleLineOperation(list, firstToken, lastToken); } private static void AddFormatSuppressOperations(List<SuppressOperation> list, SyntaxNode node) { if (!node.ContainsDirectives) { return; } foreach (var child in node.ChildNodesAndTokens()) { if (!child.IsToken) { continue; } ProcessTriviaList(list, child.AsToken().LeadingTrivia); ProcessTriviaList(list, child.AsToken().TrailingTrivia); } return; // Local functions static void ProcessTriviaList(List<SuppressOperation> list, SyntaxTriviaList triviaList) { foreach (var trivia in triviaList) { ProcessTrivia(list, trivia); } } static void ProcessTrivia(List<SuppressOperation> list, SyntaxTrivia trivia) { if (!(trivia.HasStructure)) { return; } ProcessStructuredTrivia(list, trivia.GetStructure()!); } static void ProcessStructuredTrivia(List<SuppressOperation> list, SyntaxNode structure) { if (structure is not PragmaWarningDirectiveTriviaSyntax pragmaWarningDirectiveTrivia) { return; } if (!IsFormatDirective(pragmaWarningDirectiveTrivia, SyntaxKind.DisableKeyword)) { return; } var startToken = pragmaWarningDirectiveTrivia.GetLastToken(includeZeroWidth: true, includeDirectives: true); var endDirective = pragmaWarningDirectiveTrivia.GetNextDirective(trivia => IsFormatDirective(trivia, SyntaxKind.RestoreKeyword)); var endToken = endDirective is null ? ((CompilationUnitSyntax)structure.SyntaxTree.GetRoot(CancellationToken.None)).EndOfFileToken : endDirective.GetFirstToken(includeDirectives: true); Debug.Assert(!startToken.IsKind(SyntaxKind.None) && !endToken.IsKind(SyntaxKind.None)); var textSpan = TextSpan.FromBounds(startToken.Span.End, endToken.SpanStart); list.Add(new SuppressOperation(startToken, endToken, textSpan, SuppressOption.DisableFormatting)); } } private static bool IsFormatDirective(DirectiveTriviaSyntax? trivia, SyntaxKind disableOrRestoreKeyword) { if (trivia is not PragmaWarningDirectiveTriviaSyntax pragmaWarningDirectiveTrivia) { return false; } if (!pragmaWarningDirectiveTrivia.DisableOrRestoreKeyword.IsKind(disableOrRestoreKeyword)) { return false; } foreach (var errorCode in pragmaWarningDirectiveTrivia.ErrorCodes) { if (errorCode is not IdentifierNameSyntax identifierName) { continue; } if (identifierName.Identifier.ValueText.Equals(FormattingDiagnosticIds.FormatDocumentControlDiagnosticId) || identifierName.Identifier.ValueText.Equals(FormattingDiagnosticIds.FormattingDiagnosticId)) { return true; } } return false; } private static void AddInitializerSuppressOperations(List<SuppressOperation> list, SyntaxNode node) { // array or collection initializer case if (node.IsInitializerForArrayOrCollectionCreationExpression()) { var arrayOrCollectionInitializer = (InitializerExpressionSyntax)node; AddSuppressAllOperationIfOnMultipleLine(list, arrayOrCollectionInitializer.OpenBraceToken.GetPreviousToken(includeZeroWidth: true), arrayOrCollectionInitializer.CloseBraceToken); return; } var initializer = GetInitializerNode(node); if (initializer is { Parent: { } }) { AddInitializerSuppressOperations(list, initializer.Parent, initializer.Expressions); return; } if (node is AnonymousObjectCreationExpressionSyntax anonymousCreationNode) { AddInitializerSuppressOperations(list, anonymousCreationNode, anonymousCreationNode.Initializers); return; } } private static void AddInitializerSuppressOperations(List<SuppressOperation> list, SyntaxNode parent, IEnumerable<SyntaxNode> items) { // make creation node itself to not break into multiple line, if it is on same line AddSuppressWrappingIfOnSingleLineOperation(list, parent.GetFirstToken(includeZeroWidth: true), parent.GetLastToken(includeZeroWidth: true)); // make each initializer expression to not break into multiple line if it is on same line foreach (var item in items) { var firstToken = item.GetFirstToken(includeZeroWidth: true); var lastToken = item.GetLastToken(includeZeroWidth: true); if (!firstToken.Equals(lastToken)) { AddSuppressWrappingIfOnSingleLineOperation(list, firstToken, lastToken); } } } private static InitializerExpressionSyntax? GetInitializerNode(SyntaxNode node) => node switch { ObjectCreationExpressionSyntax objectCreationNode => objectCreationNode.Initializer, ArrayCreationExpressionSyntax arrayCreationNode => arrayCreationNode.Initializer, ImplicitArrayCreationExpressionSyntax implicitArrayNode => implicitArrayNode.Initializer, _ => null, }; } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Features/Core/Portable/CodeFixes/Iterator/AbstractIteratorCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeFixes.Iterator { internal abstract class AbstractIteratorCodeFixProvider : CodeFixProvider { public override FixAllProvider GetFixAllProvider() { // Fix All is not supported by this code fix return null; } protected abstract Task<CodeAction> GetCodeFixAsync(SyntaxNode root, SyntaxNode node, Document document, Diagnostic diagnostics, CancellationToken cancellationToken); public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); if (!TryGetNode(root, context.Span, out var node)) { return; } var diagnostic = context.Diagnostics.FirstOrDefault(); var codeAction = await GetCodeFixAsync(root, node, context.Document, diagnostic, context.CancellationToken).ConfigureAwait(false); if (codeAction != null) { context.RegisterCodeFix(codeAction, diagnostic); } } protected virtual bool TryGetNode(SyntaxNode root, TextSpan span, out SyntaxNode node) { node = null; var ancestors = root.FindToken(span.Start).GetAncestors<SyntaxNode>(); if (!ancestors.Any()) { return false; } node = ancestors.FirstOrDefault(n => n.Span.Contains(span) && n != root); return node != null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeFixes.Iterator { internal abstract class AbstractIteratorCodeFixProvider : CodeFixProvider { public override FixAllProvider GetFixAllProvider() { // Fix All is not supported by this code fix return null; } protected abstract Task<CodeAction> GetCodeFixAsync(SyntaxNode root, SyntaxNode node, Document document, Diagnostic diagnostics, CancellationToken cancellationToken); public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); if (!TryGetNode(root, context.Span, out var node)) { return; } var diagnostic = context.Diagnostics.FirstOrDefault(); var codeAction = await GetCodeFixAsync(root, node, context.Document, diagnostic, context.CancellationToken).ConfigureAwait(false); if (codeAction != null) { context.RegisterCodeFix(codeAction, diagnostic); } } protected virtual bool TryGetNode(SyntaxNode root, TextSpan span, out SyntaxNode node) { node = null; var ancestors = root.FindToken(span.Start).GetAncestors<SyntaxNode>(); if (!ancestors.Any()) { return false; } node = ancestors.FirstOrDefault(n => n.Span.Contains(span) && n != root); return node != null; } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/CSharp/Test/Syntax/Parsing/ValueTupleTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Xunit; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing { public class ValueTupleTests : ParsingTests { public ValueTupleTests(ITestOutputHelper output) : base(output) { } protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { return SyntaxFactory.ParseSyntaxTree(text, options: options); } [Fact] public void SimpleTuple() { var tree = UsingTree(@" class C { (int, string) Goo() { return (1, ""Alice""); } }", options: TestOptions.Regular); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ReturnStatement); { N(SyntaxKind.ReturnKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.StringLiteralExpression); { N(SyntaxKind.StringLiteralToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void LongTuple() { var tree = UsingTree(@" class C { (int, int, int, string, string, string, int, int, int) Goo() { } }", options: TestOptions.Regular); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TuplesInLambda() { var tree = UsingTree(@" class C { var x = ((string, string) a, (int, int) b) => { }; }", options: TestOptions.Regular); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TuplesWithNamesInLambda() { var tree = UsingTree(@" class C { var x = ((string a, string) a, (int, int b) b) => { }; }", options: TestOptions.Regular); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TupleInParameters() { var tree = UsingTree(@" class C { void Goo((int, string) a) { } }", options: TestOptions.Regular); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TupleTypeWithTooFewElements() { var tree = UsingTree(@" class C { void M(int x, () y, (int a) z) { } }", options: TestOptions.Regular); tree.GetDiagnostics().Verify( // (4,20): error CS8124: Tuple must contain at least two elements. // void M(int x, () y, (int a) z) { } Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(4, 20), // (4,31): error CS8124: Tuple must contain at least two elements. // void M(int x, () y, (int a) z) { } Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(4, 31) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.TupleElement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.CommaToken); M(SyntaxKind.TupleElement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } M(SyntaxKind.CommaToken); M(SyntaxKind.TupleElement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken, "z"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TupleExpressionWithTooFewElements() { var tree = UsingTree(@" class C { object x = ((Alice: 1), ()); }", options: TestOptions.Regular); tree.GetDiagnostics().Verify( // (4,26): error CS8124: Tuple must contain at least two elements. // object x = ((Alice: 1), ()); Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(4, 26), // (4,30): error CS1525: Invalid expression term ')' // object x = ((Alice: 1), ()); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(4, 30) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Alice"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } M(SyntaxKind.CommaToken); M(SyntaxKind.Argument); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(13667, "https://github.com/dotnet/roslyn/issues/13667")] public void MissingShortTupleErrorWhenWarningPresent() { // Diff errors var test = @" class Program { object a = (x: 3l); } "; ParseAndValidate(test, // (4,21): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // object a = (x: 3l); Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(4, 21), // (4,22): error CS8124: Tuple must contain at least two elements. // object a = (x: 3l); Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(4, 22) ); } [Fact, WorkItem(377111, "https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems?id=377111")] public void TernaryVersusDeclaration_01() { UsingStatement("return (i, isValid ? Errors.IsValid : Errors.HasErrors);"); N(SyntaxKind.ReturnStatement); { N(SyntaxKind.ReturnKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "i"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "isValid"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Errors"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "IsValid"); } } N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Errors"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "HasErrors"); } } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(377111, "https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems?id=377111")] public void TernaryVersusDeclaration_02() { UsingStatement("return (isValid ? Errors.IsValid : Errors.HasErrors, i);"); N(SyntaxKind.ReturnStatement); { N(SyntaxKind.ReturnKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "isValid"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Errors"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "IsValid"); } } N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Errors"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "HasErrors"); } } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "i"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(377111, "https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems?id=377111")] public void TernaryVersusDeclaration_03() { UsingStatement("return (i, a < b, c > d);"); N(SyntaxKind.ReturnStatement); { N(SyntaxKind.ReturnKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "i"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "d"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(377111, "https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems?id=377111")] public void TernaryVersusDeclaration_04() { UsingStatement("return (i, a < b, c > d.x);"); N(SyntaxKind.ReturnStatement); { N(SyntaxKind.ReturnKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "i"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.GreaterThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.GreaterThanToken); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(377111, "https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems?id=377111")] public void TernaryVersusDeclaration_05() { UsingStatement("return (i, a < b, c > d && x);"); N(SyntaxKind.ReturnStatement); { N(SyntaxKind.ReturnKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "i"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.GreaterThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.GreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } EOF(); } } }
// Licensed to the .NET Foundation under one or more 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 Xunit; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing { public class ValueTupleTests : ParsingTests { public ValueTupleTests(ITestOutputHelper output) : base(output) { } protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { return SyntaxFactory.ParseSyntaxTree(text, options: options); } [Fact] public void SimpleTuple() { var tree = UsingTree(@" class C { (int, string) Goo() { return (1, ""Alice""); } }", options: TestOptions.Regular); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ReturnStatement); { N(SyntaxKind.ReturnKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.StringLiteralExpression); { N(SyntaxKind.StringLiteralToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void LongTuple() { var tree = UsingTree(@" class C { (int, int, int, string, string, string, int, int, int) Goo() { } }", options: TestOptions.Regular); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TuplesInLambda() { var tree = UsingTree(@" class C { var x = ((string, string) a, (int, int) b) => { }; }", options: TestOptions.Regular); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TuplesWithNamesInLambda() { var tree = UsingTree(@" class C { var x = ((string a, string) a, (int, int b) b) => { }; }", options: TestOptions.Regular); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TupleInParameters() { var tree = UsingTree(@" class C { void Goo((int, string) a) { } }", options: TestOptions.Regular); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TupleTypeWithTooFewElements() { var tree = UsingTree(@" class C { void M(int x, () y, (int a) z) { } }", options: TestOptions.Regular); tree.GetDiagnostics().Verify( // (4,20): error CS8124: Tuple must contain at least two elements. // void M(int x, () y, (int a) z) { } Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(4, 20), // (4,31): error CS8124: Tuple must contain at least two elements. // void M(int x, () y, (int a) z) { } Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(4, 31) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.TupleElement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.CommaToken); M(SyntaxKind.TupleElement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } M(SyntaxKind.CommaToken); M(SyntaxKind.TupleElement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken, "z"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TupleExpressionWithTooFewElements() { var tree = UsingTree(@" class C { object x = ((Alice: 1), ()); }", options: TestOptions.Regular); tree.GetDiagnostics().Verify( // (4,26): error CS8124: Tuple must contain at least two elements. // object x = ((Alice: 1), ()); Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(4, 26), // (4,30): error CS1525: Invalid expression term ')' // object x = ((Alice: 1), ()); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(4, 30) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Alice"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } M(SyntaxKind.CommaToken); M(SyntaxKind.Argument); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(13667, "https://github.com/dotnet/roslyn/issues/13667")] public void MissingShortTupleErrorWhenWarningPresent() { // Diff errors var test = @" class Program { object a = (x: 3l); } "; ParseAndValidate(test, // (4,21): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // object a = (x: 3l); Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(4, 21), // (4,22): error CS8124: Tuple must contain at least two elements. // object a = (x: 3l); Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(4, 22) ); } [Fact, WorkItem(377111, "https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems?id=377111")] public void TernaryVersusDeclaration_01() { UsingStatement("return (i, isValid ? Errors.IsValid : Errors.HasErrors);"); N(SyntaxKind.ReturnStatement); { N(SyntaxKind.ReturnKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "i"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "isValid"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Errors"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "IsValid"); } } N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Errors"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "HasErrors"); } } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(377111, "https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems?id=377111")] public void TernaryVersusDeclaration_02() { UsingStatement("return (isValid ? Errors.IsValid : Errors.HasErrors, i);"); N(SyntaxKind.ReturnStatement); { N(SyntaxKind.ReturnKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "isValid"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Errors"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "IsValid"); } } N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Errors"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "HasErrors"); } } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "i"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(377111, "https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems?id=377111")] public void TernaryVersusDeclaration_03() { UsingStatement("return (i, a < b, c > d);"); N(SyntaxKind.ReturnStatement); { N(SyntaxKind.ReturnKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "i"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "d"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(377111, "https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems?id=377111")] public void TernaryVersusDeclaration_04() { UsingStatement("return (i, a < b, c > d.x);"); N(SyntaxKind.ReturnStatement); { N(SyntaxKind.ReturnKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "i"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.GreaterThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.GreaterThanToken); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(377111, "https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems?id=377111")] public void TernaryVersusDeclaration_05() { UsingStatement("return (i, a < b, c > d && x);"); N(SyntaxKind.ReturnStatement); { N(SyntaxKind.ReturnKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "i"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.GreaterThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.GreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } EOF(); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Features/CSharp/Portable/InitializeParameter/InitializeParameterHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Operations; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.InitializeParameter { internal static class InitializeParameterHelpers { public static bool IsFunctionDeclaration(SyntaxNode node) => node is BaseMethodDeclarationSyntax || node is LocalFunctionStatementSyntax || node is AnonymousFunctionExpressionSyntax; public static SyntaxNode GetBody(SyntaxNode functionDeclaration) { switch (functionDeclaration) { case BaseMethodDeclarationSyntax methodDeclaration: return (SyntaxNode)methodDeclaration.Body ?? methodDeclaration.ExpressionBody; case LocalFunctionStatementSyntax localFunction: return (SyntaxNode)localFunction.Body ?? localFunction.ExpressionBody; case AnonymousFunctionExpressionSyntax anonymousFunction: return anonymousFunction.Body; default: throw ExceptionUtilities.UnexpectedValue(functionDeclaration); } } private static SyntaxToken? TryGetSemicolonToken(SyntaxNode functionDeclaration) { switch (functionDeclaration) { case BaseMethodDeclarationSyntax methodDeclaration: return methodDeclaration.SemicolonToken; case LocalFunctionStatementSyntax localFunction: return localFunction.SemicolonToken; case AnonymousFunctionExpressionSyntax _: return null; default: throw ExceptionUtilities.UnexpectedValue(functionDeclaration); } } public static bool IsImplicitConversion(Compilation compilation, ITypeSymbol source, ITypeSymbol destination) => compilation.ClassifyConversion(source: source, destination: destination).IsImplicit; public static SyntaxNode TryGetLastStatement(IBlockOperation blockStatementOpt) => blockStatementOpt?.Syntax is BlockSyntax block ? block.Statements.LastOrDefault() : blockStatementOpt?.Syntax; public static void InsertStatement( SyntaxEditor editor, SyntaxNode functionDeclaration, bool returnsVoid, SyntaxNode statementToAddAfterOpt, StatementSyntax statement) { var body = GetBody(functionDeclaration); if (IsExpressionBody(body)) { var semicolonToken = TryGetSemicolonToken(functionDeclaration) ?? SyntaxFactory.Token(SyntaxKind.SemicolonToken); if (!TryConvertExpressionBodyToStatement(body, semicolonToken, !returnsVoid, out var convertedStatement)) { return; } // Add the new statement as the first/last statement of the new block // depending if we were asked to go after something or not. editor.SetStatements(functionDeclaration, statementToAddAfterOpt == null ? ImmutableArray.Create(statement, convertedStatement) : ImmutableArray.Create(convertedStatement, statement)); } else if (body is BlockSyntax block) { // Look for the statement we were asked to go after. var indexToAddAfter = block.Statements.IndexOf(s => s == statementToAddAfterOpt); if (indexToAddAfter >= 0) { // If we find it, then insert the new statement after it. editor.InsertAfter(block.Statements[indexToAddAfter], statement); } else if (block.Statements.Count > 0) { // Otherwise, if we have multiple statements already, then insert ourselves // before the first one. editor.InsertBefore(block.Statements[0], statement); } else { // Otherwise, we have no statements in this block. Add the new statement // as the single statement the block will have. Debug.Assert(block.Statements.Count == 0); editor.ReplaceNode(block, (currentBlock, _) => ((BlockSyntax)currentBlock).AddStatements(statement)); } // If the block was on a single line before, the format it so that the formatting // engine will update it to go over multiple lines. Otherwise, we can end up in // the strange state where the { and } tokens stay where they were originally, // which will look very strange like: // // a => { // if (...) { // } }; if (CSharpSyntaxFacts.Instance.IsOnSingleLine(block, fullSpan: false)) { editor.ReplaceNode( block, (currentBlock, _) => currentBlock.WithAdditionalAnnotations(Formatter.Annotation)); } } else { editor.SetStatements(functionDeclaration, ImmutableArray.Create(statement)); } } // either from an expression lambda or expression bodied member public static bool IsExpressionBody(SyntaxNode body) => body is ExpressionSyntax || body is ArrowExpressionClauseSyntax; public static bool TryConvertExpressionBodyToStatement(SyntaxNode body, SyntaxToken semicolonToken, bool createReturnStatementForExpression, out StatementSyntax statement) { Debug.Assert(IsExpressionBody(body)); switch (body) { case ArrowExpressionClauseSyntax arrowClause: // If this is a => method, then we'll have to convert the method to have a block body. return arrowClause.TryConvertToStatement(semicolonToken, createReturnStatementForExpression, out statement); case ExpressionSyntax expression: // must be an expression lambda return expression.TryConvertToStatement(semicolonToken, createReturnStatementForExpression, out statement); default: throw ExceptionUtilities.UnexpectedValue(body); } } } }
// Licensed to the .NET Foundation under one or more 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 System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.InitializeParameter { internal static class InitializeParameterHelpers { public static bool IsFunctionDeclaration(SyntaxNode node) => node is BaseMethodDeclarationSyntax || node is LocalFunctionStatementSyntax || node is AnonymousFunctionExpressionSyntax; public static SyntaxNode GetBody(SyntaxNode functionDeclaration) => functionDeclaration switch { BaseMethodDeclarationSyntax methodDeclaration => (SyntaxNode?)methodDeclaration.Body ?? methodDeclaration.ExpressionBody!, LocalFunctionStatementSyntax localFunction => (SyntaxNode?)localFunction.Body ?? localFunction.ExpressionBody!, AnonymousFunctionExpressionSyntax anonymousFunction => anonymousFunction.Body, _ => throw ExceptionUtilities.UnexpectedValue(functionDeclaration), }; private static SyntaxToken? TryGetSemicolonToken(SyntaxNode functionDeclaration) => functionDeclaration switch { BaseMethodDeclarationSyntax methodDeclaration => methodDeclaration.SemicolonToken, LocalFunctionStatementSyntax localFunction => localFunction.SemicolonToken, AnonymousFunctionExpressionSyntax _ => null, _ => throw ExceptionUtilities.UnexpectedValue(functionDeclaration), }; public static bool IsImplicitConversion(Compilation compilation, ITypeSymbol source, ITypeSymbol destination) => compilation.ClassifyConversion(source: source, destination: destination).IsImplicit; public static SyntaxNode? TryGetLastStatement(IBlockOperation blockStatementOpt) => blockStatementOpt?.Syntax is BlockSyntax block ? block.Statements.LastOrDefault() : blockStatementOpt?.Syntax; public static void InsertStatement( SyntaxEditor editor, SyntaxNode functionDeclaration, bool returnsVoid, SyntaxNode statementToAddAfterOpt, StatementSyntax statement) { var body = GetBody(functionDeclaration); if (IsExpressionBody(body)) { var semicolonToken = TryGetSemicolonToken(functionDeclaration) ?? SyntaxFactory.Token(SyntaxKind.SemicolonToken); if (!TryConvertExpressionBodyToStatement(body, semicolonToken, !returnsVoid, out var convertedStatement)) { return; } // Add the new statement as the first/last statement of the new block // depending if we were asked to go after something or not. editor.SetStatements(functionDeclaration, statementToAddAfterOpt == null ? ImmutableArray.Create(statement, convertedStatement) : ImmutableArray.Create(convertedStatement, statement)); } else if (body is BlockSyntax block) { // Look for the statement we were asked to go after. var indexToAddAfter = block.Statements.IndexOf(s => s == statementToAddAfterOpt); if (indexToAddAfter >= 0) { // If we find it, then insert the new statement after it. editor.InsertAfter(block.Statements[indexToAddAfter], statement); } else if (block.Statements.Count > 0) { // Otherwise, if we have multiple statements already, then insert ourselves // before the first one. editor.InsertBefore(block.Statements[0], statement); } else { // Otherwise, we have no statements in this block. Add the new statement // as the single statement the block will have. Debug.Assert(block.Statements.Count == 0); editor.ReplaceNode(block, (currentBlock, _) => ((BlockSyntax)currentBlock).AddStatements(statement)); } // If the block was on a single line before, the format it so that the formatting // engine will update it to go over multiple lines. Otherwise, we can end up in // the strange state where the { and } tokens stay where they were originally, // which will look very strange like: // // a => { // if (...) { // } }; if (CSharpSyntaxFacts.Instance.IsOnSingleLine(block, fullSpan: false)) { editor.ReplaceNode( block, (currentBlock, _) => currentBlock.WithAdditionalAnnotations(Formatter.Annotation)); } } else { editor.SetStatements(functionDeclaration, ImmutableArray.Create(statement)); } } // either from an expression lambda or expression bodied member public static bool IsExpressionBody(SyntaxNode body) => body is ExpressionSyntax or ArrowExpressionClauseSyntax; public static bool TryConvertExpressionBodyToStatement( SyntaxNode body, SyntaxToken semicolonToken, bool createReturnStatementForExpression, [NotNullWhen(true)] out StatementSyntax? statement) { Debug.Assert(IsExpressionBody(body)); return body switch { // If this is a => method, then we'll have to convert the method to have a block body. ArrowExpressionClauseSyntax arrowClause => arrowClause.TryConvertToStatement(semicolonToken, createReturnStatementForExpression, out statement), // must be an expression lambda ExpressionSyntax expression => expression.TryConvertToStatement(semicolonToken, createReturnStatementForExpression, out statement), _ => throw ExceptionUtilities.UnexpectedValue(body), }; } } }
1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Features/Core/Portable/AddImport/SymbolReferenceFinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolSearch; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Shared.Utilities.EditorBrowsableHelpers; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax> { private partial class SymbolReferenceFinder { private const string AttributeSuffix = nameof(Attribute); private readonly string _diagnosticId; private readonly Document _document; private readonly SemanticModel _semanticModel; private readonly ISet<INamespaceSymbol> _namespacesInScope; private readonly ISyntaxFactsService _syntaxFacts; private readonly AbstractAddImportFeatureService<TSimpleNameSyntax> _owner; private readonly SyntaxNode _node; private readonly ISymbolSearchService _symbolSearchService; private readonly bool _searchReferenceAssemblies; private readonly ImmutableArray<PackageSource> _packageSources; public SymbolReferenceFinder( AbstractAddImportFeatureService<TSimpleNameSyntax> owner, Document document, SemanticModel semanticModel, string diagnosticId, SyntaxNode node, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { _owner = owner; _document = document; _semanticModel = semanticModel; _diagnosticId = diagnosticId; _node = node; _symbolSearchService = symbolSearchService; _searchReferenceAssemblies = searchReferenceAssemblies; _packageSources = packageSources; if (_searchReferenceAssemblies || packageSources.Length > 0) { Contract.ThrowIfNull(symbolSearchService); } _syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); _namespacesInScope = GetNamespacesInScope(cancellationToken); } private ISet<INamespaceSymbol> GetNamespacesInScope(CancellationToken cancellationToken) { // Add all the namespaces brought in by imports/usings. var set = _owner.GetImportNamespacesInScope(_semanticModel, _node, cancellationToken); // Also add all the namespaces we're contained in. We don't want // to add imports for these namespaces either. for (var containingNamespace = _semanticModel.GetEnclosingNamespace(_node.SpanStart, cancellationToken); containingNamespace != null; containingNamespace = containingNamespace.ContainingNamespace) { set.Add(MapToCompilationNamespaceIfPossible(containingNamespace)); } return set; } private INamespaceSymbol MapToCompilationNamespaceIfPossible(INamespaceSymbol containingNamespace) => _semanticModel.Compilation.GetCompilationNamespace(containingNamespace) ?? containingNamespace; internal Task<ImmutableArray<SymbolReference>> FindInAllSymbolsInStartingProjectAsync( bool exact, CancellationToken cancellationToken) { var searchScope = new AllSymbolsProjectSearchScope( _owner, _document.Project, exact, cancellationToken); return DoAsync(searchScope); } internal Task<ImmutableArray<SymbolReference>> FindInSourceSymbolsInProjectAsync( ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>> projectToAssembly, Project project, bool exact, CancellationToken cancellationToken) { var searchScope = new SourceSymbolsProjectSearchScope( _owner, projectToAssembly, project, exact, cancellationToken); return DoAsync(searchScope); } internal Task<ImmutableArray<SymbolReference>> FindInMetadataSymbolsAsync( IAssemblySymbol assembly, ProjectId assemblyProjectId, PortableExecutableReference metadataReference, bool exact, CancellationToken cancellationToken) { var searchScope = new MetadataSymbolsSearchScope( _owner, _document.Project.Solution, assembly, assemblyProjectId, metadataReference, exact, cancellationToken); return DoAsync(searchScope); } private async Task<ImmutableArray<SymbolReference>> DoAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); // Spin off tasks to do all our searching in parallel using var _1 = ArrayBuilder<Task<ImmutableArray<SymbolReference>>>.GetInstance(out var tasks); tasks.Add(GetReferencesForMatchingTypesAsync(searchScope)); tasks.Add(GetReferencesForMatchingNamespacesAsync(searchScope)); tasks.Add(GetReferencesForMatchingFieldsAndPropertiesAsync(searchScope)); tasks.Add(GetReferencesForMatchingExtensionMethodsAsync(searchScope)); // Searching for things like "Add" (for collection initializers) and "Select" // (for extension methods) should only be done when doing an 'exact' search. // We should not do fuzzy searches for these names. In this case it's not // like the user was writing Add or Select, but instead we're looking for // viable symbols with those names to make a collection initializer or // query expression valid. if (searchScope.Exact) { tasks.Add(GetReferencesForCollectionInitializerMethodsAsync(searchScope)); tasks.Add(GetReferencesForQueryPatternsAsync(searchScope)); tasks.Add(GetReferencesForDeconstructAsync(searchScope)); tasks.Add(GetReferencesForGetAwaiterAsync(searchScope)); tasks.Add(GetReferencesForGetEnumeratorAsync(searchScope)); tasks.Add(GetReferencesForGetAsyncEnumeratorAsync(searchScope)); } await Task.WhenAll(tasks).ConfigureAwait(false); searchScope.CancellationToken.ThrowIfCancellationRequested(); using var _2 = ArrayBuilder<SymbolReference>.GetInstance(out var allReferences); foreach (var task in tasks) { var taskResult = await task.ConfigureAwait(false); allReferences.AddRange(taskResult); } return DeDupeAndSortReferences(allReferences.ToImmutable()); } private ImmutableArray<SymbolReference> DeDupeAndSortReferences(ImmutableArray<SymbolReference> allReferences) { return allReferences .Distinct() .Where(NotNull) .Where(NotGlobalNamespace) .OrderBy((r1, r2) => r1.CompareTo(_document, r2)) .ToImmutableArray(); } private static void CalculateContext( TSimpleNameSyntax nameNode, ISyntaxFactsService syntaxFacts, out string name, out int arity, out bool inAttributeContext, out bool hasIncompleteParentMember, out bool looksGeneric) { // Has to be a simple identifier or generic name. syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out name, out arity); inAttributeContext = syntaxFacts.IsAttributeName(nameNode); hasIncompleteParentMember = syntaxFacts.HasIncompleteParentMember(nameNode); looksGeneric = syntaxFacts.LooksGeneric(nameNode); } /// <summary> /// Searches for types that match the name the user has written. Returns <see cref="SymbolReference"/>s /// to the <see cref="INamespaceSymbol"/>s or <see cref="INamedTypeSymbol"/>s those types are /// contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingTypesAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (!_owner.CanAddImportForType(_diagnosticId, _node, out var nameNode)) { return ImmutableArray<SymbolReference>.Empty; } CalculateContext( nameNode, _syntaxFacts, out var name, out var arity, out var inAttributeContext, out var hasIncompleteParentMember, out var looksGeneric); if (ExpressionBinds(nameNode, checkForExtensionMethods: false, cancellationToken: searchScope.CancellationToken)) { // If the expression bound, there's nothing to do. return ImmutableArray<SymbolReference>.Empty; } var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Type).ConfigureAwait(false); // also lookup type symbols with the "Attribute" suffix if necessary. if (inAttributeContext) { var attributeSymbols = await searchScope.FindDeclarationsAsync(name + AttributeSuffix, nameNode, SymbolFilter.Type).ConfigureAwait(false); symbols = symbols.AddRange( attributeSymbols.Select(r => r.WithDesiredName(r.DesiredName.GetWithoutAttributeSuffix(isCaseSensitive: false)))); } var typeSymbols = OfType<ITypeSymbol>(symbols); var options = await _document.GetOptionsAsync(searchScope.CancellationToken).ConfigureAwait(false); var hideAdvancedMembers = options.GetOption(CompletionOptions.HideAdvancedMembers); var editorBrowserInfo = new EditorBrowsableInfo(_semanticModel.Compilation); // Only keep symbols which are accessible from the current location and that are allowed by the current // editor browsable rules. var accessibleTypeSymbols = typeSymbols.WhereAsArray( s => ArityAccessibilityAndAttributeContextAreCorrect(s.Symbol, arity, inAttributeContext, hasIncompleteParentMember, looksGeneric) && s.Symbol.IsEditorBrowsable(hideAdvancedMembers, _semanticModel.Compilation, editorBrowserInfo)); // These types may be contained within namespaces, or they may be nested // inside generic types. Record these namespaces/types if it would be // legal to add imports for them. var typesContainedDirectlyInNamespaces = accessibleTypeSymbols.WhereAsArray(s => s.Symbol.ContainingSymbol is INamespaceSymbol); var typesContainedDirectlyInTypes = accessibleTypeSymbols.WhereAsArray(s => s.Symbol.ContainingType != null); var namespaceReferences = GetNamespaceSymbolReferences(searchScope, typesContainedDirectlyInNamespaces.SelectAsArray(r => r.WithSymbol(r.Symbol.ContainingNamespace))); var typeReferences = typesContainedDirectlyInTypes.SelectAsArray( r => searchScope.CreateReference(r.WithSymbol(r.Symbol.ContainingType))); return namespaceReferences.Concat(typeReferences); } private bool ArityAccessibilityAndAttributeContextAreCorrect( ITypeSymbol symbol, int arity, bool inAttributeContext, bool hasIncompleteParentMember, bool looksGeneric) { if (inAttributeContext && !symbol.IsAttribute()) { return false; } if (!symbol.IsAccessibleWithin(_semanticModel.Compilation.Assembly)) { return false; } if (looksGeneric && symbol.GetTypeArguments().Length == 0) { return false; } return arity == 0 || symbol.GetArity() == arity || hasIncompleteParentMember; } /// <summary> /// Searches for namespaces that match the name the user has written. Returns <see cref="SymbolReference"/>s /// to the <see cref="INamespaceSymbol"/>s those namespaces are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingNamespacesAsync( SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForNamespace(_diagnosticId, _node, out var nameNode)) { _syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out var name, out var arity); if (arity == 0 && !ExpressionBinds(nameNode, checkForExtensionMethods: false, cancellationToken: searchScope.CancellationToken)) { var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Namespace).ConfigureAwait(false); var namespaceSymbols = OfType<INamespaceSymbol>(symbols); var containingNamespaceSymbols = OfType<INamespaceSymbol>(symbols).SelectAsArray(s => s.WithSymbol(s.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, containingNamespaceSymbols); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Specialized finder for the "Color Color" case. Used when we have "Color.Black" and "Color" /// bound to a Field/Property, but not a type. In this case, we want to look for namespaces /// containing 'Color' as if we import them it can resolve this issue. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingFieldsAndPropertiesAsync( SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForMethod(_diagnosticId, _syntaxFacts, _node, out var nameNode) && nameNode != null) { // We have code like "Color.Black". "Color" bound to a 'Color Color' property, and // 'Black' did not bind. We want to find a type called 'Color' that will actually // allow 'Black' to bind. var syntaxFacts = _document.GetLanguageService<ISyntaxFactsService>(); if (syntaxFacts.IsNameOfSimpleMemberAccessExpression(nameNode) || syntaxFacts.IsNameOfMemberBindingExpression(nameNode)) { var expression = syntaxFacts.IsNameOfSimpleMemberAccessExpression(nameNode) ? syntaxFacts.GetExpressionOfMemberAccessExpression(nameNode.Parent, allowImplicitTarget: true) : syntaxFacts.GetTargetOfMemberBinding(nameNode.Parent); if (expression is TSimpleNameSyntax simpleName) { // Check if the expression before the dot binds to a property or field. var symbol = _semanticModel.GetSymbolInfo(expression, searchScope.CancellationToken).GetAnySymbol(); if (symbol?.Kind is SymbolKind.Property or SymbolKind.Field) { // Check if we have the 'Color Color' case. var propertyOrFieldType = symbol.GetSymbolType(); if (propertyOrFieldType is INamedTypeSymbol propertyType && Equals(propertyType.Name, symbol.Name)) { // Try to look up 'Color' as a type. var symbolResults = await searchScope.FindDeclarationsAsync( symbol.Name, simpleName, SymbolFilter.Type).ConfigureAwait(false); // Return results that have accessible members. var namedTypeSymbols = OfType<INamedTypeSymbol>(symbolResults); var name = nameNode.GetFirstToken().ValueText; var namespaceResults = namedTypeSymbols.WhereAsArray(sr => HasAccessibleStaticFieldOrProperty(sr.Symbol, name)) .SelectAsArray(sr => sr.WithSymbol(sr.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, namespaceResults); } } } } } return ImmutableArray<SymbolReference>.Empty; } private bool HasAccessibleStaticFieldOrProperty(INamedTypeSymbol namedType, string fieldOrPropertyName) { return namedType.GetMembers(fieldOrPropertyName) .Any(m => (m is IFieldSymbol || m is IPropertySymbol) && m.IsStatic && m.IsAccessibleWithin(_semanticModel.Compilation.Assembly)); } /// <summary> /// Searches for extension methods that match the name the user has written. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingExtensionMethodsAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForMethod(_diagnosticId, _syntaxFacts, _node, out var nameNode) && nameNode != null) { searchScope.CancellationToken.ThrowIfCancellationRequested(); // See if the name binds. If it does, there's nothing further we need to do. if (!ExpressionBinds(nameNode, checkForExtensionMethods: true, cancellationToken: searchScope.CancellationToken)) { _syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out var name, out var arity); if (name != null) { var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Member).ConfigureAwait(false); var methodSymbols = OfType<IMethodSymbol>(symbols); var extensionMethodSymbols = GetViableExtensionMethods( methodSymbols, nameNode.Parent, searchScope.CancellationToken); var namespaceSymbols = extensionMethodSymbols.SelectAsArray(s => s.WithSymbol(s.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, namespaceSymbols); } } } return ImmutableArray<SymbolReference>.Empty; } private ImmutableArray<SymbolResult<IMethodSymbol>> GetViableExtensionMethods( ImmutableArray<SymbolResult<IMethodSymbol>> methodSymbols, SyntaxNode expression, CancellationToken cancellationToken) { return GetViableExtensionMethodsWorker(methodSymbols).WhereAsArray( s => _owner.IsViableExtensionMethod(s.Symbol, expression, _semanticModel, _syntaxFacts, cancellationToken)); } private ImmutableArray<SymbolResult<IMethodSymbol>> GetViableExtensionMethods( ImmutableArray<SymbolResult<IMethodSymbol>> methodSymbols, ITypeSymbol typeSymbol) { return GetViableExtensionMethodsWorker(methodSymbols).WhereAsArray( s => IsViableExtensionMethod(s.Symbol, typeSymbol)); } private ImmutableArray<SymbolResult<IMethodSymbol>> GetViableExtensionMethodsWorker( ImmutableArray<SymbolResult<IMethodSymbol>> methodSymbols) { return methodSymbols.WhereAsArray( s => s.Symbol.IsExtensionMethod && s.Symbol.IsAccessibleWithin(_semanticModel.Compilation.Assembly)); } /// <summary> /// Searches for extension methods exactly called 'Add'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForCollectionInitializerMethodsAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForMethod(_diagnosticId, _syntaxFacts, _node, out _) && !_syntaxFacts.IsSimpleName(_node) && _owner.IsAddMethodContext(_node, _semanticModel)) { var symbols = await searchScope.FindDeclarationsAsync( nameof(IList.Add), nameNode: null, filter: SymbolFilter.Member).ConfigureAwait(false); // Note: there is no desiredName for these search results. We're searching for // extension methods called "Add", but we have no intention of renaming any // of the existing user code to that name. var methodSymbols = OfType<IMethodSymbol>(symbols).SelectAsArray(s => s.WithDesiredName(null)); var viableMethods = GetViableExtensionMethods( methodSymbols, _node.Parent, searchScope.CancellationToken); return GetNamespaceSymbolReferences(searchScope, viableMethods.SelectAsArray(m => m.WithSymbol(m.Symbol.ContainingNamespace))); } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'Select'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForQueryPatternsAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForQuery(_diagnosticId, _node)) { var type = _owner.GetQueryClauseInfo(_semanticModel, _node, searchScope.CancellationToken); if (type != null) { // find extension methods named "Select" return await GetReferencesForExtensionMethodAsync( searchScope, nameof(Enumerable.Select), type).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'GetAwaiter'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForGetAwaiterAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForGetAwaiter(_diagnosticId, _syntaxFacts, _node)) { var type = GetAwaitInfo(_semanticModel, _syntaxFacts, _node); if (type != null) { return await GetReferencesForExtensionMethodAsync(searchScope, WellKnownMemberNames.GetAwaiter, type, m => m.IsValidGetAwaiter()).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'GetEnumerator'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForGetEnumeratorAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForGetEnumerator(_diagnosticId, _syntaxFacts, _node)) { var type = GetCollectionExpressionType(_semanticModel, _syntaxFacts, _node); if (type != null) { return await GetReferencesForExtensionMethodAsync(searchScope, WellKnownMemberNames.GetEnumeratorMethodName, type, m => m.IsValidGetEnumerator()).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'GetAsyncEnumerator'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForGetAsyncEnumeratorAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForGetAsyncEnumerator(_diagnosticId, _syntaxFacts, _node)) { var type = GetCollectionExpressionType(_semanticModel, _syntaxFacts, _node); if (type != null) { return await GetReferencesForExtensionMethodAsync(searchScope, WellKnownMemberNames.GetAsyncEnumeratorMethodName, type, m => m.IsValidGetAsyncEnumerator()).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'Deconstruct'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForDeconstructAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForDeconstruct(_diagnosticId, _node)) { var type = _owner.GetDeconstructInfo(_semanticModel, _node, searchScope.CancellationToken); if (type != null) { // Note: we could check that the extension methods have the right number of out-params. // But that would involve figuring out what we're trying to deconstruct into. For now // we'll just be permissive, with the assumption that there won't be that many matching // 'Deconstruct' extension methods for the type of node that we're on. return await GetReferencesForExtensionMethodAsync( searchScope, "Deconstruct", type, m => m.ReturnsVoid).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } private async Task<ImmutableArray<SymbolReference>> GetReferencesForExtensionMethodAsync( SearchScope searchScope, string name, ITypeSymbol type, Func<IMethodSymbol, bool> predicate = null) { var symbols = await searchScope.FindDeclarationsAsync( name, nameNode: null, filter: SymbolFilter.Member).ConfigureAwait(false); // Note: there is no "desiredName" when doing this. We're not going to do any // renames of the user code. We're just looking for an extension method called // "Select", but that name has no bearing on the code in question that we're // trying to fix up. var methodSymbols = OfType<IMethodSymbol>(symbols).SelectAsArray(s => s.WithDesiredName(null)); var viableExtensionMethods = GetViableExtensionMethods(methodSymbols, type); if (predicate != null) { viableExtensionMethods = viableExtensionMethods.WhereAsArray(s => predicate(s.Symbol)); } var namespaceSymbols = viableExtensionMethods.SelectAsArray(s => s.WithSymbol(s.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, namespaceSymbols); } protected bool ExpressionBinds( TSimpleNameSyntax nameNode, bool checkForExtensionMethods, CancellationToken cancellationToken) { // See if the name binds to something other then the error type. If it does, there's nothing further we need to do. // For extension methods, however, we will continue to search if there exists any better matched method. cancellationToken.ThrowIfCancellationRequested(); var symbolInfo = _semanticModel.GetSymbolInfo(nameNode, cancellationToken); if (symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure && !checkForExtensionMethods) { return true; } return symbolInfo.Symbol != null; } private ImmutableArray<SymbolReference> GetNamespaceSymbolReferences( SearchScope scope, ImmutableArray<SymbolResult<INamespaceSymbol>> namespaces) { using var _ = ArrayBuilder<SymbolReference>.GetInstance(out var references); foreach (var namespaceResult in namespaces) { var symbol = namespaceResult.Symbol; var mappedResult = namespaceResult.WithSymbol(MapToCompilationNamespaceIfPossible(namespaceResult.Symbol)); var namespaceIsInScope = _namespacesInScope.Contains(mappedResult.Symbol); if (!symbol.IsGlobalNamespace && !namespaceIsInScope) references.Add(scope.CreateReference(mappedResult)); } return references.ToImmutable(); } private static ImmutableArray<SymbolResult<T>> OfType<T>(ImmutableArray<SymbolResult<ISymbol>> symbols) where T : ISymbol { return symbols.WhereAsArray(s => s.Symbol is T) .SelectAsArray(s => s.WithSymbol((T)s.Symbol)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolSearch; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Shared.Utilities.EditorBrowsableHelpers; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax> { private partial class SymbolReferenceFinder { private const string AttributeSuffix = nameof(Attribute); private readonly string _diagnosticId; private readonly Document _document; private readonly SemanticModel _semanticModel; private readonly ISet<INamespaceSymbol> _namespacesInScope; private readonly ISyntaxFactsService _syntaxFacts; private readonly AbstractAddImportFeatureService<TSimpleNameSyntax> _owner; private readonly SyntaxNode _node; private readonly ISymbolSearchService _symbolSearchService; private readonly bool _searchReferenceAssemblies; private readonly ImmutableArray<PackageSource> _packageSources; public SymbolReferenceFinder( AbstractAddImportFeatureService<TSimpleNameSyntax> owner, Document document, SemanticModel semanticModel, string diagnosticId, SyntaxNode node, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { _owner = owner; _document = document; _semanticModel = semanticModel; _diagnosticId = diagnosticId; _node = node; _symbolSearchService = symbolSearchService; _searchReferenceAssemblies = searchReferenceAssemblies; _packageSources = packageSources; if (_searchReferenceAssemblies || packageSources.Length > 0) { Contract.ThrowIfNull(symbolSearchService); } _syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); _namespacesInScope = GetNamespacesInScope(cancellationToken); } private ISet<INamespaceSymbol> GetNamespacesInScope(CancellationToken cancellationToken) { // Add all the namespaces brought in by imports/usings. var set = _owner.GetImportNamespacesInScope(_semanticModel, _node, cancellationToken); // Also add all the namespaces we're contained in. We don't want // to add imports for these namespaces either. for (var containingNamespace = _semanticModel.GetEnclosingNamespace(_node.SpanStart, cancellationToken); containingNamespace != null; containingNamespace = containingNamespace.ContainingNamespace) { set.Add(MapToCompilationNamespaceIfPossible(containingNamespace)); } return set; } private INamespaceSymbol MapToCompilationNamespaceIfPossible(INamespaceSymbol containingNamespace) => _semanticModel.Compilation.GetCompilationNamespace(containingNamespace) ?? containingNamespace; internal Task<ImmutableArray<SymbolReference>> FindInAllSymbolsInStartingProjectAsync( bool exact, CancellationToken cancellationToken) { var searchScope = new AllSymbolsProjectSearchScope( _owner, _document.Project, exact, cancellationToken); return DoAsync(searchScope); } internal Task<ImmutableArray<SymbolReference>> FindInSourceSymbolsInProjectAsync( ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>> projectToAssembly, Project project, bool exact, CancellationToken cancellationToken) { var searchScope = new SourceSymbolsProjectSearchScope( _owner, projectToAssembly, project, exact, cancellationToken); return DoAsync(searchScope); } internal Task<ImmutableArray<SymbolReference>> FindInMetadataSymbolsAsync( IAssemblySymbol assembly, ProjectId assemblyProjectId, PortableExecutableReference metadataReference, bool exact, CancellationToken cancellationToken) { var searchScope = new MetadataSymbolsSearchScope( _owner, _document.Project.Solution, assembly, assemblyProjectId, metadataReference, exact, cancellationToken); return DoAsync(searchScope); } private async Task<ImmutableArray<SymbolReference>> DoAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); // Spin off tasks to do all our searching in parallel using var _1 = ArrayBuilder<Task<ImmutableArray<SymbolReference>>>.GetInstance(out var tasks); tasks.Add(GetReferencesForMatchingTypesAsync(searchScope)); tasks.Add(GetReferencesForMatchingNamespacesAsync(searchScope)); tasks.Add(GetReferencesForMatchingFieldsAndPropertiesAsync(searchScope)); tasks.Add(GetReferencesForMatchingExtensionMethodsAsync(searchScope)); // Searching for things like "Add" (for collection initializers) and "Select" // (for extension methods) should only be done when doing an 'exact' search. // We should not do fuzzy searches for these names. In this case it's not // like the user was writing Add or Select, but instead we're looking for // viable symbols with those names to make a collection initializer or // query expression valid. if (searchScope.Exact) { tasks.Add(GetReferencesForCollectionInitializerMethodsAsync(searchScope)); tasks.Add(GetReferencesForQueryPatternsAsync(searchScope)); tasks.Add(GetReferencesForDeconstructAsync(searchScope)); tasks.Add(GetReferencesForGetAwaiterAsync(searchScope)); tasks.Add(GetReferencesForGetEnumeratorAsync(searchScope)); tasks.Add(GetReferencesForGetAsyncEnumeratorAsync(searchScope)); } await Task.WhenAll(tasks).ConfigureAwait(false); searchScope.CancellationToken.ThrowIfCancellationRequested(); using var _2 = ArrayBuilder<SymbolReference>.GetInstance(out var allReferences); foreach (var task in tasks) { var taskResult = await task.ConfigureAwait(false); allReferences.AddRange(taskResult); } return DeDupeAndSortReferences(allReferences.ToImmutable()); } private ImmutableArray<SymbolReference> DeDupeAndSortReferences(ImmutableArray<SymbolReference> allReferences) { return allReferences .Distinct() .Where(NotNull) .Where(NotGlobalNamespace) .OrderBy((r1, r2) => r1.CompareTo(_document, r2)) .ToImmutableArray(); } private static void CalculateContext( TSimpleNameSyntax nameNode, ISyntaxFactsService syntaxFacts, out string name, out int arity, out bool inAttributeContext, out bool hasIncompleteParentMember, out bool looksGeneric) { // Has to be a simple identifier or generic name. syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out name, out arity); inAttributeContext = syntaxFacts.IsAttributeName(nameNode); hasIncompleteParentMember = nameNode?.Parent?.RawKind == syntaxFacts.SyntaxKinds.IncompleteMember; looksGeneric = syntaxFacts.LooksGeneric(nameNode); } /// <summary> /// Searches for types that match the name the user has written. Returns <see cref="SymbolReference"/>s /// to the <see cref="INamespaceSymbol"/>s or <see cref="INamedTypeSymbol"/>s those types are /// contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingTypesAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (!_owner.CanAddImportForType(_diagnosticId, _node, out var nameNode)) { return ImmutableArray<SymbolReference>.Empty; } CalculateContext( nameNode, _syntaxFacts, out var name, out var arity, out var inAttributeContext, out var hasIncompleteParentMember, out var looksGeneric); if (ExpressionBinds(nameNode, checkForExtensionMethods: false, cancellationToken: searchScope.CancellationToken)) { // If the expression bound, there's nothing to do. return ImmutableArray<SymbolReference>.Empty; } var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Type).ConfigureAwait(false); // also lookup type symbols with the "Attribute" suffix if necessary. if (inAttributeContext) { var attributeSymbols = await searchScope.FindDeclarationsAsync(name + AttributeSuffix, nameNode, SymbolFilter.Type).ConfigureAwait(false); symbols = symbols.AddRange( attributeSymbols.Select(r => r.WithDesiredName(r.DesiredName.GetWithoutAttributeSuffix(isCaseSensitive: false)))); } var typeSymbols = OfType<ITypeSymbol>(symbols); var options = await _document.GetOptionsAsync(searchScope.CancellationToken).ConfigureAwait(false); var hideAdvancedMembers = options.GetOption(CompletionOptions.HideAdvancedMembers); var editorBrowserInfo = new EditorBrowsableInfo(_semanticModel.Compilation); // Only keep symbols which are accessible from the current location and that are allowed by the current // editor browsable rules. var accessibleTypeSymbols = typeSymbols.WhereAsArray( s => ArityAccessibilityAndAttributeContextAreCorrect(s.Symbol, arity, inAttributeContext, hasIncompleteParentMember, looksGeneric) && s.Symbol.IsEditorBrowsable(hideAdvancedMembers, _semanticModel.Compilation, editorBrowserInfo)); // These types may be contained within namespaces, or they may be nested // inside generic types. Record these namespaces/types if it would be // legal to add imports for them. var typesContainedDirectlyInNamespaces = accessibleTypeSymbols.WhereAsArray(s => s.Symbol.ContainingSymbol is INamespaceSymbol); var typesContainedDirectlyInTypes = accessibleTypeSymbols.WhereAsArray(s => s.Symbol.ContainingType != null); var namespaceReferences = GetNamespaceSymbolReferences(searchScope, typesContainedDirectlyInNamespaces.SelectAsArray(r => r.WithSymbol(r.Symbol.ContainingNamespace))); var typeReferences = typesContainedDirectlyInTypes.SelectAsArray( r => searchScope.CreateReference(r.WithSymbol(r.Symbol.ContainingType))); return namespaceReferences.Concat(typeReferences); } private bool ArityAccessibilityAndAttributeContextAreCorrect( ITypeSymbol symbol, int arity, bool inAttributeContext, bool hasIncompleteParentMember, bool looksGeneric) { if (inAttributeContext && !symbol.IsAttribute()) { return false; } if (!symbol.IsAccessibleWithin(_semanticModel.Compilation.Assembly)) { return false; } if (looksGeneric && symbol.GetTypeArguments().Length == 0) { return false; } return arity == 0 || symbol.GetArity() == arity || hasIncompleteParentMember; } /// <summary> /// Searches for namespaces that match the name the user has written. Returns <see cref="SymbolReference"/>s /// to the <see cref="INamespaceSymbol"/>s those namespaces are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingNamespacesAsync( SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForNamespace(_diagnosticId, _node, out var nameNode)) { _syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out var name, out var arity); if (arity == 0 && !ExpressionBinds(nameNode, checkForExtensionMethods: false, cancellationToken: searchScope.CancellationToken)) { var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Namespace).ConfigureAwait(false); var namespaceSymbols = OfType<INamespaceSymbol>(symbols); var containingNamespaceSymbols = OfType<INamespaceSymbol>(symbols).SelectAsArray(s => s.WithSymbol(s.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, containingNamespaceSymbols); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Specialized finder for the "Color Color" case. Used when we have "Color.Black" and "Color" /// bound to a Field/Property, but not a type. In this case, we want to look for namespaces /// containing 'Color' as if we import them it can resolve this issue. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingFieldsAndPropertiesAsync( SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForMethod(_diagnosticId, _syntaxFacts, _node, out var nameNode) && nameNode != null) { // We have code like "Color.Black". "Color" bound to a 'Color Color' property, and // 'Black' did not bind. We want to find a type called 'Color' that will actually // allow 'Black' to bind. var syntaxFacts = _document.GetLanguageService<ISyntaxFactsService>(); if (syntaxFacts.IsNameOfSimpleMemberAccessExpression(nameNode) || syntaxFacts.IsNameOfMemberBindingExpression(nameNode)) { var expression = syntaxFacts.IsNameOfSimpleMemberAccessExpression(nameNode) ? syntaxFacts.GetExpressionOfMemberAccessExpression(nameNode.Parent, allowImplicitTarget: true) : syntaxFacts.GetTargetOfMemberBinding(nameNode.Parent); if (expression is TSimpleNameSyntax simpleName) { // Check if the expression before the dot binds to a property or field. var symbol = _semanticModel.GetSymbolInfo(expression, searchScope.CancellationToken).GetAnySymbol(); if (symbol?.Kind is SymbolKind.Property or SymbolKind.Field) { // Check if we have the 'Color Color' case. var propertyOrFieldType = symbol.GetSymbolType(); if (propertyOrFieldType is INamedTypeSymbol propertyType && Equals(propertyType.Name, symbol.Name)) { // Try to look up 'Color' as a type. var symbolResults = await searchScope.FindDeclarationsAsync( symbol.Name, simpleName, SymbolFilter.Type).ConfigureAwait(false); // Return results that have accessible members. var namedTypeSymbols = OfType<INamedTypeSymbol>(symbolResults); var name = nameNode.GetFirstToken().ValueText; var namespaceResults = namedTypeSymbols.WhereAsArray(sr => HasAccessibleStaticFieldOrProperty(sr.Symbol, name)) .SelectAsArray(sr => sr.WithSymbol(sr.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, namespaceResults); } } } } } return ImmutableArray<SymbolReference>.Empty; } private bool HasAccessibleStaticFieldOrProperty(INamedTypeSymbol namedType, string fieldOrPropertyName) { return namedType.GetMembers(fieldOrPropertyName) .Any(m => (m is IFieldSymbol || m is IPropertySymbol) && m.IsStatic && m.IsAccessibleWithin(_semanticModel.Compilation.Assembly)); } /// <summary> /// Searches for extension methods that match the name the user has written. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingExtensionMethodsAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForMethod(_diagnosticId, _syntaxFacts, _node, out var nameNode) && nameNode != null) { searchScope.CancellationToken.ThrowIfCancellationRequested(); // See if the name binds. If it does, there's nothing further we need to do. if (!ExpressionBinds(nameNode, checkForExtensionMethods: true, cancellationToken: searchScope.CancellationToken)) { _syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out var name, out var arity); if (name != null) { var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Member).ConfigureAwait(false); var methodSymbols = OfType<IMethodSymbol>(symbols); var extensionMethodSymbols = GetViableExtensionMethods( methodSymbols, nameNode.Parent, searchScope.CancellationToken); var namespaceSymbols = extensionMethodSymbols.SelectAsArray(s => s.WithSymbol(s.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, namespaceSymbols); } } } return ImmutableArray<SymbolReference>.Empty; } private ImmutableArray<SymbolResult<IMethodSymbol>> GetViableExtensionMethods( ImmutableArray<SymbolResult<IMethodSymbol>> methodSymbols, SyntaxNode expression, CancellationToken cancellationToken) { return GetViableExtensionMethodsWorker(methodSymbols).WhereAsArray( s => _owner.IsViableExtensionMethod(s.Symbol, expression, _semanticModel, _syntaxFacts, cancellationToken)); } private ImmutableArray<SymbolResult<IMethodSymbol>> GetViableExtensionMethods( ImmutableArray<SymbolResult<IMethodSymbol>> methodSymbols, ITypeSymbol typeSymbol) { return GetViableExtensionMethodsWorker(methodSymbols).WhereAsArray( s => IsViableExtensionMethod(s.Symbol, typeSymbol)); } private ImmutableArray<SymbolResult<IMethodSymbol>> GetViableExtensionMethodsWorker( ImmutableArray<SymbolResult<IMethodSymbol>> methodSymbols) { return methodSymbols.WhereAsArray( s => s.Symbol.IsExtensionMethod && s.Symbol.IsAccessibleWithin(_semanticModel.Compilation.Assembly)); } /// <summary> /// Searches for extension methods exactly called 'Add'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForCollectionInitializerMethodsAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForMethod(_diagnosticId, _syntaxFacts, _node, out _) && !_syntaxFacts.IsSimpleName(_node) && _owner.IsAddMethodContext(_node, _semanticModel)) { var symbols = await searchScope.FindDeclarationsAsync( nameof(IList.Add), nameNode: null, filter: SymbolFilter.Member).ConfigureAwait(false); // Note: there is no desiredName for these search results. We're searching for // extension methods called "Add", but we have no intention of renaming any // of the existing user code to that name. var methodSymbols = OfType<IMethodSymbol>(symbols).SelectAsArray(s => s.WithDesiredName(null)); var viableMethods = GetViableExtensionMethods( methodSymbols, _node.Parent, searchScope.CancellationToken); return GetNamespaceSymbolReferences(searchScope, viableMethods.SelectAsArray(m => m.WithSymbol(m.Symbol.ContainingNamespace))); } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'Select'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForQueryPatternsAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForQuery(_diagnosticId, _node)) { var type = _owner.GetQueryClauseInfo(_semanticModel, _node, searchScope.CancellationToken); if (type != null) { // find extension methods named "Select" return await GetReferencesForExtensionMethodAsync( searchScope, nameof(Enumerable.Select), type).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'GetAwaiter'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForGetAwaiterAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForGetAwaiter(_diagnosticId, _syntaxFacts, _node)) { var type = GetAwaitInfo(_semanticModel, _syntaxFacts, _node); if (type != null) { return await GetReferencesForExtensionMethodAsync(searchScope, WellKnownMemberNames.GetAwaiter, type, m => m.IsValidGetAwaiter()).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'GetEnumerator'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForGetEnumeratorAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForGetEnumerator(_diagnosticId, _syntaxFacts, _node)) { var type = GetCollectionExpressionType(_semanticModel, _syntaxFacts, _node); if (type != null) { return await GetReferencesForExtensionMethodAsync(searchScope, WellKnownMemberNames.GetEnumeratorMethodName, type, m => m.IsValidGetEnumerator()).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'GetAsyncEnumerator'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForGetAsyncEnumeratorAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForGetAsyncEnumerator(_diagnosticId, _syntaxFacts, _node)) { var type = GetCollectionExpressionType(_semanticModel, _syntaxFacts, _node); if (type != null) { return await GetReferencesForExtensionMethodAsync(searchScope, WellKnownMemberNames.GetAsyncEnumeratorMethodName, type, m => m.IsValidGetAsyncEnumerator()).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'Deconstruct'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForDeconstructAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForDeconstruct(_diagnosticId, _node)) { var type = _owner.GetDeconstructInfo(_semanticModel, _node, searchScope.CancellationToken); if (type != null) { // Note: we could check that the extension methods have the right number of out-params. // But that would involve figuring out what we're trying to deconstruct into. For now // we'll just be permissive, with the assumption that there won't be that many matching // 'Deconstruct' extension methods for the type of node that we're on. return await GetReferencesForExtensionMethodAsync( searchScope, "Deconstruct", type, m => m.ReturnsVoid).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } private async Task<ImmutableArray<SymbolReference>> GetReferencesForExtensionMethodAsync( SearchScope searchScope, string name, ITypeSymbol type, Func<IMethodSymbol, bool> predicate = null) { var symbols = await searchScope.FindDeclarationsAsync( name, nameNode: null, filter: SymbolFilter.Member).ConfigureAwait(false); // Note: there is no "desiredName" when doing this. We're not going to do any // renames of the user code. We're just looking for an extension method called // "Select", but that name has no bearing on the code in question that we're // trying to fix up. var methodSymbols = OfType<IMethodSymbol>(symbols).SelectAsArray(s => s.WithDesiredName(null)); var viableExtensionMethods = GetViableExtensionMethods(methodSymbols, type); if (predicate != null) { viableExtensionMethods = viableExtensionMethods.WhereAsArray(s => predicate(s.Symbol)); } var namespaceSymbols = viableExtensionMethods.SelectAsArray(s => s.WithSymbol(s.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, namespaceSymbols); } protected bool ExpressionBinds( TSimpleNameSyntax nameNode, bool checkForExtensionMethods, CancellationToken cancellationToken) { // See if the name binds to something other then the error type. If it does, there's nothing further we need to do. // For extension methods, however, we will continue to search if there exists any better matched method. cancellationToken.ThrowIfCancellationRequested(); var symbolInfo = _semanticModel.GetSymbolInfo(nameNode, cancellationToken); if (symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure && !checkForExtensionMethods) { return true; } return symbolInfo.Symbol != null; } private ImmutableArray<SymbolReference> GetNamespaceSymbolReferences( SearchScope scope, ImmutableArray<SymbolResult<INamespaceSymbol>> namespaces) { using var _ = ArrayBuilder<SymbolReference>.GetInstance(out var references); foreach (var namespaceResult in namespaces) { var symbol = namespaceResult.Symbol; var mappedResult = namespaceResult.WithSymbol(MapToCompilationNamespaceIfPossible(namespaceResult.Symbol)); var namespaceIsInScope = _namespacesInScope.Contains(mappedResult.Symbol); if (!symbol.IsGlobalNamespace && !namespaceIsInScope) references.Add(scope.CreateReference(mappedResult)); } return references.ToImmutable(); } private static ImmutableArray<SymbolResult<T>> OfType<T>(ImmutableArray<SymbolResult<ISymbol>> symbols) where T : ISymbol { return symbols.WhereAsArray(s => s.Symbol is T) .SelectAsArray(s => s.WithSymbol((T)s.Symbol)); } } } }
1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/BlockSyntaxExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class BlockSyntaxExtensions { public static bool TryConvertToExpressionBody( this BlockSyntax block, ParseOptions options, ExpressionBodyPreference preference, out ExpressionSyntax expression, out SyntaxToken semicolonToken) { if (preference != ExpressionBodyPreference.Never && block != null && block.Statements.Count == 1) { var firstStatement = block.Statements[0]; var version = ((CSharpParseOptions)options).LanguageVersion; if (TryGetExpression(version, firstStatement, out expression, out semicolonToken) && MatchesPreference(expression, preference)) { // The close brace of the block may have important trivia on it (like // comments or directives). Preserve them on the semicolon when we // convert to an expression body. semicolonToken = semicolonToken.WithAppendedTrailingTrivia( block.CloseBraceToken.LeadingTrivia.Where(t => !t.IsWhitespaceOrEndOfLine())); return true; } } expression = null; semicolonToken = default; return false; } public static bool TryConvertToArrowExpressionBody( this BlockSyntax block, SyntaxKind declarationKind, ParseOptions options, ExpressionBodyPreference preference, out ArrowExpressionClauseSyntax arrowExpression, out SyntaxToken semicolonToken) { var version = ((CSharpParseOptions)options).LanguageVersion; // We can always use arrow-expression bodies in C# 7 or above. // We can also use them in C# 6, but only a select set of member kinds. var acceptableVersion = version >= LanguageVersion.CSharp7 || (version >= LanguageVersion.CSharp6 && IsSupportedInCSharp6(declarationKind)); if (!acceptableVersion || !block.TryConvertToExpressionBody( options, preference, out var expression, out semicolonToken)) { arrowExpression = null; semicolonToken = default; return false; } arrowExpression = SyntaxFactory.ArrowExpressionClause(expression); return true; } private static bool IsSupportedInCSharp6(SyntaxKind declarationKind) { switch (declarationKind) { case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: return false; } return true; } public static bool MatchesPreference( ExpressionSyntax expression, ExpressionBodyPreference preference) { if (preference == ExpressionBodyPreference.WhenPossible) { return true; } Contract.ThrowIfFalse(preference == ExpressionBodyPreference.WhenOnSingleLine); return CSharpSyntaxFacts.Instance.IsOnSingleLine(expression, fullSpan: false); } private static bool TryGetExpression( LanguageVersion version, StatementSyntax firstStatement, out ExpressionSyntax expression, out SyntaxToken semicolonToken) { if (firstStatement is ExpressionStatementSyntax exprStatement) { expression = exprStatement.Expression; semicolonToken = exprStatement.SemicolonToken; return true; } else if (firstStatement is ReturnStatementSyntax returnStatement) { if (returnStatement.Expression != null) { // If there are any comments or directives on the return keyword, move them to // the expression. expression = firstStatement.GetLeadingTrivia().Any(t => t.IsDirective || t.IsSingleOrMultiLineComment()) ? returnStatement.Expression.WithLeadingTrivia(returnStatement.GetLeadingTrivia()) : returnStatement.Expression; semicolonToken = returnStatement.SemicolonToken; return true; } } else if (firstStatement is ThrowStatementSyntax throwStatement) { if (version >= LanguageVersion.CSharp7 && throwStatement.Expression != null) { expression = SyntaxFactory.ThrowExpression(throwStatement.ThrowKeyword, throwStatement.Expression); semicolonToken = throwStatement.SemicolonToken; return true; } } expression = null; semicolonToken = default; return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class BlockSyntaxExtensions { public static bool TryConvertToExpressionBody( this BlockSyntax block, ParseOptions options, ExpressionBodyPreference preference, [NotNullWhen(true)] out ExpressionSyntax? expression, out SyntaxToken semicolonToken) { if (preference != ExpressionBodyPreference.Never && block != null && block.Statements.Count == 1) { var firstStatement = block.Statements[0]; var version = ((CSharpParseOptions)options).LanguageVersion; if (TryGetExpression(version, firstStatement, out expression, out semicolonToken) && MatchesPreference(expression, preference)) { // The close brace of the block may have important trivia on it (like // comments or directives). Preserve them on the semicolon when we // convert to an expression body. semicolonToken = semicolonToken.WithAppendedTrailingTrivia( block.CloseBraceToken.LeadingTrivia.Where(t => !t.IsWhitespaceOrEndOfLine())); return true; } } expression = null; semicolonToken = default; return false; } public static bool TryConvertToArrowExpressionBody( this BlockSyntax block, SyntaxKind declarationKind, ParseOptions options, ExpressionBodyPreference preference, [NotNullWhen(true)] out ArrowExpressionClauseSyntax? arrowExpression, out SyntaxToken semicolonToken) { var version = ((CSharpParseOptions)options).LanguageVersion; // We can always use arrow-expression bodies in C# 7 or above. // We can also use them in C# 6, but only a select set of member kinds. var acceptableVersion = version >= LanguageVersion.CSharp7 || (version >= LanguageVersion.CSharp6 && IsSupportedInCSharp6(declarationKind)); if (!acceptableVersion || !block.TryConvertToExpressionBody( options, preference, out var expression, out semicolonToken)) { arrowExpression = null; semicolonToken = default; return false; } arrowExpression = SyntaxFactory.ArrowExpressionClause(expression); return true; } private static bool IsSupportedInCSharp6(SyntaxKind declarationKind) { switch (declarationKind) { case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: return false; } return true; } public static bool MatchesPreference( ExpressionSyntax expression, ExpressionBodyPreference preference) { if (preference == ExpressionBodyPreference.WhenPossible) { return true; } Contract.ThrowIfFalse(preference == ExpressionBodyPreference.WhenOnSingleLine); return CSharpSyntaxFacts.Instance.IsOnSingleLine(expression, fullSpan: false); } private static bool TryGetExpression( LanguageVersion version, StatementSyntax firstStatement, [NotNullWhen(true)] out ExpressionSyntax? expression, out SyntaxToken semicolonToken) { if (firstStatement is ExpressionStatementSyntax exprStatement) { expression = exprStatement.Expression; semicolonToken = exprStatement.SemicolonToken; return true; } else if (firstStatement is ReturnStatementSyntax returnStatement) { if (returnStatement.Expression != null) { // If there are any comments or directives on the return keyword, move them to // the expression. expression = firstStatement.GetLeadingTrivia().Any(t => t.IsDirective || t.IsSingleOrMultiLineComment()) ? returnStatement.Expression.WithLeadingTrivia(returnStatement.GetLeadingTrivia()) : returnStatement.Expression; semicolonToken = returnStatement.SemicolonToken; return true; } } else if (firstStatement is ThrowStatementSyntax throwStatement) { if (version >= LanguageVersion.CSharp7 && throwStatement.Expression != null) { expression = SyntaxFactory.ThrowExpression(throwStatement.ThrowKeyword, throwStatement.Expression); semicolonToken = throwStatement.SemicolonToken; return true; } } expression = null; semicolonToken = default; return false; } } }
1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpSyntaxFacts.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Shared.Extensions; #if CODE_STYLE using Microsoft.CodeAnalysis.Internal.Editing; #else using Microsoft.CodeAnalysis.Editing; #endif namespace Microsoft.CodeAnalysis.CSharp.LanguageServices { internal class CSharpSyntaxFacts : AbstractSyntaxFacts, ISyntaxFacts { internal static readonly CSharpSyntaxFacts Instance = new(); protected CSharpSyntaxFacts() { } public bool IsCaseSensitive => true; public StringComparer StringComparer { get; } = StringComparer.Ordinal; public SyntaxTrivia ElasticMarker => SyntaxFactory.ElasticMarker; public SyntaxTrivia ElasticCarriageReturnLineFeed => SyntaxFactory.ElasticCarriageReturnLineFeed; public override ISyntaxKinds SyntaxKinds { get; } = CSharpSyntaxKinds.Instance; public bool SupportsIndexingInitializer(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp6; public bool SupportsThrowExpression(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7; public bool SupportsLocalFunctionDeclaration(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7; public bool SupportsRecord(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp9; public bool SupportsRecordStruct(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion.IsCSharp10OrAbove(); public SyntaxToken ParseToken(string text) => SyntaxFactory.ParseToken(text); public SyntaxTriviaList ParseLeadingTrivia(string text) => SyntaxFactory.ParseLeadingTrivia(text); public string EscapeIdentifier(string identifier) { var nullIndex = identifier.IndexOf('\0'); if (nullIndex >= 0) { identifier = identifier.Substring(0, nullIndex); } var needsEscaping = SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None; return needsEscaping ? "@" + identifier : identifier; } public bool IsVerbatimIdentifier(SyntaxToken token) => token.IsVerbatimIdentifier(); public bool IsOperator(SyntaxToken token) { var kind = token.Kind(); return (SyntaxFacts.IsAnyUnaryExpression(kind) && (token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsBinaryExpression(kind) && (token.Parent is BinaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsAssignmentExpressionOperatorToken(kind) && token.Parent is AssignmentExpressionSyntax); } public bool IsReservedKeyword(SyntaxToken token) => SyntaxFacts.IsReservedKeyword(token.Kind()); public bool IsContextualKeyword(SyntaxToken token) => SyntaxFacts.IsContextualKeyword(token.Kind()); public bool IsPreprocessorKeyword(SyntaxToken token) => SyntaxFacts.IsPreprocessorKeyword(token.Kind()); public bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) => syntaxTree.IsPreProcessorDirectiveContext( position, syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true), cancellationToken); public bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken) { if (syntaxTree == null) { return false; } return syntaxTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken); } public bool IsDirective([NotNullWhen(true)] SyntaxNode? node) => node is DirectiveTriviaSyntax; public bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? node, out ExternalSourceInfo info) { if (node is LineDirectiveTriviaSyntax lineDirective) { if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword) { info = new ExternalSourceInfo(null, ends: true); return true; } else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken && lineDirective.Line.Value is int) { info = new ExternalSourceInfo((int)lineDirective.Line.Value, false); return true; } } info = default; return false; } public bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsSimpleMemberAccessExpressionName(); } public bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => node?.Parent is MemberAccessExpressionSyntax memberAccess && memberAccess.Name == node; public bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsMemberBindingExpressionName(); } [return: NotNullIfNotNull("node")] public SyntaxNode? GetStandaloneExpression(SyntaxNode? node) => node is ExpressionSyntax expression ? SyntaxFactory.GetStandaloneExpression(expression) : node; public SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node) => node.GetRootConditionalAccessExpression(); public bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node) => node is DeclarationExpressionSyntax; public bool IsAttributeName(SyntaxNode node) => SyntaxFacts.IsAttributeName(node); public bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node) => node is ArgumentSyntax arg && arg.NameColon != null; public bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node) => node.CheckParent<NameColonSyntax>(p => p.Name == node); public SyntaxToken? GetNameOfParameter(SyntaxNode? node) => (node as ParameterSyntax)?.Identifier; public SyntaxNode? GetDefaultOfParameter(SyntaxNode node) => ((ParameterSyntax)node).Default; public SyntaxNode? GetParameterList(SyntaxNode node) => node.GetParameterList(); public bool IsParameterList([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ParameterList, SyntaxKind.BracketedParameterList); public SyntaxToken GetIdentifierOfGenericName(SyntaxNode node) => ((GenericNameSyntax)node).Identifier; public bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.UsingDirective, out UsingDirectiveSyntax? usingDirective) && usingDirective.Name == node; public bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node) => node is UsingDirectiveSyntax usingDirectiveNode && usingDirectiveNode.Alias != null; public void GetPartsOfUsingAliasDirective(SyntaxNode node, out SyntaxToken globalKeyword, out SyntaxToken alias, out SyntaxNode name) { var usingDirective = (UsingDirectiveSyntax)node; globalKeyword = usingDirective.GlobalKeyword; alias = usingDirective.Alias!.Name.Identifier; name = usingDirective.Name; } public bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node) => node is ForEachVariableStatementSyntax; public bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node) => node is AssignmentExpressionSyntax assignment && assignment.IsDeconstruction(); public Location GetDeconstructionReferenceLocation(SyntaxNode node) { return node switch { AssignmentExpressionSyntax assignment => assignment.Left.GetLocation(), ForEachVariableStatementSyntax @foreach => @foreach.Variable.GetLocation(), _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()), }; } public bool IsStatement([NotNullWhen(true)] SyntaxNode? node) => node is StatementSyntax; public bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node) => node is StatementSyntax; public bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node) { if (node is BlockSyntax || node is ArrowExpressionClauseSyntax) { return node.Parent is BaseMethodDeclarationSyntax || node.Parent is AccessorDeclarationSyntax; } return false; } public SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode node) => ((ReturnStatementSyntax)node).Expression; public bool IsThisConstructorInitializer(SyntaxToken token) => token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) && constructorInit.ThisOrBaseKeyword == token; public bool IsBaseConstructorInitializer(SyntaxToken token) => token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) && constructorInit.ThisOrBaseKeyword == token; public bool IsQueryKeyword(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.FromKeyword: case SyntaxKind.JoinKeyword: case SyntaxKind.LetKeyword: case SyntaxKind.OrderByKeyword: case SyntaxKind.WhereKeyword: case SyntaxKind.OnKeyword: case SyntaxKind.EqualsKeyword: case SyntaxKind.InKeyword: return token.Parent is QueryClauseSyntax; case SyntaxKind.ByKeyword: case SyntaxKind.GroupKeyword: case SyntaxKind.SelectKeyword: return token.Parent is SelectOrGroupClauseSyntax; case SyntaxKind.AscendingKeyword: case SyntaxKind.DescendingKeyword: return token.Parent is OrderingSyntax; case SyntaxKind.IntoKeyword: return token.Parent.IsKind(SyntaxKind.JoinIntoClause, SyntaxKind.QueryContinuation); default: return false; } } public bool IsPredefinedType(SyntaxToken token) => TryGetPredefinedType(token, out _); public bool IsPredefinedType(SyntaxToken token, PredefinedType type) => TryGetPredefinedType(token, out var actualType) && actualType == type; public bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type) { type = GetPredefinedType(token); return type != PredefinedType.None; } private static PredefinedType GetPredefinedType(SyntaxToken token) { return (SyntaxKind)token.RawKind switch { SyntaxKind.BoolKeyword => PredefinedType.Boolean, SyntaxKind.ByteKeyword => PredefinedType.Byte, SyntaxKind.SByteKeyword => PredefinedType.SByte, SyntaxKind.IntKeyword => PredefinedType.Int32, SyntaxKind.UIntKeyword => PredefinedType.UInt32, SyntaxKind.ShortKeyword => PredefinedType.Int16, SyntaxKind.UShortKeyword => PredefinedType.UInt16, SyntaxKind.LongKeyword => PredefinedType.Int64, SyntaxKind.ULongKeyword => PredefinedType.UInt64, SyntaxKind.FloatKeyword => PredefinedType.Single, SyntaxKind.DoubleKeyword => PredefinedType.Double, SyntaxKind.DecimalKeyword => PredefinedType.Decimal, SyntaxKind.StringKeyword => PredefinedType.String, SyntaxKind.CharKeyword => PredefinedType.Char, SyntaxKind.ObjectKeyword => PredefinedType.Object, SyntaxKind.VoidKeyword => PredefinedType.Void, _ => PredefinedType.None, }; } public bool IsPredefinedOperator(SyntaxToken token) => TryGetPredefinedOperator(token, out var actualOperator) && actualOperator != PredefinedOperator.None; public bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op) => TryGetPredefinedOperator(token, out var actualOperator) && actualOperator == op; public bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op) { op = GetPredefinedOperator(token); return op != PredefinedOperator.None; } private static PredefinedOperator GetPredefinedOperator(SyntaxToken token) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.PlusToken: case SyntaxKind.PlusEqualsToken: return PredefinedOperator.Addition; case SyntaxKind.MinusToken: case SyntaxKind.MinusEqualsToken: return PredefinedOperator.Subtraction; case SyntaxKind.AmpersandToken: case SyntaxKind.AmpersandEqualsToken: return PredefinedOperator.BitwiseAnd; case SyntaxKind.BarToken: case SyntaxKind.BarEqualsToken: return PredefinedOperator.BitwiseOr; case SyntaxKind.MinusMinusToken: return PredefinedOperator.Decrement; case SyntaxKind.PlusPlusToken: return PredefinedOperator.Increment; case SyntaxKind.SlashToken: case SyntaxKind.SlashEqualsToken: return PredefinedOperator.Division; case SyntaxKind.EqualsEqualsToken: return PredefinedOperator.Equality; case SyntaxKind.CaretToken: case SyntaxKind.CaretEqualsToken: return PredefinedOperator.ExclusiveOr; case SyntaxKind.GreaterThanToken: return PredefinedOperator.GreaterThan; case SyntaxKind.GreaterThanEqualsToken: return PredefinedOperator.GreaterThanOrEqual; case SyntaxKind.ExclamationEqualsToken: return PredefinedOperator.Inequality; case SyntaxKind.LessThanLessThanToken: case SyntaxKind.LessThanLessThanEqualsToken: return PredefinedOperator.LeftShift; case SyntaxKind.LessThanToken: return PredefinedOperator.LessThan; case SyntaxKind.LessThanEqualsToken: return PredefinedOperator.LessThanOrEqual; case SyntaxKind.AsteriskToken: case SyntaxKind.AsteriskEqualsToken: return PredefinedOperator.Multiplication; case SyntaxKind.PercentToken: case SyntaxKind.PercentEqualsToken: return PredefinedOperator.Modulus; case SyntaxKind.ExclamationToken: case SyntaxKind.TildeToken: return PredefinedOperator.Complement; case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: return PredefinedOperator.RightShift; } return PredefinedOperator.None; } public string GetText(int kind) => SyntaxFacts.GetText((SyntaxKind)kind); public bool IsIdentifierStartCharacter(char c) => SyntaxFacts.IsIdentifierStartCharacter(c); public bool IsIdentifierPartCharacter(char c) => SyntaxFacts.IsIdentifierPartCharacter(c); public bool IsIdentifierEscapeCharacter(char c) => c == '@'; public bool IsValidIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length; } public bool IsVerbatimIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier(); } public bool IsTypeCharacter(char c) => false; public bool IsStartOfUnicodeEscapeSequence(char c) => c == '\\'; public bool IsLiteral(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.NumericLiteralToken: case SyntaxKind.CharacterLiteralToken: case SyntaxKind.StringLiteralToken: case SyntaxKind.NullKeyword: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.InterpolatedStringStartToken: case SyntaxKind.InterpolatedStringEndToken: case SyntaxKind.InterpolatedVerbatimStringStartToken: case SyntaxKind.InterpolatedStringTextToken: return true; default: return false; } } public bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token) => token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken); public bool IsBindableToken(SyntaxToken token) { if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token)) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.DelegateKeyword: case SyntaxKind.VoidKeyword: return false; } return true; } // In the order by clause a comma might be bound to ThenBy or ThenByDescending if (token.Kind() == SyntaxKind.CommaToken && token.Parent.IsKind(SyntaxKind.OrderByClause)) { return true; } return false; } public bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node) => node is PostfixUnaryExpressionSyntax; public bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node) => node is MemberBindingExpressionSyntax; public bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => (node as MemberAccessExpressionSyntax)?.Kind() == SyntaxKind.PointerMemberAccessExpression; public void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity) { var simpleName = (SimpleNameSyntax)node; name = simpleName.Identifier.ValueText; arity = simpleName.Arity; } public bool LooksGeneric(SyntaxNode simpleName) => simpleName.IsKind(SyntaxKind.GenericName) || simpleName.GetLastToken().GetNextToken().Kind() == SyntaxKind.LessThanToken; public SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node) => (node as MemberBindingExpressionSyntax).GetParentConditionalAccessExpression()?.Expression; public SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node) => ((MemberBindingExpressionSyntax)node).Name; public SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode node, bool allowImplicitTarget) => ((MemberAccessExpressionSyntax)node).Expression; public void GetPartsOfElementAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList) { var elementAccess = (ElementAccessExpressionSyntax)node; expression = elementAccess.Expression; argumentList = elementAccess.ArgumentList; } public SyntaxNode GetExpressionOfInterpolation(SyntaxNode node) => ((InterpolationSyntax)node).Expression; public bool IsInStaticContext(SyntaxNode node) => node.IsInStaticContext(); public bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node) => SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax); public bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.BaseList); public SyntaxNode GetExpressionOfArgument(SyntaxNode node) => ((ArgumentSyntax)node).Expression; public RefKind GetRefKindOfArgument(SyntaxNode node) => ((ArgumentSyntax)node).GetRefKind(); public bool IsArgument([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Argument); public bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node) { return node is ArgumentSyntax argument && argument.RefOrOutKeyword.Kind() == SyntaxKind.None && argument.NameColon == null; } public bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsInConstantContext(); public bool IsInConstructor(SyntaxNode node) => node.GetAncestor<ConstructorDeclarationSyntax>() != null; public bool IsUnsafeContext(SyntaxNode node) => node.IsUnsafeContext(); public SyntaxNode GetNameOfAttribute(SyntaxNode node) => ((AttributeSyntax)node).Name; public bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node) => (node as IdentifierNameSyntax).IsAttributeNamedArgumentIdentifier(); public SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position) { if (root == null) { throw new ArgumentNullException(nameof(root)); } if (position < 0 || position > root.Span.End) { throw new ArgumentOutOfRangeException(nameof(position)); } return root .FindToken(position) .GetAncestors<SyntaxNode>() .FirstOrDefault(n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax); } public SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node) => throw ExceptionUtilities.Unreachable; public bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IdentifierName) && node.IsParentKind(SyntaxKind.NameColon) && node.Parent.IsParentKind(SyntaxKind.Subpattern); public bool IsPropertyPatternClause(SyntaxNode node) => node.Kind() == SyntaxKind.PropertyPatternClause; public bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node) => IsMemberInitializerNamedAssignmentIdentifier(node, out _); public bool IsMemberInitializerNamedAssignmentIdentifier( [NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance) { initializedInstance = null; if (node is IdentifierNameSyntax identifier && identifier.IsLeftSideOfAssignExpression()) { if (identifier.Parent.IsParentKind(SyntaxKind.WithInitializerExpression)) { var withInitializer = identifier.Parent.GetRequiredParent(); initializedInstance = withInitializer.GetRequiredParent(); return true; } else if (identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression)) { 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; } } } return false; } public bool IsElementAccessExpression(SyntaxNode? node) => node.IsKind(SyntaxKind.ElementAccessExpression); [return: NotNullIfNotNull("node")] public SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false) => node.ConvertToSingleLine(useElasticTrivia); public bool IsIndexerMemberCRef(SyntaxNode? node) => node.IsKind(SyntaxKind.IndexerMemberCref); public SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true) { Contract.ThrowIfNull(root, "root"); Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position"); var end = root.FullSpan.End; if (end == 0) { // empty file return null; } // make sure position doesn't touch end of root position = Math.Min(position, end - 1); var node = root.FindToken(position).Parent; while (node != null) { if (useFullSpan || node.Span.Contains(position)) { var kind = node.Kind(); if ((kind != SyntaxKind.GlobalStatement) && (kind != SyntaxKind.IncompleteMember) && (node is MemberDeclarationSyntax)) { return node; } } node = node.Parent; } return null; } public bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node) { return node is BaseMethodDeclarationSyntax || node is BasePropertyDeclarationSyntax || node is EnumMemberDeclarationSyntax || node is BaseFieldDeclarationSyntax; } public bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node) { return node is BaseNamespaceDeclarationSyntax || node is TypeDeclarationSyntax || node is EnumDeclarationSyntax; } private const string dotToken = "."; public string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null) { if (node == null) { return string.Empty; } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; // return type var memberDeclaration = node as MemberDeclarationSyntax; if ((options & DisplayNameOptions.IncludeType) != 0) { var type = memberDeclaration.GetMemberType(); if (type != null && !type.IsMissing) { builder.Append(type); builder.Append(' '); } } var names = ArrayBuilder<string?>.GetInstance(); // containing type(s) var parent = node.GetAncestor<TypeDeclarationSyntax>() ?? node.Parent; while (parent is TypeDeclarationSyntax) { names.Push(GetName(parent, options)); parent = parent.Parent; } // containing namespace(s) in source (if any) if ((options & DisplayNameOptions.IncludeNamespaces) != 0) { while (parent is BaseNamespaceDeclarationSyntax) { names.Add(GetName(parent, options)); parent = parent.Parent; } } while (!names.IsEmpty()) { var name = names.Pop(); if (name != null) { builder.Append(name); builder.Append(dotToken); } } // name (including generic type parameters) builder.Append(GetName(node, options)); // parameter list (if any) if ((options & DisplayNameOptions.IncludeParameters) != 0) { builder.Append(memberDeclaration.GetParameterList()); } return pooled.ToStringAndFree(); } private static string? GetName(SyntaxNode node, DisplayNameOptions options) { const string missingTokenPlaceholder = "?"; switch (node.Kind()) { case SyntaxKind.CompilationUnit: return null; case SyntaxKind.IdentifierName: var identifier = ((IdentifierNameSyntax)node).Identifier; return identifier.IsMissing ? missingTokenPlaceholder : identifier.Text; case SyntaxKind.IncompleteMember: return missingTokenPlaceholder; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return GetName(((BaseNamespaceDeclarationSyntax)node).Name, options); case SyntaxKind.QualifiedName: var qualified = (QualifiedNameSyntax)node; return GetName(qualified.Left, options) + dotToken + GetName(qualified.Right, options); } string? name = null; if (node is MemberDeclarationSyntax memberDeclaration) { if (memberDeclaration.Kind() == SyntaxKind.ConversionOperatorDeclaration) { name = (memberDeclaration as ConversionOperatorDeclarationSyntax)?.Type.ToString(); } else { var nameToken = memberDeclaration.GetNameToken(); if (nameToken != default) { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; if (memberDeclaration.Kind() == SyntaxKind.DestructorDeclaration) { name = "~" + name; } if ((options & DisplayNameOptions.IncludeTypeParameters) != 0) { var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append(name); AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList()); name = pooled.ToStringAndFree(); } } else { Debug.Assert(memberDeclaration.Kind() == SyntaxKind.IncompleteMember); name = "?"; } } } else { if (node is VariableDeclaratorSyntax fieldDeclarator) { var nameToken = fieldDeclarator.Identifier; if (nameToken != default) { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; } } } Debug.Assert(name != null, "Unexpected node type " + node.Kind()); return name; } private static void AppendTypeParameterList(StringBuilder builder, TypeParameterListSyntax typeParameterList) { if (typeParameterList != null && typeParameterList.Parameters.Count > 0) { builder.Append('<'); builder.Append(typeParameterList.Parameters[0].Identifier.ValueText); for (var i = 1; i < typeParameterList.Parameters.Count; i++) { builder.Append(", "); builder.Append(typeParameterList.Parameters[i].Identifier.ValueText); } builder.Append('>'); } } public List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root) { var list = new List<SyntaxNode>(); AppendMembers(root, list, topLevel: true, methodLevel: true); return list; } public List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root) { var list = new List<SyntaxNode>(); AppendMembers(root, list, topLevel: false, methodLevel: true); return list; } public SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration) => ((TypeDeclarationSyntax)typeDeclaration).Members; private void AppendMembers(SyntaxNode? node, List<SyntaxNode> list, bool topLevel, bool methodLevel) { Debug.Assert(topLevel || methodLevel); foreach (var member in node.GetMembers()) { if (IsTopLevelNodeWithMembers(member)) { if (topLevel) { list.Add(member); } AppendMembers(member, list, topLevel, methodLevel); continue; } if (methodLevel && IsMethodLevelMember(member)) { list.Add(member); } } } public TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node) { if (node.Span.IsEmpty) { return default; } var member = GetContainingMemberDeclaration(node, node.SpanStart); if (member == null) { return default; } // TODO: currently we only support method for now if (member is BaseMethodDeclarationSyntax method) { if (method.Body == null) { return default; } return GetBlockBodySpan(method.Body); } return default; } public bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span) { switch (node) { case ConstructorDeclarationSyntax constructor: return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) || (constructor.Initializer != null && constructor.Initializer.Span.Contains(span)); case BaseMethodDeclarationSyntax method: return method.Body != null && GetBlockBodySpan(method.Body).Contains(span); case BasePropertyDeclarationSyntax property: return property.AccessorList != null && property.AccessorList.Span.Contains(span); case EnumMemberDeclarationSyntax @enum: return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span); case BaseFieldDeclarationSyntax field: return field.Declaration != null && field.Declaration.Span.Contains(span); } return false; } private static TextSpan GetBlockBodySpan(BlockSyntax body) => TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart); public SyntaxNode? TryGetBindableParent(SyntaxToken token) { var node = token.Parent; while (node != null) { var parent = node.Parent; // If this node is on the left side of a member access expression, don't ascend // further or we'll end up binding to something else. if (parent is MemberAccessExpressionSyntax memberAccess) { if (memberAccess.Expression == node) { break; } } // If this node is on the left side of a qualified name, don't ascend // further or we'll end up binding to something else. if (parent is QualifiedNameSyntax qualifiedName) { if (qualifiedName.Left == node) { break; } } // If this node is on the left side of a alias-qualified name, don't ascend // further or we'll end up binding to something else. if (parent is AliasQualifiedNameSyntax aliasQualifiedName) { if (aliasQualifiedName.Alias == node) { break; } } // If this node is the type of an object creation expression, return the // object creation expression. if (parent is ObjectCreationExpressionSyntax objectCreation) { if (objectCreation.Type == node) { node = parent; break; } } // The inside of an interpolated string is treated as its own token so we // need to force navigation to the parent expression syntax. if (node is InterpolatedStringTextSyntax && parent is InterpolatedStringExpressionSyntax) { node = parent; break; } // If this node is not parented by a name, we're done. if (!(parent is NameSyntax)) { break; } node = parent; } if (node is VarPatternSyntax) { return node; } // Patterns are never bindable (though their constituent types/exprs may be). return node is PatternSyntax ? null : node; } public IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken) { if (root is not CompilationUnitSyntax compilationUnit) { return SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } var constructors = new List<SyntaxNode>(); AppendConstructors(compilationUnit.Members, constructors, cancellationToken); return constructors; } private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); switch (member) { case ConstructorDeclarationSyntax constructor: constructors.Add(constructor); continue; case BaseNamespaceDeclarationSyntax @namespace: AppendConstructors(@namespace.Members, constructors, cancellationToken); break; case ClassDeclarationSyntax @class: AppendConstructors(@class.Members, constructors, cancellationToken); break; case RecordDeclarationSyntax record: AppendConstructors(record.Members, constructors, cancellationToken); break; case StructDeclarationSyntax @struct: AppendConstructors(@struct.Members, constructors, cancellationToken); break; } } } public bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace) { if (token.Kind() == SyntaxKind.CloseBraceToken) { var tuple = token.Parent.GetBraces(); openBrace = tuple.openBrace; return openBrace.Kind() == SyntaxKind.OpenBraceToken; } openBrace = default; return false; } public TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false); if (trivia.Kind() == SyntaxKind.DisabledTextTrivia) { return trivia.FullSpan; } var token = syntaxTree.FindTokenOrEndToken(position, cancellationToken); if (token.Kind() == SyntaxKind.EndOfFileToken) { var triviaList = token.LeadingTrivia; foreach (var triviaTok in triviaList.Reverse()) { if (triviaTok.Span.Contains(position)) { return default; } if (triviaTok.Span.End < position) { if (!triviaTok.HasStructure) { return default; } var structure = triviaTok.GetStructure(); if (structure is BranchingDirectiveTriviaSyntax branch) { return !branch.IsActive || !branch.BranchTaken ? TextSpan.FromBounds(branch.FullSpan.Start, position) : default; } } } } return default; } public string GetNameForArgument(SyntaxNode? argument) => (argument as ArgumentSyntax)?.NameColon?.Name.Identifier.ValueText ?? string.Empty; public string GetNameForAttributeArgument(SyntaxNode? argument) => (argument as AttributeArgumentSyntax)?.NameEquals?.Name.Identifier.ValueText ?? string.Empty; public bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfDot(); public SyntaxNode? GetRightSideOfDot(SyntaxNode? node) { return (node as QualifiedNameSyntax)?.Right ?? (node as MemberAccessExpressionSyntax)?.Name; } public SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget) { return (node as QualifiedNameSyntax)?.Left ?? (node as MemberAccessExpressionSyntax)?.Expression; } public bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node) => (node as NameSyntax).IsLeftSideOfExplicitInterfaceSpecifier(); public bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfAssignExpression(); public bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfAnyAssignExpression(); public bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfCompoundAssignExpression(); public SyntaxNode GetRightHandSideOfAssignment(SyntaxNode node) => ((AssignmentExpressionSyntax)node).Right; public bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator, out AnonymousObjectMemberDeclaratorSyntax? anonObject) && anonObject.NameEquals == null; public bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.PostIncrementExpression) || node.IsParentKind(SyntaxKind.PreIncrementExpression); public static bool IsOperandOfDecrementExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.PostDecrementExpression) || node.IsParentKind(SyntaxKind.PreDecrementExpression); public bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node) => IsOperandOfIncrementExpression(node) || IsOperandOfDecrementExpression(node); public SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString) => ((InterpolatedStringExpressionSyntax)interpolatedString).Contents; public bool IsVerbatimStringLiteral(SyntaxToken token) => token.IsVerbatimStringLiteral(); public bool IsNumericLiteral(SyntaxToken token) => token.Kind() == SyntaxKind.NumericLiteralToken; public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode invocationExpression) => GetArgumentsOfArgumentList(((InvocationExpressionSyntax)invocationExpression).ArgumentList); public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode objectCreationExpression) => ((BaseObjectCreationExpressionSyntax)objectCreationExpression).ArgumentList is { } argumentList ? GetArgumentsOfArgumentList(argumentList) : default; public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode argumentList) => ((BaseArgumentListSyntax)argumentList).Arguments; public bool IsRegularComment(SyntaxTrivia trivia) => trivia.IsRegularComment(); public bool IsDocumentationComment(SyntaxTrivia trivia) => trivia.IsDocComment(); public bool IsElastic(SyntaxTrivia trivia) => trivia.IsElastic(); public bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes) => trivia.IsPragmaDirective(out isDisable, out isActive, out errorCodes); public bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.DocumentationCommentExteriorTrivia; public bool IsDocumentationComment(SyntaxNode node) => SyntaxFacts.IsDocumentationCommentTrivia(node.Kind()); public bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node) { return node.IsKind(SyntaxKind.UsingDirective) || node.IsKind(SyntaxKind.ExternAliasDirective); } public bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node) => IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword); public bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node) => IsGlobalAttribute(node, SyntaxKind.ModuleKeyword); private static bool IsGlobalAttribute([NotNullWhen(true)] SyntaxNode? node, SyntaxKind attributeTarget) => node.IsKind(SyntaxKind.Attribute) && node.Parent.IsKind(SyntaxKind.AttributeList, out AttributeListSyntax? attributeList) && attributeList.Target?.Identifier.Kind() == attributeTarget; private static bool IsMemberDeclaration(SyntaxNode node) { // From the C# language spec: // class-member-declaration: // constant-declaration // field-declaration // method-declaration // property-declaration // event-declaration // indexer-declaration // operator-declaration // constructor-declaration // destructor-declaration // static-constructor-declaration // type-declaration switch (node.Kind()) { // Because fields declarations can define multiple symbols "public int a, b;" // We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name. case SyntaxKind.VariableDeclarator: return node.Parent.IsParentKind(SyntaxKind.FieldDeclaration) || node.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration); case SyntaxKind.FieldDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.PropertyDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: return true; default: return false; } } public bool IsDeclaration(SyntaxNode node) => SyntaxFacts.IsNamespaceMemberDeclaration(node.Kind()) || IsMemberDeclaration(node); public bool IsTypeDeclaration(SyntaxNode node) => SyntaxFacts.IsTypeDeclaration(node.Kind()); public bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement) => statement.IsKind(SyntaxKind.ExpressionStatement, out ExpressionStatementSyntax? exprStatement) && exprStatement.Expression.IsKind(SyntaxKind.SimpleAssignmentExpression); public void GetPartsOfAssignmentStatement( SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { GetPartsOfAssignmentExpressionOrStatement( ((ExpressionStatementSyntax)statement).Expression, out left, out operatorToken, out right); } public void GetPartsOfAssignmentExpressionOrStatement( SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var expression = statement; if (statement is ExpressionStatementSyntax expressionStatement) { expression = expressionStatement.Expression; } var assignment = (AssignmentExpressionSyntax)expression; left = assignment.Left; operatorToken = assignment.OperatorToken; right = assignment.Right; } public SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node) => ((SimpleNameSyntax)node).Identifier; public SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node) => ((VariableDeclaratorSyntax)node).Identifier; public SyntaxToken GetIdentifierOfParameter(SyntaxNode node) => ((ParameterSyntax)node).Identifier; public SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node) => node switch { BaseTypeDeclarationSyntax typeDecl => typeDecl.Identifier, DelegateDeclarationSyntax delegateDecl => delegateDecl.Identifier, _ => throw ExceptionUtilities.UnexpectedValue(node), }; public SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node) => ((IdentifierNameSyntax)node).Identifier; public bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement) { return ((LocalDeclarationStatementSyntax)localDeclarationStatement).Declaration.Variables.Contains( (VariableDeclaratorSyntax)declarator); } public bool AreEquivalent(SyntaxToken token1, SyntaxToken token2) => SyntaxFactory.AreEquivalent(token1, token2); public bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2) => SyntaxFactory.AreEquivalent(node1, node2); public static SyntaxNode GetExpressionOfInvocationExpression(SyntaxNode node) => ((InvocationExpressionSyntax)node).Expression; public bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node) => node?.Parent is ForEachStatementSyntax foreachStatement && foreachStatement.Expression == node; public SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node) => ((ExpressionStatementSyntax)node).Expression; public bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IsExpression); [return: NotNullIfNotNull("node")] public SyntaxNode? WalkDownParentheses(SyntaxNode? node) => (node as ExpressionSyntax)?.WalkDownParentheses() ?? node; public void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node, out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode { var tupleExpression = (TupleExpressionSyntax)node; openParen = tupleExpression.OpenParenToken; arguments = (SeparatedSyntaxList<TArgumentSyntax>)(SeparatedSyntaxList<SyntaxNode>)tupleExpression.Arguments; closeParen = tupleExpression.CloseParenToken; } public override bool IsPreprocessorDirective(SyntaxTrivia trivia) => SyntaxFacts.IsPreprocessorDirective(trivia.Kind()); protected override bool ContainsInterleavedDirective(TextSpan span, SyntaxToken token, CancellationToken cancellationToken) => token.ContainsInterleavedDirective(span, cancellationToken); public SyntaxTokenList GetModifiers(SyntaxNode? node) => node.GetModifiers(); public SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers) => node.WithModifiers(modifiers); public SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node) => ((LocalDeclarationStatementSyntax)node).Declaration.Variables; public SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node) => ((VariableDeclaratorSyntax)node).Initializer; public SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node) => ((VariableDeclarationSyntax)((VariableDeclaratorSyntax)node).Parent!).Type; public SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node) => ((EqualsValueClauseSyntax?)node)?.Value; public bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Block); public bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Block, SyntaxKind.SwitchSection, SyntaxKind.CompilationUnit); public IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node) { return node switch { BlockSyntax block => block.Statements, SwitchSectionSyntax switchSection => switchSection.Statements, CompilationUnitSyntax compilationUnit => compilationUnit.Members.OfType<GlobalStatementSyntax>().SelectAsArray(globalStatement => globalStatement.Statement), _ => throw ExceptionUtilities.UnexpectedValue(node), }; } public SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes) => nodes.FindInnermostCommonNode(node => IsExecutableBlock(node)); public bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node) => IsExecutableBlock(node) || node.IsEmbeddedStatementOwner(); public IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node) { if (IsExecutableBlock(node)) return GetExecutableBlockStatements(node); else if (node.GetEmbeddedStatement() is { } embeddedStatement) return ImmutableArray.Create<SyntaxNode>(embeddedStatement); else return ImmutableArray<SyntaxNode>.Empty; } public bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node) => node is CastExpressionSyntax; public bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node) => node is CastExpressionSyntax; public void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression) { var cast = (CastExpressionSyntax)node; type = cast.Type; expression = cast.Expression; } public SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token) { if (token.Kind() == SyntaxKind.OverrideKeyword && token.Parent is MemberDeclarationSyntax member) { return member.GetNameToken(); } return null; } public override SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node) => node.GetAttributeLists(); public override bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.XmlElement, out XmlElementSyntax? xmlElement) && xmlElement.StartTag.Name.LocalName.ValueText == DocumentationCommentXmlNames.ParameterElementName; public override SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia) { if (trivia.GetStructure() is DocumentationCommentTriviaSyntax documentationCommentTrivia) { return documentationCommentTrivia.Content; } throw ExceptionUtilities.UnexpectedValue(trivia.Kind()); } public bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IsPatternExpression); public void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right) { var isPatternExpression = (IsPatternExpressionSyntax)node; left = isPatternExpression.Expression; isToken = isPatternExpression.IsKeyword; right = isPatternExpression.Pattern; } public bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node) => node is PatternSyntax; public bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ConstantPattern); public bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.DeclarationPattern); public bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.RecursivePattern); public bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.VarPattern); public SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node) => ((ConstantPatternSyntax)node).Expression; public void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation) { var declarationPattern = (DeclarationPatternSyntax)node; type = declarationPattern.Type; designation = declarationPattern.Designation; } public void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation) { var recursivePattern = (RecursivePatternSyntax)node; type = recursivePattern.Type; positionalPart = recursivePattern.PositionalPatternClause; propertyPart = recursivePattern.PropertyPatternClause; designation = recursivePattern.Designation; } public bool SupportsNotPattern(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion.IsCSharp9OrAbove(); public bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.AndPattern); public bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node) => node is BinaryPatternSyntax; public bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.NotPattern); public bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.OrPattern); public bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ParenthesizedPattern); public bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.TypePattern); public bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node) => node is UnaryPatternSyntax; public void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen) { var parenthesizedPattern = (ParenthesizedPatternSyntax)node; openParen = parenthesizedPattern.OpenParenToken; pattern = parenthesizedPattern.Pattern; closeParen = parenthesizedPattern.CloseParenToken; } public void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var binaryPattern = (BinaryPatternSyntax)node; left = binaryPattern.Left; operatorToken = binaryPattern.OperatorToken; right = binaryPattern.Right; } public void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern) { var unaryPattern = (UnaryPatternSyntax)node; operatorToken = unaryPattern.OperatorToken; pattern = unaryPattern.Pattern; } public SyntaxNode GetTypeOfTypePattern(SyntaxNode node) => ((TypePatternSyntax)node).Type; public void GetPartsOfInterpolationExpression(SyntaxNode node, out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken) { var interpolatedStringExpression = (InterpolatedStringExpressionSyntax)node; stringStartToken = interpolatedStringExpression.StringStartToken; contents = interpolatedStringExpression.Contents; stringEndToken = interpolatedStringExpression.StringEndToken; } public bool IsVerbatimInterpolatedStringExpression(SyntaxNode node) => node is InterpolatedStringExpressionSyntax interpolatedString && interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken); #region IsXXX members public bool IsAnonymousFunctionExpression([NotNullWhen(true)] SyntaxNode? node) => node is AnonymousFunctionExpressionSyntax; public bool IsBaseNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node) => node is BaseNamespaceDeclarationSyntax; public bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node) => node is BinaryExpressionSyntax; public bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node) => node is LiteralExpressionSyntax; public bool IsMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => node is MemberAccessExpressionSyntax; public bool IsSimpleName([NotNullWhen(true)] SyntaxNode? node) => node is SimpleNameSyntax; #endregion #region GetPartsOfXXX members public void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var binaryExpression = (BinaryExpressionSyntax)node; left = binaryExpression.Left; operatorToken = binaryExpression.OperatorToken; right = binaryExpression.Right; } public void GetPartsOfCompilationUnit(SyntaxNode node, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> attributeLists, out SyntaxList<SyntaxNode> members) { var compilationUnit = (CompilationUnitSyntax)node; imports = compilationUnit.Usings; attributeLists = compilationUnit.AttributeLists; members = compilationUnit.Members; } public void GetPartsOfConditionalAccessExpression( SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull) { var conditionalAccess = (ConditionalAccessExpressionSyntax)node; expression = conditionalAccess.Expression; operatorToken = conditionalAccess.OperatorToken; whenNotNull = conditionalAccess.WhenNotNull; } public void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse) { var conditionalExpression = (ConditionalExpressionSyntax)node; condition = conditionalExpression.Condition; whenTrue = conditionalExpression.WhenTrue; whenFalse = conditionalExpression.WhenFalse; } public void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode? argumentList) { var invocation = (InvocationExpressionSyntax)node; expression = invocation.Expression; argumentList = invocation.ArgumentList; } public void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name) { var memberAccess = (MemberAccessExpressionSyntax)node; expression = memberAccess.Expression; operatorToken = memberAccess.OperatorToken; name = memberAccess.Name; } public void GetPartsOfBaseNamespaceDeclaration(SyntaxNode node, out SyntaxNode name, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> members) { var namespaceDeclaration = (BaseNamespaceDeclarationSyntax)node; name = namespaceDeclaration.Name; imports = namespaceDeclaration.Usings; members = namespaceDeclaration.Members; } public void GetPartsOfObjectCreationExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode? argumentList, out SyntaxNode? initializer) { var objectCreationExpression = (ObjectCreationExpressionSyntax)node; type = objectCreationExpression.Type; argumentList = objectCreationExpression.ArgumentList; initializer = objectCreationExpression.Initializer; } public void GetPartsOfParenthesizedExpression( SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen) { var parenthesizedExpression = (ParenthesizedExpressionSyntax)node; openParen = parenthesizedExpression.OpenParenToken; expression = parenthesizedExpression.Expression; closeParen = parenthesizedExpression.CloseParenToken; } public void GetPartsOfPrefixUnaryExpression(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode operand) { var prefixUnaryExpression = (PrefixUnaryExpressionSyntax)node; operatorToken = prefixUnaryExpression.OperatorToken; operand = prefixUnaryExpression.Operand; } public void GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var qualifiedName = (QualifiedNameSyntax)node; left = qualifiedName.Left; operatorToken = qualifiedName.DotToken; right = qualifiedName.Right; } #endregion #region GetXXXOfYYY members public SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node) => ((AwaitExpressionSyntax)node).Expression; public SyntaxNode GetExpressionOfThrowExpression(SyntaxNode node) => ((ThrowExpressionSyntax)node).Expression; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Shared.Extensions; #if CODE_STYLE using Microsoft.CodeAnalysis.Internal.Editing; #else using Microsoft.CodeAnalysis.Editing; #endif namespace Microsoft.CodeAnalysis.CSharp.LanguageServices { internal class CSharpSyntaxFacts : ISyntaxFacts { internal static readonly CSharpSyntaxFacts Instance = new(); protected CSharpSyntaxFacts() { } public bool IsCaseSensitive => true; public StringComparer StringComparer { get; } = StringComparer.Ordinal; public SyntaxTrivia ElasticMarker => SyntaxFactory.ElasticMarker; public SyntaxTrivia ElasticCarriageReturnLineFeed => SyntaxFactory.ElasticCarriageReturnLineFeed; public ISyntaxKinds SyntaxKinds { get; } = CSharpSyntaxKinds.Instance; public bool SupportsIndexingInitializer(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp6; public bool SupportsThrowExpression(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7; public bool SupportsLocalFunctionDeclaration(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7; public bool SupportsRecord(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp9; public bool SupportsRecordStruct(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion.IsCSharp10OrAbove(); public SyntaxToken ParseToken(string text) => SyntaxFactory.ParseToken(text); public SyntaxTriviaList ParseLeadingTrivia(string text) => SyntaxFactory.ParseLeadingTrivia(text); public string EscapeIdentifier(string identifier) { var nullIndex = identifier.IndexOf('\0'); if (nullIndex >= 0) { identifier = identifier.Substring(0, nullIndex); } var needsEscaping = SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None; return needsEscaping ? "@" + identifier : identifier; } public bool IsVerbatimIdentifier(SyntaxToken token) => token.IsVerbatimIdentifier(); public bool IsOperator(SyntaxToken token) { var kind = token.Kind(); return (SyntaxFacts.IsAnyUnaryExpression(kind) && (token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsBinaryExpression(kind) && (token.Parent is BinaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsAssignmentExpressionOperatorToken(kind) && token.Parent is AssignmentExpressionSyntax); } public bool IsReservedKeyword(SyntaxToken token) => SyntaxFacts.IsReservedKeyword(token.Kind()); public bool IsContextualKeyword(SyntaxToken token) => SyntaxFacts.IsContextualKeyword(token.Kind()); public bool IsPreprocessorKeyword(SyntaxToken token) => SyntaxFacts.IsPreprocessorKeyword(token.Kind()); public bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) => syntaxTree.IsPreProcessorDirectiveContext( position, syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true), cancellationToken); public bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken) { if (syntaxTree == null) { return false; } return syntaxTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken); } public bool IsDirective([NotNullWhen(true)] SyntaxNode? node) => node is DirectiveTriviaSyntax; public bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? node, out ExternalSourceInfo info) { if (node is LineDirectiveTriviaSyntax lineDirective) { if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword) { info = new ExternalSourceInfo(null, ends: true); return true; } else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken && lineDirective.Line.Value is int) { info = new ExternalSourceInfo((int)lineDirective.Line.Value, false); return true; } } info = default; return false; } public bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsSimpleMemberAccessExpressionName(); } public bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => node?.Parent is MemberAccessExpressionSyntax memberAccess && memberAccess.Name == node; public bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsMemberBindingExpressionName(); } [return: NotNullIfNotNull("node")] public SyntaxNode? GetStandaloneExpression(SyntaxNode? node) => node is ExpressionSyntax expression ? SyntaxFactory.GetStandaloneExpression(expression) : node; public SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node) => node.GetRootConditionalAccessExpression(); public bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node) => node is DeclarationExpressionSyntax; public bool IsAttributeName(SyntaxNode node) => SyntaxFacts.IsAttributeName(node); public bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node) => node is ArgumentSyntax arg && arg.NameColon != null; public bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node) => node.CheckParent<NameColonSyntax>(p => p.Name == node); public SyntaxToken? GetNameOfParameter(SyntaxNode? node) => (node as ParameterSyntax)?.Identifier; public SyntaxNode? GetDefaultOfParameter(SyntaxNode node) => ((ParameterSyntax)node).Default; public SyntaxNode? GetParameterList(SyntaxNode node) => node.GetParameterList(); public bool IsParameterList([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ParameterList, SyntaxKind.BracketedParameterList); public SyntaxToken GetIdentifierOfGenericName(SyntaxNode node) => ((GenericNameSyntax)node).Identifier; public bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.UsingDirective, out UsingDirectiveSyntax? usingDirective) && usingDirective.Name == node; public bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node) => node is UsingDirectiveSyntax usingDirectiveNode && usingDirectiveNode.Alias != null; public void GetPartsOfUsingAliasDirective(SyntaxNode node, out SyntaxToken globalKeyword, out SyntaxToken alias, out SyntaxNode name) { var usingDirective = (UsingDirectiveSyntax)node; globalKeyword = usingDirective.GlobalKeyword; alias = usingDirective.Alias!.Name.Identifier; name = usingDirective.Name; } public bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node) => node is ForEachVariableStatementSyntax; public bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node) => node is AssignmentExpressionSyntax assignment && assignment.IsDeconstruction(); public Location GetDeconstructionReferenceLocation(SyntaxNode node) { return node switch { AssignmentExpressionSyntax assignment => assignment.Left.GetLocation(), ForEachVariableStatementSyntax @foreach => @foreach.Variable.GetLocation(), _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()), }; } public bool IsStatement([NotNullWhen(true)] SyntaxNode? node) => node is StatementSyntax; public bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node) => node is StatementSyntax; public bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node) { if (node is BlockSyntax || node is ArrowExpressionClauseSyntax) { return node.Parent is BaseMethodDeclarationSyntax || node.Parent is AccessorDeclarationSyntax; } return false; } public SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode node) => ((ReturnStatementSyntax)node).Expression; public bool IsThisConstructorInitializer(SyntaxToken token) => token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) && constructorInit.ThisOrBaseKeyword == token; public bool IsBaseConstructorInitializer(SyntaxToken token) => token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) && constructorInit.ThisOrBaseKeyword == token; public bool IsQueryKeyword(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.FromKeyword: case SyntaxKind.JoinKeyword: case SyntaxKind.LetKeyword: case SyntaxKind.OrderByKeyword: case SyntaxKind.WhereKeyword: case SyntaxKind.OnKeyword: case SyntaxKind.EqualsKeyword: case SyntaxKind.InKeyword: return token.Parent is QueryClauseSyntax; case SyntaxKind.ByKeyword: case SyntaxKind.GroupKeyword: case SyntaxKind.SelectKeyword: return token.Parent is SelectOrGroupClauseSyntax; case SyntaxKind.AscendingKeyword: case SyntaxKind.DescendingKeyword: return token.Parent is OrderingSyntax; case SyntaxKind.IntoKeyword: return token.Parent.IsKind(SyntaxKind.JoinIntoClause, SyntaxKind.QueryContinuation); default: return false; } } public bool IsPredefinedType(SyntaxToken token) => TryGetPredefinedType(token, out _); public bool IsPredefinedType(SyntaxToken token, PredefinedType type) => TryGetPredefinedType(token, out var actualType) && actualType == type; public bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type) { type = GetPredefinedType(token); return type != PredefinedType.None; } private static PredefinedType GetPredefinedType(SyntaxToken token) { return (SyntaxKind)token.RawKind switch { SyntaxKind.BoolKeyword => PredefinedType.Boolean, SyntaxKind.ByteKeyword => PredefinedType.Byte, SyntaxKind.SByteKeyword => PredefinedType.SByte, SyntaxKind.IntKeyword => PredefinedType.Int32, SyntaxKind.UIntKeyword => PredefinedType.UInt32, SyntaxKind.ShortKeyword => PredefinedType.Int16, SyntaxKind.UShortKeyword => PredefinedType.UInt16, SyntaxKind.LongKeyword => PredefinedType.Int64, SyntaxKind.ULongKeyword => PredefinedType.UInt64, SyntaxKind.FloatKeyword => PredefinedType.Single, SyntaxKind.DoubleKeyword => PredefinedType.Double, SyntaxKind.DecimalKeyword => PredefinedType.Decimal, SyntaxKind.StringKeyword => PredefinedType.String, SyntaxKind.CharKeyword => PredefinedType.Char, SyntaxKind.ObjectKeyword => PredefinedType.Object, SyntaxKind.VoidKeyword => PredefinedType.Void, _ => PredefinedType.None, }; } public bool IsPredefinedOperator(SyntaxToken token) => TryGetPredefinedOperator(token, out var actualOperator) && actualOperator != PredefinedOperator.None; public bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op) => TryGetPredefinedOperator(token, out var actualOperator) && actualOperator == op; public bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op) { op = GetPredefinedOperator(token); return op != PredefinedOperator.None; } private static PredefinedOperator GetPredefinedOperator(SyntaxToken token) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.PlusToken: case SyntaxKind.PlusEqualsToken: return PredefinedOperator.Addition; case SyntaxKind.MinusToken: case SyntaxKind.MinusEqualsToken: return PredefinedOperator.Subtraction; case SyntaxKind.AmpersandToken: case SyntaxKind.AmpersandEqualsToken: return PredefinedOperator.BitwiseAnd; case SyntaxKind.BarToken: case SyntaxKind.BarEqualsToken: return PredefinedOperator.BitwiseOr; case SyntaxKind.MinusMinusToken: return PredefinedOperator.Decrement; case SyntaxKind.PlusPlusToken: return PredefinedOperator.Increment; case SyntaxKind.SlashToken: case SyntaxKind.SlashEqualsToken: return PredefinedOperator.Division; case SyntaxKind.EqualsEqualsToken: return PredefinedOperator.Equality; case SyntaxKind.CaretToken: case SyntaxKind.CaretEqualsToken: return PredefinedOperator.ExclusiveOr; case SyntaxKind.GreaterThanToken: return PredefinedOperator.GreaterThan; case SyntaxKind.GreaterThanEqualsToken: return PredefinedOperator.GreaterThanOrEqual; case SyntaxKind.ExclamationEqualsToken: return PredefinedOperator.Inequality; case SyntaxKind.LessThanLessThanToken: case SyntaxKind.LessThanLessThanEqualsToken: return PredefinedOperator.LeftShift; case SyntaxKind.LessThanToken: return PredefinedOperator.LessThan; case SyntaxKind.LessThanEqualsToken: return PredefinedOperator.LessThanOrEqual; case SyntaxKind.AsteriskToken: case SyntaxKind.AsteriskEqualsToken: return PredefinedOperator.Multiplication; case SyntaxKind.PercentToken: case SyntaxKind.PercentEqualsToken: return PredefinedOperator.Modulus; case SyntaxKind.ExclamationToken: case SyntaxKind.TildeToken: return PredefinedOperator.Complement; case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: return PredefinedOperator.RightShift; } return PredefinedOperator.None; } public string GetText(int kind) => SyntaxFacts.GetText((SyntaxKind)kind); public bool IsIdentifierStartCharacter(char c) => SyntaxFacts.IsIdentifierStartCharacter(c); public bool IsIdentifierPartCharacter(char c) => SyntaxFacts.IsIdentifierPartCharacter(c); public bool IsIdentifierEscapeCharacter(char c) => c == '@'; public bool IsValidIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length; } public bool IsVerbatimIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier(); } public bool IsTypeCharacter(char c) => false; public bool IsStartOfUnicodeEscapeSequence(char c) => c == '\\'; public bool IsLiteral(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.NumericLiteralToken: case SyntaxKind.CharacterLiteralToken: case SyntaxKind.StringLiteralToken: case SyntaxKind.NullKeyword: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.InterpolatedStringStartToken: case SyntaxKind.InterpolatedStringEndToken: case SyntaxKind.InterpolatedVerbatimStringStartToken: case SyntaxKind.InterpolatedStringTextToken: return true; default: return false; } } public bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token) => token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken); public bool IsBindableToken(SyntaxToken token) { if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token)) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.DelegateKeyword: case SyntaxKind.VoidKeyword: return false; } return true; } // In the order by clause a comma might be bound to ThenBy or ThenByDescending if (token.Kind() == SyntaxKind.CommaToken && token.Parent.IsKind(SyntaxKind.OrderByClause)) { return true; } return false; } public bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node) => node is PostfixUnaryExpressionSyntax; public bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node) => node is MemberBindingExpressionSyntax; public bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => (node as MemberAccessExpressionSyntax)?.Kind() == SyntaxKind.PointerMemberAccessExpression; public void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity) { var simpleName = (SimpleNameSyntax)node; name = simpleName.Identifier.ValueText; arity = simpleName.Arity; } public bool LooksGeneric(SyntaxNode simpleName) => simpleName.IsKind(SyntaxKind.GenericName) || simpleName.GetLastToken().GetNextToken().Kind() == SyntaxKind.LessThanToken; public SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node) => (node as MemberBindingExpressionSyntax).GetParentConditionalAccessExpression()?.Expression; public SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node) => ((MemberBindingExpressionSyntax)node).Name; public SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode node, bool allowImplicitTarget) => ((MemberAccessExpressionSyntax)node).Expression; public void GetPartsOfElementAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList) { var elementAccess = (ElementAccessExpressionSyntax)node; expression = elementAccess.Expression; argumentList = elementAccess.ArgumentList; } public SyntaxNode GetExpressionOfInterpolation(SyntaxNode node) => ((InterpolationSyntax)node).Expression; public bool IsInStaticContext(SyntaxNode node) => node.IsInStaticContext(); public bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node) => SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax); public bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.BaseList); public SyntaxNode GetExpressionOfArgument(SyntaxNode node) => ((ArgumentSyntax)node).Expression; public RefKind GetRefKindOfArgument(SyntaxNode node) => ((ArgumentSyntax)node).GetRefKind(); public bool IsArgument([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Argument); public bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node) { return node is ArgumentSyntax argument && argument.RefOrOutKeyword.Kind() == SyntaxKind.None && argument.NameColon == null; } public bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsInConstantContext(); public bool IsInConstructor(SyntaxNode node) => node.GetAncestor<ConstructorDeclarationSyntax>() != null; public bool IsUnsafeContext(SyntaxNode node) => node.IsUnsafeContext(); public SyntaxNode GetNameOfAttribute(SyntaxNode node) => ((AttributeSyntax)node).Name; public bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node) => (node as IdentifierNameSyntax).IsAttributeNamedArgumentIdentifier(); public SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position) { if (root == null) { throw new ArgumentNullException(nameof(root)); } if (position < 0 || position > root.Span.End) { throw new ArgumentOutOfRangeException(nameof(position)); } return root .FindToken(position) .GetAncestors<SyntaxNode>() .FirstOrDefault(n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax); } public SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node) => throw ExceptionUtilities.Unreachable; public bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IdentifierName) && node.IsParentKind(SyntaxKind.NameColon) && node.Parent.IsParentKind(SyntaxKind.Subpattern); public bool IsPropertyPatternClause(SyntaxNode node) => node.Kind() == SyntaxKind.PropertyPatternClause; public bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node) => IsMemberInitializerNamedAssignmentIdentifier(node, out _); public bool IsMemberInitializerNamedAssignmentIdentifier( [NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance) { initializedInstance = null; if (node is IdentifierNameSyntax identifier && identifier.IsLeftSideOfAssignExpression()) { if (identifier.Parent.IsParentKind(SyntaxKind.WithInitializerExpression)) { var withInitializer = identifier.Parent.GetRequiredParent(); initializedInstance = withInitializer.GetRequiredParent(); return true; } else if (identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression)) { 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; } } } return false; } public bool IsElementAccessExpression(SyntaxNode? node) => node.IsKind(SyntaxKind.ElementAccessExpression); [return: NotNullIfNotNull("node")] public SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false) => node.ConvertToSingleLine(useElasticTrivia); public bool IsIndexerMemberCRef(SyntaxNode? node) => node.IsKind(SyntaxKind.IndexerMemberCref); public SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true) { Contract.ThrowIfNull(root, "root"); Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position"); var end = root.FullSpan.End; if (end == 0) { // empty file return null; } // make sure position doesn't touch end of root position = Math.Min(position, end - 1); var node = root.FindToken(position).Parent; while (node != null) { if (useFullSpan || node.Span.Contains(position)) { var kind = node.Kind(); if ((kind != SyntaxKind.GlobalStatement) && (kind != SyntaxKind.IncompleteMember) && (node is MemberDeclarationSyntax)) { return node; } } node = node.Parent; } return null; } public bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node) { return node is BaseMethodDeclarationSyntax || node is BasePropertyDeclarationSyntax || node is EnumMemberDeclarationSyntax || node is BaseFieldDeclarationSyntax; } public bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node) { return node is BaseNamespaceDeclarationSyntax || node is TypeDeclarationSyntax || node is EnumDeclarationSyntax; } private const string dotToken = "."; public string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null) { if (node == null) { return string.Empty; } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; // return type var memberDeclaration = node as MemberDeclarationSyntax; if ((options & DisplayNameOptions.IncludeType) != 0) { var type = memberDeclaration.GetMemberType(); if (type != null && !type.IsMissing) { builder.Append(type); builder.Append(' '); } } var names = ArrayBuilder<string?>.GetInstance(); // containing type(s) var parent = node.GetAncestor<TypeDeclarationSyntax>() ?? node.Parent; while (parent is TypeDeclarationSyntax) { names.Push(GetName(parent, options)); parent = parent.Parent; } // containing namespace(s) in source (if any) if ((options & DisplayNameOptions.IncludeNamespaces) != 0) { while (parent is BaseNamespaceDeclarationSyntax) { names.Add(GetName(parent, options)); parent = parent.Parent; } } while (!names.IsEmpty()) { var name = names.Pop(); if (name != null) { builder.Append(name); builder.Append(dotToken); } } // name (including generic type parameters) builder.Append(GetName(node, options)); // parameter list (if any) if ((options & DisplayNameOptions.IncludeParameters) != 0) { builder.Append(memberDeclaration.GetParameterList()); } return pooled.ToStringAndFree(); } private static string? GetName(SyntaxNode node, DisplayNameOptions options) { const string missingTokenPlaceholder = "?"; switch (node.Kind()) { case SyntaxKind.CompilationUnit: return null; case SyntaxKind.IdentifierName: var identifier = ((IdentifierNameSyntax)node).Identifier; return identifier.IsMissing ? missingTokenPlaceholder : identifier.Text; case SyntaxKind.IncompleteMember: return missingTokenPlaceholder; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return GetName(((BaseNamespaceDeclarationSyntax)node).Name, options); case SyntaxKind.QualifiedName: var qualified = (QualifiedNameSyntax)node; return GetName(qualified.Left, options) + dotToken + GetName(qualified.Right, options); } string? name = null; if (node is MemberDeclarationSyntax memberDeclaration) { if (memberDeclaration.Kind() == SyntaxKind.ConversionOperatorDeclaration) { name = (memberDeclaration as ConversionOperatorDeclarationSyntax)?.Type.ToString(); } else { var nameToken = memberDeclaration.GetNameToken(); if (nameToken != default) { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; if (memberDeclaration.Kind() == SyntaxKind.DestructorDeclaration) { name = "~" + name; } if ((options & DisplayNameOptions.IncludeTypeParameters) != 0) { var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append(name); AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList()); name = pooled.ToStringAndFree(); } } else { Debug.Assert(memberDeclaration.Kind() == SyntaxKind.IncompleteMember); name = "?"; } } } else { if (node is VariableDeclaratorSyntax fieldDeclarator) { var nameToken = fieldDeclarator.Identifier; if (nameToken != default) { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; } } } Debug.Assert(name != null, "Unexpected node type " + node.Kind()); return name; } private static void AppendTypeParameterList(StringBuilder builder, TypeParameterListSyntax typeParameterList) { if (typeParameterList != null && typeParameterList.Parameters.Count > 0) { builder.Append('<'); builder.Append(typeParameterList.Parameters[0].Identifier.ValueText); for (var i = 1; i < typeParameterList.Parameters.Count; i++) { builder.Append(", "); builder.Append(typeParameterList.Parameters[i].Identifier.ValueText); } builder.Append('>'); } } public List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root) { var list = new List<SyntaxNode>(); AppendMembers(root, list, topLevel: true, methodLevel: true); return list; } public List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root) { var list = new List<SyntaxNode>(); AppendMembers(root, list, topLevel: false, methodLevel: true); return list; } public SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration) => ((TypeDeclarationSyntax)typeDeclaration).Members; private void AppendMembers(SyntaxNode? node, List<SyntaxNode> list, bool topLevel, bool methodLevel) { Debug.Assert(topLevel || methodLevel); foreach (var member in node.GetMembers()) { if (IsTopLevelNodeWithMembers(member)) { if (topLevel) { list.Add(member); } AppendMembers(member, list, topLevel, methodLevel); continue; } if (methodLevel && IsMethodLevelMember(member)) { list.Add(member); } } } public TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node) { if (node.Span.IsEmpty) { return default; } var member = GetContainingMemberDeclaration(node, node.SpanStart); if (member == null) { return default; } // TODO: currently we only support method for now if (member is BaseMethodDeclarationSyntax method) { if (method.Body == null) { return default; } return GetBlockBodySpan(method.Body); } return default; } public bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span) { switch (node) { case ConstructorDeclarationSyntax constructor: return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) || (constructor.Initializer != null && constructor.Initializer.Span.Contains(span)); case BaseMethodDeclarationSyntax method: return method.Body != null && GetBlockBodySpan(method.Body).Contains(span); case BasePropertyDeclarationSyntax property: return property.AccessorList != null && property.AccessorList.Span.Contains(span); case EnumMemberDeclarationSyntax @enum: return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span); case BaseFieldDeclarationSyntax field: return field.Declaration != null && field.Declaration.Span.Contains(span); } return false; } private static TextSpan GetBlockBodySpan(BlockSyntax body) => TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart); public SyntaxNode? TryGetBindableParent(SyntaxToken token) { var node = token.Parent; while (node != null) { var parent = node.Parent; // If this node is on the left side of a member access expression, don't ascend // further or we'll end up binding to something else. if (parent is MemberAccessExpressionSyntax memberAccess) { if (memberAccess.Expression == node) { break; } } // If this node is on the left side of a qualified name, don't ascend // further or we'll end up binding to something else. if (parent is QualifiedNameSyntax qualifiedName) { if (qualifiedName.Left == node) { break; } } // If this node is on the left side of a alias-qualified name, don't ascend // further or we'll end up binding to something else. if (parent is AliasQualifiedNameSyntax aliasQualifiedName) { if (aliasQualifiedName.Alias == node) { break; } } // If this node is the type of an object creation expression, return the // object creation expression. if (parent is ObjectCreationExpressionSyntax objectCreation) { if (objectCreation.Type == node) { node = parent; break; } } // The inside of an interpolated string is treated as its own token so we // need to force navigation to the parent expression syntax. if (node is InterpolatedStringTextSyntax && parent is InterpolatedStringExpressionSyntax) { node = parent; break; } // If this node is not parented by a name, we're done. if (!(parent is NameSyntax)) { break; } node = parent; } if (node is VarPatternSyntax) { return node; } // Patterns are never bindable (though their constituent types/exprs may be). return node is PatternSyntax ? null : node; } public IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken) { if (root is not CompilationUnitSyntax compilationUnit) { return SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } var constructors = new List<SyntaxNode>(); AppendConstructors(compilationUnit.Members, constructors, cancellationToken); return constructors; } private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); switch (member) { case ConstructorDeclarationSyntax constructor: constructors.Add(constructor); continue; case BaseNamespaceDeclarationSyntax @namespace: AppendConstructors(@namespace.Members, constructors, cancellationToken); break; case ClassDeclarationSyntax @class: AppendConstructors(@class.Members, constructors, cancellationToken); break; case RecordDeclarationSyntax record: AppendConstructors(record.Members, constructors, cancellationToken); break; case StructDeclarationSyntax @struct: AppendConstructors(@struct.Members, constructors, cancellationToken); break; } } } public bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace) { if (token.Kind() == SyntaxKind.CloseBraceToken) { var tuple = token.Parent.GetBraces(); openBrace = tuple.openBrace; return openBrace.Kind() == SyntaxKind.OpenBraceToken; } openBrace = default; return false; } public TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false); if (trivia.Kind() == SyntaxKind.DisabledTextTrivia) { return trivia.FullSpan; } var token = syntaxTree.FindTokenOrEndToken(position, cancellationToken); if (token.Kind() == SyntaxKind.EndOfFileToken) { var triviaList = token.LeadingTrivia; foreach (var triviaTok in triviaList.Reverse()) { if (triviaTok.Span.Contains(position)) { return default; } if (triviaTok.Span.End < position) { if (!triviaTok.HasStructure) { return default; } var structure = triviaTok.GetStructure(); if (structure is BranchingDirectiveTriviaSyntax branch) { return !branch.IsActive || !branch.BranchTaken ? TextSpan.FromBounds(branch.FullSpan.Start, position) : default; } } } } return default; } public string GetNameForArgument(SyntaxNode? argument) => (argument as ArgumentSyntax)?.NameColon?.Name.Identifier.ValueText ?? string.Empty; public string GetNameForAttributeArgument(SyntaxNode? argument) => (argument as AttributeArgumentSyntax)?.NameEquals?.Name.Identifier.ValueText ?? string.Empty; public bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfDot(); public SyntaxNode? GetRightSideOfDot(SyntaxNode? node) { return (node as QualifiedNameSyntax)?.Right ?? (node as MemberAccessExpressionSyntax)?.Name; } public SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget) { return (node as QualifiedNameSyntax)?.Left ?? (node as MemberAccessExpressionSyntax)?.Expression; } public bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node) => (node as NameSyntax).IsLeftSideOfExplicitInterfaceSpecifier(); public bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfAssignExpression(); public bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfAnyAssignExpression(); public bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfCompoundAssignExpression(); public SyntaxNode GetRightHandSideOfAssignment(SyntaxNode node) => ((AssignmentExpressionSyntax)node).Right; public bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator, out AnonymousObjectMemberDeclaratorSyntax? anonObject) && anonObject.NameEquals == null; public bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.PostIncrementExpression) || node.IsParentKind(SyntaxKind.PreIncrementExpression); public static bool IsOperandOfDecrementExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.PostDecrementExpression) || node.IsParentKind(SyntaxKind.PreDecrementExpression); public bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node) => IsOperandOfIncrementExpression(node) || IsOperandOfDecrementExpression(node); public SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString) => ((InterpolatedStringExpressionSyntax)interpolatedString).Contents; public bool IsVerbatimStringLiteral(SyntaxToken token) => token.IsVerbatimStringLiteral(); public bool IsNumericLiteral(SyntaxToken token) => token.Kind() == SyntaxKind.NumericLiteralToken; public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode invocationExpression) => GetArgumentsOfArgumentList(((InvocationExpressionSyntax)invocationExpression).ArgumentList); public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode objectCreationExpression) => ((BaseObjectCreationExpressionSyntax)objectCreationExpression).ArgumentList is { } argumentList ? GetArgumentsOfArgumentList(argumentList) : default; public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode argumentList) => ((BaseArgumentListSyntax)argumentList).Arguments; public bool IsRegularComment(SyntaxTrivia trivia) => trivia.IsRegularComment(); public bool IsDocumentationComment(SyntaxTrivia trivia) => trivia.IsDocComment(); public bool IsElastic(SyntaxTrivia trivia) => trivia.IsElastic(); public bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes) => trivia.IsPragmaDirective(out isDisable, out isActive, out errorCodes); public bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.DocumentationCommentExteriorTrivia; public bool IsDocumentationComment(SyntaxNode node) => SyntaxFacts.IsDocumentationCommentTrivia(node.Kind()); public bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node) { return node.IsKind(SyntaxKind.UsingDirective) || node.IsKind(SyntaxKind.ExternAliasDirective); } public bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node) => IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword); public bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node) => IsGlobalAttribute(node, SyntaxKind.ModuleKeyword); private static bool IsGlobalAttribute([NotNullWhen(true)] SyntaxNode? node, SyntaxKind attributeTarget) => node.IsKind(SyntaxKind.Attribute) && node.Parent.IsKind(SyntaxKind.AttributeList, out AttributeListSyntax? attributeList) && attributeList.Target?.Identifier.Kind() == attributeTarget; private static bool IsMemberDeclaration(SyntaxNode node) { // From the C# language spec: // class-member-declaration: // constant-declaration // field-declaration // method-declaration // property-declaration // event-declaration // indexer-declaration // operator-declaration // constructor-declaration // destructor-declaration // static-constructor-declaration // type-declaration switch (node.Kind()) { // Because fields declarations can define multiple symbols "public int a, b;" // We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name. case SyntaxKind.VariableDeclarator: return node.Parent.IsParentKind(SyntaxKind.FieldDeclaration) || node.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration); case SyntaxKind.FieldDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.PropertyDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: return true; default: return false; } } public bool IsDeclaration(SyntaxNode node) => SyntaxFacts.IsNamespaceMemberDeclaration(node.Kind()) || IsMemberDeclaration(node); public bool IsTypeDeclaration(SyntaxNode node) => SyntaxFacts.IsTypeDeclaration(node.Kind()); public bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement) => statement.IsKind(SyntaxKind.ExpressionStatement, out ExpressionStatementSyntax? exprStatement) && exprStatement.Expression.IsKind(SyntaxKind.SimpleAssignmentExpression); public void GetPartsOfAssignmentStatement( SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { GetPartsOfAssignmentExpressionOrStatement( ((ExpressionStatementSyntax)statement).Expression, out left, out operatorToken, out right); } public void GetPartsOfAssignmentExpressionOrStatement( SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var expression = statement; if (statement is ExpressionStatementSyntax expressionStatement) { expression = expressionStatement.Expression; } var assignment = (AssignmentExpressionSyntax)expression; left = assignment.Left; operatorToken = assignment.OperatorToken; right = assignment.Right; } public SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node) => ((SimpleNameSyntax)node).Identifier; public SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node) => ((VariableDeclaratorSyntax)node).Identifier; public SyntaxToken GetIdentifierOfParameter(SyntaxNode node) => ((ParameterSyntax)node).Identifier; public SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node) => node switch { BaseTypeDeclarationSyntax typeDecl => typeDecl.Identifier, DelegateDeclarationSyntax delegateDecl => delegateDecl.Identifier, _ => throw ExceptionUtilities.UnexpectedValue(node), }; public SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node) => ((IdentifierNameSyntax)node).Identifier; public bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement) { return ((LocalDeclarationStatementSyntax)localDeclarationStatement).Declaration.Variables.Contains( (VariableDeclaratorSyntax)declarator); } public bool AreEquivalent(SyntaxToken token1, SyntaxToken token2) => SyntaxFactory.AreEquivalent(token1, token2); public bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2) => SyntaxFactory.AreEquivalent(node1, node2); public static SyntaxNode GetExpressionOfInvocationExpression(SyntaxNode node) => ((InvocationExpressionSyntax)node).Expression; public bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node) => node?.Parent is ForEachStatementSyntax foreachStatement && foreachStatement.Expression == node; public SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node) => ((ExpressionStatementSyntax)node).Expression; public bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IsExpression); [return: NotNullIfNotNull("node")] public SyntaxNode? WalkDownParentheses(SyntaxNode? node) => (node as ExpressionSyntax)?.WalkDownParentheses() ?? node; public void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node, out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode { var tupleExpression = (TupleExpressionSyntax)node; openParen = tupleExpression.OpenParenToken; arguments = (SeparatedSyntaxList<SyntaxNode>)tupleExpression.Arguments; closeParen = tupleExpression.CloseParenToken; } public bool IsPreprocessorDirective(SyntaxTrivia trivia) => SyntaxFacts.IsPreprocessorDirective(trivia.Kind()); public bool ContainsInterleavedDirective(TextSpan span, SyntaxToken token, CancellationToken cancellationToken) => token.ContainsInterleavedDirective(span, cancellationToken); public SyntaxTokenList GetModifiers(SyntaxNode? node) => node.GetModifiers(); public SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers) => node.WithModifiers(modifiers); public SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node) => ((LocalDeclarationStatementSyntax)node).Declaration.Variables; public SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node) => ((VariableDeclaratorSyntax)node).Initializer; public SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node) => ((VariableDeclarationSyntax)((VariableDeclaratorSyntax)node).Parent!).Type; public SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node) => ((EqualsValueClauseSyntax?)node)?.Value; public bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Block); public bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Block, SyntaxKind.SwitchSection, SyntaxKind.CompilationUnit); public IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node) { return node switch { BlockSyntax block => block.Statements, SwitchSectionSyntax switchSection => switchSection.Statements, CompilationUnitSyntax compilationUnit => compilationUnit.Members.OfType<GlobalStatementSyntax>().SelectAsArray(globalStatement => globalStatement.Statement), _ => throw ExceptionUtilities.UnexpectedValue(node), }; } public SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes) => nodes.FindInnermostCommonNode(node => IsExecutableBlock(node)); public bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node) => IsExecutableBlock(node) || node.IsEmbeddedStatementOwner(); public IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node) { if (IsExecutableBlock(node)) return GetExecutableBlockStatements(node); else if (node.GetEmbeddedStatement() is { } embeddedStatement) return ImmutableArray.Create<SyntaxNode>(embeddedStatement); else return ImmutableArray<SyntaxNode>.Empty; } public bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node) => node is CastExpressionSyntax; public bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node) => node is CastExpressionSyntax; public void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression) { var cast = (CastExpressionSyntax)node; type = cast.Type; expression = cast.Expression; } public SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token) { if (token.Kind() == SyntaxKind.OverrideKeyword && token.Parent is MemberDeclarationSyntax member) { return member.GetNameToken(); } return null; } public SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node) => node.GetAttributeLists(); public bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.XmlElement, out XmlElementSyntax? xmlElement) && xmlElement.StartTag.Name.LocalName.ValueText == DocumentationCommentXmlNames.ParameterElementName; public SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia) { if (trivia.GetStructure() is DocumentationCommentTriviaSyntax documentationCommentTrivia) { return documentationCommentTrivia.Content; } throw ExceptionUtilities.UnexpectedValue(trivia.Kind()); } public bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IsPatternExpression); public void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right) { var isPatternExpression = (IsPatternExpressionSyntax)node; left = isPatternExpression.Expression; isToken = isPatternExpression.IsKeyword; right = isPatternExpression.Pattern; } public bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node) => node is PatternSyntax; public bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ConstantPattern); public bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.DeclarationPattern); public bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.RecursivePattern); public bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.VarPattern); public SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node) => ((ConstantPatternSyntax)node).Expression; public void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation) { var declarationPattern = (DeclarationPatternSyntax)node; type = declarationPattern.Type; designation = declarationPattern.Designation; } public void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation) { var recursivePattern = (RecursivePatternSyntax)node; type = recursivePattern.Type; positionalPart = recursivePattern.PositionalPatternClause; propertyPart = recursivePattern.PropertyPatternClause; designation = recursivePattern.Designation; } public bool SupportsNotPattern(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion.IsCSharp9OrAbove(); public bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.AndPattern); public bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node) => node is BinaryPatternSyntax; public bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.NotPattern); public bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.OrPattern); public bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ParenthesizedPattern); public bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.TypePattern); public bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node) => node is UnaryPatternSyntax; public void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen) { var parenthesizedPattern = (ParenthesizedPatternSyntax)node; openParen = parenthesizedPattern.OpenParenToken; pattern = parenthesizedPattern.Pattern; closeParen = parenthesizedPattern.CloseParenToken; } public void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var binaryPattern = (BinaryPatternSyntax)node; left = binaryPattern.Left; operatorToken = binaryPattern.OperatorToken; right = binaryPattern.Right; } public void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern) { var unaryPattern = (UnaryPatternSyntax)node; operatorToken = unaryPattern.OperatorToken; pattern = unaryPattern.Pattern; } public SyntaxNode GetTypeOfTypePattern(SyntaxNode node) => ((TypePatternSyntax)node).Type; public void GetPartsOfInterpolationExpression(SyntaxNode node, out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken) { var interpolatedStringExpression = (InterpolatedStringExpressionSyntax)node; stringStartToken = interpolatedStringExpression.StringStartToken; contents = interpolatedStringExpression.Contents; stringEndToken = interpolatedStringExpression.StringEndToken; } public bool IsVerbatimInterpolatedStringExpression(SyntaxNode node) => node is InterpolatedStringExpressionSyntax interpolatedString && interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken); #region IsXXX members public bool IsAnonymousFunctionExpression([NotNullWhen(true)] SyntaxNode? node) => node is AnonymousFunctionExpressionSyntax; public bool IsBaseNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node) => node is BaseNamespaceDeclarationSyntax; public bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node) => node is BinaryExpressionSyntax; public bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node) => node is LiteralExpressionSyntax; public bool IsMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => node is MemberAccessExpressionSyntax; public bool IsSimpleName([NotNullWhen(true)] SyntaxNode? node) => node is SimpleNameSyntax; #endregion #region GetPartsOfXXX members public void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var binaryExpression = (BinaryExpressionSyntax)node; left = binaryExpression.Left; operatorToken = binaryExpression.OperatorToken; right = binaryExpression.Right; } public void GetPartsOfCompilationUnit(SyntaxNode node, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> attributeLists, out SyntaxList<SyntaxNode> members) { var compilationUnit = (CompilationUnitSyntax)node; imports = compilationUnit.Usings; attributeLists = compilationUnit.AttributeLists; members = compilationUnit.Members; } public void GetPartsOfConditionalAccessExpression( SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull) { var conditionalAccess = (ConditionalAccessExpressionSyntax)node; expression = conditionalAccess.Expression; operatorToken = conditionalAccess.OperatorToken; whenNotNull = conditionalAccess.WhenNotNull; } public void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse) { var conditionalExpression = (ConditionalExpressionSyntax)node; condition = conditionalExpression.Condition; whenTrue = conditionalExpression.WhenTrue; whenFalse = conditionalExpression.WhenFalse; } public void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode? argumentList) { var invocation = (InvocationExpressionSyntax)node; expression = invocation.Expression; argumentList = invocation.ArgumentList; } public void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name) { var memberAccess = (MemberAccessExpressionSyntax)node; expression = memberAccess.Expression; operatorToken = memberAccess.OperatorToken; name = memberAccess.Name; } public void GetPartsOfBaseNamespaceDeclaration(SyntaxNode node, out SyntaxNode name, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> members) { var namespaceDeclaration = (BaseNamespaceDeclarationSyntax)node; name = namespaceDeclaration.Name; imports = namespaceDeclaration.Usings; members = namespaceDeclaration.Members; } public void GetPartsOfObjectCreationExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode? argumentList, out SyntaxNode? initializer) { var objectCreationExpression = (ObjectCreationExpressionSyntax)node; type = objectCreationExpression.Type; argumentList = objectCreationExpression.ArgumentList; initializer = objectCreationExpression.Initializer; } public void GetPartsOfParenthesizedExpression( SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen) { var parenthesizedExpression = (ParenthesizedExpressionSyntax)node; openParen = parenthesizedExpression.OpenParenToken; expression = parenthesizedExpression.Expression; closeParen = parenthesizedExpression.CloseParenToken; } public void GetPartsOfPrefixUnaryExpression(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode operand) { var prefixUnaryExpression = (PrefixUnaryExpressionSyntax)node; operatorToken = prefixUnaryExpression.OperatorToken; operand = prefixUnaryExpression.Operand; } public void GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var qualifiedName = (QualifiedNameSyntax)node; left = qualifiedName.Left; operatorToken = qualifiedName.DotToken; right = qualifiedName.Right; } #endregion #region GetXXXOfYYY members public SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node) => ((AwaitExpressionSyntax)node).Expression; public SyntaxNode GetExpressionOfThrowExpression(SyntaxNode node) => ((ThrowExpressionSyntax)node).Expression; #endregion } }
1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CompilerExtensions.projitems
<?xml version="1.0" encoding="utf-8"?> <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects> <HasSharedItems>true</HasSharedItems> <SharedGUID>ec946164-1e17-410b-b7d9-7de7e6268d63</SharedGUID> </PropertyGroup> <PropertyGroup Label="Configuration"> <Import_RootNamespace>Microsoft.CodeAnalysis.Shared</Import_RootNamespace> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ConcurrentDictionaryExtensions.cs" Link="InternalUtilities\ConcurrentDictionaryExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ConfiguredYieldAwaitable.cs" Link="InternalUtilities\ConfiguredYieldAwaitable.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\Debug.cs" Link="InternalUtilities\Debug.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\EnumerableExtensions.cs" Link="InternalUtilities\EnumerableExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ExceptionUtilities.cs" Link="InternalUtilities\ExceptionUtilities.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\IReadOnlySet.cs" Link="InternalUtilities\IReadOnlySet.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\KeyValuePairUtil.cs" Link="InternalUtilities\KeyValuePairUtil.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\NonCopyableAttribute.cs" Link="InternalUtilities\NonCopyableAttribute.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\NonDefaultableAttribute.cs" Link="InternalUtilities\NonDefaultableAttribute.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\NullableAttributes.cs" Link="InternalUtilities\NullableAttributes.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ReferenceEqualityComparer.cs" Link="InternalUtilities\ReferenceEqualityComparer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\RoslynString.cs" Link="InternalUtilities\RoslynString.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.cs" Link="InternalUtilities\SpecializedCollections.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SharedStopwatch.cs" Link="InternalUtilities\SharedStopwatch.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.Collection.cs" Link="InternalUtilities\SpecializedCollections.Empty.Collection.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.cs" Link="InternalUtilities\SpecializedCollections.Empty.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.Dictionary.cs" Link="InternalUtilities\SpecializedCollections.Empty.Dictionary.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.Enumerable.cs" Link="InternalUtilities\SpecializedCollections.Empty.Enumerable.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.Enumerator.cs" Link="InternalUtilities\SpecializedCollections.Empty.Enumerator.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.Enumerator`1.cs" Link="InternalUtilities\SpecializedCollections.Empty.Enumerator`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.List.cs" Link="InternalUtilities\SpecializedCollections.Empty.List.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.Set.cs" Link="InternalUtilities\SpecializedCollections.Empty.Set.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.ReadOnly.Collection.cs" Link="InternalUtilities\SpecializedCollections.ReadOnly.Collection.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.ReadOnly.Enumerable`1.cs" Link="InternalUtilities\SpecializedCollections.ReadOnly.Enumerable`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.ReadOnly.Enumerable`2.cs" Link="InternalUtilities\SpecializedCollections.ReadOnly.Enumerable`2.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.ReadOnly.Set.cs" Link="InternalUtilities\SpecializedCollections.ReadOnly.Set.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Singleton.Collection`1.cs" Link="InternalUtilities\SpecializedCollections.Singleton.Collection`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Singleton.Enumerator`1.cs" Link="InternalUtilities\SpecializedCollections.Singleton.Enumerator`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\StringExtensions.cs" Link="InternalUtilities\StringExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ValueTaskFactory.cs" Link="InternalUtilities\ValueTaskFactory.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\VoidResult.cs" Link="InternalUtilities\VoidResult.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\YieldAwaitableExtensions.cs" Link="InternalUtilities\YieldAwaitableExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Syntax\SyntaxTreeExtensions.cs" Link="Syntax\SyntaxTreeExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Collections\ImmutableArrayExtensions.cs" Link="Collections\ImmutableArrayExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Collections\BitVector.cs" Link="Collections\BitVector.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\Hash.cs" Link="InternalUtilities\Hash.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\GeneratedCodeUtilities.cs" Link="InternalUtilities\GeneratedCodeUtilities.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Serialization\IObjectWritable.cs" Link="Serialization\IObjectWritable.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Serialization\ObjectBinder.cs" Link="Serialization\ObjectBinder.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Serialization\ObjectBinderSnapshot.cs" Link="Serialization\ObjectBinderSnapshot.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Serialization\ObjectReader.cs" Link="Serialization\ObjectReader.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Serialization\ObjectWriter.cs" Link="Serialization\ObjectWriter.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Serialization\SerializationThreadPool.cs" Link="Serialization\SerializationThreadPool.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\SourceCodeKindExtensions.cs" Link="Utilities\Compiler\SourceCodeKindExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\SpecialTypeExtensions.cs" Link="Extensions\Compiler\SpecialTypeExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Collections\ArrayBuilderExtensions.cs"> <Link>Collections\ArrayBuilderExtensions.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Collections\DictionaryExtensions.cs"> <Link>Collections\DictionaryExtensions.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Collections\Boxes.cs"> <Link>Collections\Boxes.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Collections\OrderPreservingMultiDictionary.cs"> <Link>Collections\OrderPreservingMultiDictionary.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\EncodedStringText.cs"> <Link>EncodedStringText.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\FileSystem\RelativePathResolver.cs"> <Link>FileSystem\RelativePathResolver.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\AssemblyIdentityUtils.cs"> <Link>InternalUtilities\AssemblyIdentityUtils.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\BitArithmeticUtilities.cs"> <Link>InternalUtilities\BitArithmeticUtilities.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ArrayExtensions.cs"> <Link>InternalUtilities\ArrayExtensions.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\CompilerOptionParseUtilities.cs"> <Link>InternalUtilities\CompilerOptionParseUtilities.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ConcurrentSet.cs"> <Link>InternalUtilities\ConcurrentSet.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ConsList`1.cs"> <Link>InternalUtilities\ConsList`1.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\DecimalUtilities.cs"> <Link>InternalUtilities\DecimalUtilities.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\DocumentationCommentXmlNames.cs"> <Link>InternalUtilities\DocumentationCommentXmlNames.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\EncodingExtensions.cs"> <Link>InternalUtilities\EncodingExtensions.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\EnumUtilties.cs"> <Link>InternalUtilities\EnumUtilties.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\FailFast.cs"> <Link>InternalUtilities\FailFast.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\FatalError.cs"> <Link>InternalUtilities\FatalError.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\FileNameUtilities.cs"> <Link>InternalUtilities\FileNameUtilities.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ImmutableListExtensions.cs"> <Link>InternalUtilities\ImmutableListExtensions.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\Index.cs"> <Link>InternalUtilities\Index.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ISetExtensions.cs"> <Link>InternalUtilities\ISetExtensions.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\MultiDictionary.cs"> <Link>InternalUtilities\MultiDictionary.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\OrderedMultiDictionary.cs"> <Link>InternalUtilities\OrderedMultiDictionary.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SetWithInsertionOrder.cs"> <Link>InternalUtilities\SetWithInsertionOrder.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\FileSystem\PathKind.cs"> <Link>FileSystem\PathKind.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\OneOrMany.cs"> <Link>InternalUtilities\OneOrMany.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\PerformanceSensitiveAttribute.cs" Condition="'$(DotNetBuildFromSource)' == 'true'"> <Link>InternalUtilities\PerformanceSensitiveAttribute.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\PlatformInformation.cs"> <Link>InternalUtilities\PlatformInformation.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\Range.cs"> <Link>InternalUtilities\Range.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ReaderWriterLockSlimExtensions.cs"> <Link>InternalUtilities\ReaderWriterLockSlimExtensions.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SemaphoreSlimExtensions.cs"> <Link>InternalUtilities\SemaphoreSlimExtensions.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\StackGuard.cs"> <Link>InternalUtilities\StackGuard.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\StreamExtensions.cs"> <Link>InternalUtilities\StreamExtensions.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\StringTable.cs" Link="InternalUtilities\StringTable.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\TextChangeRangeExtensions.cs"> <Link>InternalUtilities\TextChangeRangeExtensions.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\WeakReferenceExtensions.cs"> <Link>InternalUtilities\WeakReferenceExtensions.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\FileSystem\FileUtilities.cs"> <Link>FileSystem\FileUtilities.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\FileSystem\PathUtilities.cs"> <Link>FileSystem\PathUtilities.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ReflectionUtilities.cs"> <Link>InternalUtilities\ReflectionUtilities.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\UnicodeCharacterUtilities.cs"> <Link>InternalUtilities\UnicodeCharacterUtilities.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)CodeActions\CodeActionRequestPriority.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\AccessibilityModifiersRequired.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\AddImportPlacement.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\CodeStyleHelpers.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\CodeStyleOption2`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\CodeStyleOptions2.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\EditorConfigSeverityStrings.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\ExpressionBodyPreference.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\NamespaceDeclarationPreference.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\NotificationOption2.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\OperatorPlacementWhenWrappingPreference.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\ParenthesesPreference.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Collections\TemporaryArrayExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Collections\TemporaryArray`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Diagnostics\IPragmaSuppressionsAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedDiagnostic.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedSyntaxHelpers.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedSyntaxNode.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedSyntaxNodeOrToken.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedSyntaxToken.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedSyntaxTree.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedSyntaxTrivia.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\VirtualChars\AbstractVirtualCharService.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\VirtualChars\IVirtualCharService.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\VirtualChars\VirtualChar.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\VirtualChars\VirtualCharSequence.Chunks.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\VirtualChars\VirtualCharSequence.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\VirtualChars\VirtualCharSequence.Enumerator.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\CompilationExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\DiagnosticAnalyzerExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\DiagnosticDescriptorExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ListExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ObjectWriterExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\FeatureFlagStorageLocation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\HeaderFacts\IHeaderFactsExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\Precedence\IPrecedenceService.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\Precedence\PrecedenceKind.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\UnusedParametersPreference.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\UnusedValuePreference.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Collections\IIntervalIntrospector.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Collections\IntervalTree`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Collections\IntervalTree`1.Node.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Collections\NormalizedTextSpanCollection.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Collections\SimpleIntervalTree.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Collections\SimpleIntervalTree`2.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Collections\TextSpanIntervalIntrospector.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Editing\GenerationOptions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\AnalyzerConfigOptionsExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ChildSyntaxListExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\DiagnosticSeverityExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\NotificationOptionExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ObjectExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ObjectExtensions.TypeSwitch.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ReportDiagnosticExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ImmutableArrayExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\LinkedListExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\LocationExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ParenthesizedExpressionSyntaxExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Fading\FadingOptions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\CustomDataFlowAnalysis.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\DataFlowAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\FlowCaptureKind.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\LValueFlowCaptureProvider.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.AnalysisData.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.BasicBlockAnalysisData.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.DataFlowAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.DataFlowAnalyzer.FlowGraphAnalysisData.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.OperationTreeAnalysisData.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.Walker.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageResult.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\AbstractSyntaxFormattingService.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\BottomUpBaseIndentationFinder.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\ContextIntervalTree.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\FormattingContext.AnchorData.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\FormattingContext.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\FormattingContext.IndentationData.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\FormattingContext.InitialContextFinder.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\SuppressIntervalIntrospector.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\SuppressSpacingData.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\SuppressWrappingData.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractAggregatedFormattingResult.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractFormatEngine.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractFormatEngine.OperationApplier.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractFormattingResult.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractTriviaDataFactory.AbstractComplexTrivia.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractTriviaDataFactory.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractTriviaDataFactory.FormattedWhitespace.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractTriviaDataFactory.ModifiedWhitespace.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractTriviaDataFactory.Whitespace.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\ChainedFormattingRules.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\NodeOperations.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TokenData.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TokenPairWithOperations.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TokenStream.Changes.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TokenStream.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TokenStream.Iterator.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TreeData.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TreeData.Debug.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TreeData.Node.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TreeData.NodeAndText.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TreeData.StructuredTrivia.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TriviaData.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TriviaDataWithList.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\FormattingDiagnosticIds.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\FormattingExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\FormattingOptions.IndentStyle.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\FormattingOptions2.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\IFormattingResult.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\ISyntaxFormattingService.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\AbstractFormattingRule.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\BaseIndentationFormattingRule.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\CompatAbstractFormattingRule.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NextAlignTokensOperationAction.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NextAnchorIndentationOperationAction.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NextGetAdjustNewLinesOperation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NextGetAdjustSpacesOperation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NextIndentBlockOperationAction.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NextSuppressOperationAction.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NoOpFormattingRule.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AdjustNewLinesOperation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AdjustNewLinesOption.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AdjustSpacesOperation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AdjustSpacesOption.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AlignTokensOperation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AlignTokensOption.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AnchorIndentationOperation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\FormattingOperations.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\IndentBlockOperation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\IndentBlockOption.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\SuppressOperation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\SuppressOption.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\StringBuilderPool.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\TriviaEngine\AbstractTriviaFormatter.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\TriviaEngine\LineColumn.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\TriviaEngine\LineColumnDelta.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\TriviaEngine\LineColumnRule.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\TriviaEngine\TriviaHelpers.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\TriviaEngine\TriviaList.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Helpers\RemoveUnnecessaryImports\IUnnecessaryImportsProvider.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Helpers\RemoveUnnecessaryImports\AbstractUnnecessaryImportsProvider.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Log\EmptyLogBlock.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Log\FunctionId.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Log\FunctionIdOptions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Log\ILogger.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Log\Logger.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Log\LogLevel.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Log\Logger.LogBlock.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Log\LogMessage.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\Capitalization.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\EditorConfig\EditorConfigNamingStyleParser.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\EditorConfig\EditorConfigNamingStyleParser_NamingRule.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\EditorConfig\EditorConfigNamingStyleParser_NamingStyle.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\EditorConfig\EditorConfigNamingStyleParser_SymbolSpec.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\NamingRule.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\NamingStyle.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\NamingStyle.WordSpanEnumerable.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\NamingStyle.WordSpanEnumerator.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\NamingStyleOptions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\NamingStyleRules.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\Serialization\AccessibilityExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\Serialization\MutableNamingStyle.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\Serialization\NamingStylePreferences.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\Serialization\SerializableNamingRule.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\Serialization\SymbolSpecification.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ObjectPools\PooledDictionary.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfig\EditorConfigStorageLocation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfig\EditorConfigStorageLocationExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfig\EditorConfigStorageLocation`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfig\IEditorConfigStorageLocation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfig\IEditorConfigStorageLocation2.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfig\NamingStylePreferenceEditorConfigStorageLocation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\IOption2.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\IOptionWithGroup.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\LocalUserProfileStorageLocation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\OptionGroup.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\OptionDefinition.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\OptionKey2.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\OptionStorageLocation2.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\Option2`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\PerLanguageOption2.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\RoamingProfileStorageLocation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\SelectedMembers\AbstractSelectedMembers.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\SemanticFacts\ForEachSymbols.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\AbstractDocumentationCommentService.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\FileBannerFacts\AbstractFileBannerFacts.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\HeaderFacts\AbstractHeaderFacts.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\AbstractSyntaxFacts.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\ExternalSourceInfo.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\IAccessibilityFacts.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\IDocumentationCommentService.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\SemanticFacts\ISemanticFacts.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\FileBannerFacts\IFileBannerFacts.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\FileBannerFacts\IFileBannerFactsExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\HeaderFacts\IHeaderFacts.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\ISyntaxFacts.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\ISyntaxFactsExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\ISyntaxKinds.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Simplification\AliasAnnotation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Simplification\DoNotAddImportsAnnotation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Simplification\DoNotAllowVarAnnotation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Simplification\SpecialTypeAnnotation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Simplification\SymbolAnnotation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)System.Text\Rune.cs" /> <Compile Include="$(MSBuildThisFileDirectory)System.Text\UnicodeDebug.cs" /> <Compile Include="$(MSBuildThisFileDirectory)System.Text\UnicodeUtility.cs" /> <Compile Include="$(MSBuildThisFileDirectory)System.Text\Utf16Utility.cs" /> <Compile Include="$(MSBuildThisFileDirectory)TestHooks\IExpeditableDelaySource.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\AbstractSpeculationAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\AliasSymbolCache.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\AnnotationTable.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\AsyncLazy`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\BidirectionalMap.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\BKTree.Builder.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\BKTree.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\BKTree.Edge.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\BKTree.Node.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\BKTree.Serialization.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\CancellableLazy.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\CancellableLazy`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\CommonFormattingHelpers.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\ComparerWithState.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\Contract.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\PathMetadataUtilities.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\PublicContract.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\EditDistance.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\EditorConfigFileGenerator_NamingStyles.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\EventMap.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\IBidirectionalMap.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\ICacheEntry.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\ICollectionExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\IDictionaryExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\IGroupingExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\IntegerUtilities.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\IReadOnlyDictionaryExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\IReadOnlyListExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\IReferenceCountedDisposable.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\LazyInitialization.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\Matcher.ChoiceMatcher.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\Matcher.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\Matcher.RepeatMatcher.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\Matcher.SequenceMatcher.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\Matcher.SingleMatcher.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\Matcher`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\NonReentrantLock.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\PooledBuilderExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\PredefinedOperator.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\PredefinedType.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\PredefinedTypeExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SemanticModelExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SimpleIntervalTreeExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SourceTextExtensions_SharedWithCodeStyle.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SpecialTypeExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\StringExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SymbolDisplayPartExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxNodeExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxNodeOrTokenExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxTokenExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxTokenListExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxTreeExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxTriviaExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxTriviaListExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\TextLineExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\TextSpanExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\CompilerUtilities\CompilerPathUtilities.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\CompilerUtilities\ImmutableDictionaryExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\CompilerUtilities\ImmutableHashMap.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\CompilerUtilities\ImmutableHashMapExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\ConcatImmutableArray`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\ReferenceCountedDisposable.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\ReferenceCountedDisposableCache.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\RestrictedInternalsVisibleToAttribute.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SemaphoreSlimFactory.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SerializableBytes.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SoftCrashException.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SpecializedTasks.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\StringBreaker.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\WordSimilarityChecker.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\StringEscapeEncoder.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\StringSlice.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SyntaxPath.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\TaskExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\TaskFactoryExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\TopologicalSorter.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\ValuesSources\ConstantValueSource.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\ValuesSources\ValueSource.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\ValuesSources\WeaklyCachedRecoverableValueSource.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\ValuesSources\WeaklyCachedValueSource.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\ValuesSources\WeakValueSource.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\WeakEventHandler.cs" /> </ItemGroup> <ItemGroup> <Compile Include="$(MSBuildThisFileDirectory)Extensions\AccessibilityUtilities.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\BasicBlockExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ControlFlowGraphExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ControlFlowRegionExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\IAssemblySymbolExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ICollectionExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ICompilationExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\IMethodSymbolExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\INamedTypeSymbolExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\INamespaceOrTypeSymbolExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\IParameterSymbolExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ISymbolExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ISymbolExtensions.RequiresUnsafeModifierVisitor.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ISymbolExtensions_Accessibility.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ITypeSymbolExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ITypeSymbolExtensions.MinimalAccessibilityVisitor.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\MethodKindExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\OperationExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\StackExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SymbolInfoExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SymbolUsageInfo.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\TypeOrNamespaceUsageInfo.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ValueUsageInfo.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ObjectPools\ArrayBuilder.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ObjectPools\Extensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ObjectPools\IPooled.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ObjectPools\PooledDisposer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ObjectPools\PooledHashSet.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ObjectPools\PooledObject.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ObjectPools\PooledStringBuilder.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ObjectPools\SharedPools.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolDisplayFormats.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolVisibility.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolEquivalenceComparer.AssemblyComparers.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolEquivalenceComparer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolEquivalenceComparer.EquivalenceVisitor.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolEquivalenceComparer.GetHashCodeVisitor.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolEquivalenceComparer.ParameterSymbolEqualityComparer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolEquivalenceComparer.SignatureTypeSymbolEquivalenceComparer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Diagnostics\DiagnosticAnalyzerCategory.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Diagnostics\DiagnosticCategory.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Diagnostics\IBuiltInAnalyzer.cs" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="$(MSBuildThisFileDirectory)CompilerExtensionsResources.resx" GenerateSource="true" Link="CompilerExtensionsResources.resx" /> <None Include="$(MSBuildThisFileDirectory)CompilerExtensionsResources.resx" /> </ItemGroup> <ItemGroup Condition="'$(DefaultLanguageSourceExtension)' != '' AND '$(BuildingInsideVisualStudio)' != 'true'"> <ExpectedCompile Include="$(MSBuildThisFileDirectory)**\*$(DefaultLanguageSourceExtension)" /> </ItemGroup> <ItemGroup> <Folder Include="$(MSBuildThisFileDirectory)Extensions\Compiler\" /> <Folder Include="$(MSBuildThisFileDirectory)Services\FileBannerFacts\" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects> <HasSharedItems>true</HasSharedItems> <SharedGUID>ec946164-1e17-410b-b7d9-7de7e6268d63</SharedGUID> </PropertyGroup> <PropertyGroup Label="Configuration"> <Import_RootNamespace>Microsoft.CodeAnalysis.Shared</Import_RootNamespace> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ConcurrentDictionaryExtensions.cs" Link="InternalUtilities\ConcurrentDictionaryExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ConfiguredYieldAwaitable.cs" Link="InternalUtilities\ConfiguredYieldAwaitable.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\Debug.cs" Link="InternalUtilities\Debug.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\EnumerableExtensions.cs" Link="InternalUtilities\EnumerableExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ExceptionUtilities.cs" Link="InternalUtilities\ExceptionUtilities.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\IReadOnlySet.cs" Link="InternalUtilities\IReadOnlySet.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\KeyValuePairUtil.cs" Link="InternalUtilities\KeyValuePairUtil.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\NonCopyableAttribute.cs" Link="InternalUtilities\NonCopyableAttribute.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\NonDefaultableAttribute.cs" Link="InternalUtilities\NonDefaultableAttribute.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\NullableAttributes.cs" Link="InternalUtilities\NullableAttributes.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ReferenceEqualityComparer.cs" Link="InternalUtilities\ReferenceEqualityComparer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\RoslynString.cs" Link="InternalUtilities\RoslynString.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.cs" Link="InternalUtilities\SpecializedCollections.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SharedStopwatch.cs" Link="InternalUtilities\SharedStopwatch.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.Collection.cs" Link="InternalUtilities\SpecializedCollections.Empty.Collection.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.cs" Link="InternalUtilities\SpecializedCollections.Empty.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.Dictionary.cs" Link="InternalUtilities\SpecializedCollections.Empty.Dictionary.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.Enumerable.cs" Link="InternalUtilities\SpecializedCollections.Empty.Enumerable.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.Enumerator.cs" Link="InternalUtilities\SpecializedCollections.Empty.Enumerator.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.Enumerator`1.cs" Link="InternalUtilities\SpecializedCollections.Empty.Enumerator`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.List.cs" Link="InternalUtilities\SpecializedCollections.Empty.List.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.Set.cs" Link="InternalUtilities\SpecializedCollections.Empty.Set.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.ReadOnly.Collection.cs" Link="InternalUtilities\SpecializedCollections.ReadOnly.Collection.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.ReadOnly.Enumerable`1.cs" Link="InternalUtilities\SpecializedCollections.ReadOnly.Enumerable`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.ReadOnly.Enumerable`2.cs" Link="InternalUtilities\SpecializedCollections.ReadOnly.Enumerable`2.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.ReadOnly.Set.cs" Link="InternalUtilities\SpecializedCollections.ReadOnly.Set.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Singleton.Collection`1.cs" Link="InternalUtilities\SpecializedCollections.Singleton.Collection`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Singleton.Enumerator`1.cs" Link="InternalUtilities\SpecializedCollections.Singleton.Enumerator`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\StringExtensions.cs" Link="InternalUtilities\StringExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ValueTaskFactory.cs" Link="InternalUtilities\ValueTaskFactory.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\VoidResult.cs" Link="InternalUtilities\VoidResult.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\YieldAwaitableExtensions.cs" Link="InternalUtilities\YieldAwaitableExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Syntax\SyntaxTreeExtensions.cs" Link="Syntax\SyntaxTreeExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Collections\ImmutableArrayExtensions.cs" Link="Collections\ImmutableArrayExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Collections\BitVector.cs" Link="Collections\BitVector.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\Hash.cs" Link="InternalUtilities\Hash.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\GeneratedCodeUtilities.cs" Link="InternalUtilities\GeneratedCodeUtilities.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Serialization\IObjectWritable.cs" Link="Serialization\IObjectWritable.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Serialization\ObjectBinder.cs" Link="Serialization\ObjectBinder.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Serialization\ObjectBinderSnapshot.cs" Link="Serialization\ObjectBinderSnapshot.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Serialization\ObjectReader.cs" Link="Serialization\ObjectReader.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Serialization\ObjectWriter.cs" Link="Serialization\ObjectWriter.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Serialization\SerializationThreadPool.cs" Link="Serialization\SerializationThreadPool.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\SourceCodeKindExtensions.cs" Link="Utilities\Compiler\SourceCodeKindExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\SpecialTypeExtensions.cs" Link="Extensions\Compiler\SpecialTypeExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Collections\ArrayBuilderExtensions.cs"> <Link>Collections\ArrayBuilderExtensions.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Collections\DictionaryExtensions.cs"> <Link>Collections\DictionaryExtensions.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Collections\Boxes.cs"> <Link>Collections\Boxes.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Collections\OrderPreservingMultiDictionary.cs"> <Link>Collections\OrderPreservingMultiDictionary.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\EncodedStringText.cs"> <Link>EncodedStringText.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\FileSystem\RelativePathResolver.cs"> <Link>FileSystem\RelativePathResolver.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\AssemblyIdentityUtils.cs"> <Link>InternalUtilities\AssemblyIdentityUtils.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\BitArithmeticUtilities.cs"> <Link>InternalUtilities\BitArithmeticUtilities.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ArrayExtensions.cs"> <Link>InternalUtilities\ArrayExtensions.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\CompilerOptionParseUtilities.cs"> <Link>InternalUtilities\CompilerOptionParseUtilities.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ConcurrentSet.cs"> <Link>InternalUtilities\ConcurrentSet.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ConsList`1.cs"> <Link>InternalUtilities\ConsList`1.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\DecimalUtilities.cs"> <Link>InternalUtilities\DecimalUtilities.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\DocumentationCommentXmlNames.cs"> <Link>InternalUtilities\DocumentationCommentXmlNames.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\EncodingExtensions.cs"> <Link>InternalUtilities\EncodingExtensions.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\EnumUtilties.cs"> <Link>InternalUtilities\EnumUtilties.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\FailFast.cs"> <Link>InternalUtilities\FailFast.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\FatalError.cs"> <Link>InternalUtilities\FatalError.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\FileNameUtilities.cs"> <Link>InternalUtilities\FileNameUtilities.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ImmutableListExtensions.cs"> <Link>InternalUtilities\ImmutableListExtensions.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\Index.cs"> <Link>InternalUtilities\Index.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ISetExtensions.cs"> <Link>InternalUtilities\ISetExtensions.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\MultiDictionary.cs"> <Link>InternalUtilities\MultiDictionary.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\OrderedMultiDictionary.cs"> <Link>InternalUtilities\OrderedMultiDictionary.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SetWithInsertionOrder.cs"> <Link>InternalUtilities\SetWithInsertionOrder.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\FileSystem\PathKind.cs"> <Link>FileSystem\PathKind.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\OneOrMany.cs"> <Link>InternalUtilities\OneOrMany.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\PerformanceSensitiveAttribute.cs" Condition="'$(DotNetBuildFromSource)' == 'true'"> <Link>InternalUtilities\PerformanceSensitiveAttribute.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\PlatformInformation.cs"> <Link>InternalUtilities\PlatformInformation.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\Range.cs"> <Link>InternalUtilities\Range.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ReaderWriterLockSlimExtensions.cs"> <Link>InternalUtilities\ReaderWriterLockSlimExtensions.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SemaphoreSlimExtensions.cs"> <Link>InternalUtilities\SemaphoreSlimExtensions.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\StackGuard.cs"> <Link>InternalUtilities\StackGuard.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\StreamExtensions.cs"> <Link>InternalUtilities\StreamExtensions.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\StringTable.cs" Link="InternalUtilities\StringTable.cs" /> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\TextChangeRangeExtensions.cs"> <Link>InternalUtilities\TextChangeRangeExtensions.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\WeakReferenceExtensions.cs"> <Link>InternalUtilities\WeakReferenceExtensions.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\FileSystem\FileUtilities.cs"> <Link>FileSystem\FileUtilities.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\FileSystem\PathUtilities.cs"> <Link>FileSystem\PathUtilities.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ReflectionUtilities.cs"> <Link>InternalUtilities\ReflectionUtilities.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\UnicodeCharacterUtilities.cs"> <Link>InternalUtilities\UnicodeCharacterUtilities.cs</Link> </Compile> <Compile Include="$(MSBuildThisFileDirectory)CodeActions\CodeActionRequestPriority.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\AccessibilityModifiersRequired.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\AddImportPlacement.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\CodeStyleHelpers.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\CodeStyleOption2`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\CodeStyleOptions2.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\EditorConfigSeverityStrings.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\ExpressionBodyPreference.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\NamespaceDeclarationPreference.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\NotificationOption2.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\OperatorPlacementWhenWrappingPreference.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\ParenthesesPreference.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Collections\TemporaryArrayExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Collections\TemporaryArray`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Diagnostics\IPragmaSuppressionsAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedDiagnostic.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedSyntaxHelpers.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedSyntaxNode.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedSyntaxNodeOrToken.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedSyntaxToken.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedSyntaxTree.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedSyntaxTrivia.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\VirtualChars\AbstractVirtualCharService.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\VirtualChars\IVirtualCharService.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\VirtualChars\VirtualChar.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\VirtualChars\VirtualCharSequence.Chunks.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\VirtualChars\VirtualCharSequence.cs" /> <Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\VirtualChars\VirtualCharSequence.Enumerator.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\CompilationExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\DiagnosticAnalyzerExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\DiagnosticDescriptorExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ListExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ObjectWriterExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\FeatureFlagStorageLocation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\HeaderFacts\IHeaderFactsExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\Precedence\IPrecedenceService.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\Precedence\PrecedenceKind.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\UnusedParametersPreference.cs" /> <Compile Include="$(MSBuildThisFileDirectory)CodeStyle\UnusedValuePreference.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Collections\IIntervalIntrospector.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Collections\IntervalTree`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Collections\IntervalTree`1.Node.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Collections\NormalizedTextSpanCollection.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Collections\SimpleIntervalTree.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Collections\SimpleIntervalTree`2.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Collections\TextSpanIntervalIntrospector.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Editing\GenerationOptions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\AnalyzerConfigOptionsExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ChildSyntaxListExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\DiagnosticSeverityExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\NotificationOptionExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ObjectExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ObjectExtensions.TypeSwitch.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ReportDiagnosticExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ImmutableArrayExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\LinkedListExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\LocationExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ParenthesizedExpressionSyntaxExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Fading\FadingOptions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\CustomDataFlowAnalysis.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\DataFlowAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\FlowCaptureKind.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\LValueFlowCaptureProvider.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.AnalysisData.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.BasicBlockAnalysisData.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.DataFlowAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.DataFlowAnalyzer.FlowGraphAnalysisData.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.OperationTreeAnalysisData.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.Walker.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageResult.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\AbstractSyntaxFormattingService.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\BottomUpBaseIndentationFinder.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\ContextIntervalTree.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\FormattingContext.AnchorData.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\FormattingContext.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\FormattingContext.IndentationData.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\FormattingContext.InitialContextFinder.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\SuppressIntervalIntrospector.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\SuppressSpacingData.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\SuppressWrappingData.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractAggregatedFormattingResult.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractFormatEngine.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractFormatEngine.OperationApplier.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractFormattingResult.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractTriviaDataFactory.AbstractComplexTrivia.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractTriviaDataFactory.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractTriviaDataFactory.FormattedWhitespace.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractTriviaDataFactory.ModifiedWhitespace.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractTriviaDataFactory.Whitespace.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\ChainedFormattingRules.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\NodeOperations.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TokenData.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TokenPairWithOperations.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TokenStream.Changes.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TokenStream.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TokenStream.Iterator.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TreeData.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TreeData.Debug.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TreeData.Node.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TreeData.NodeAndText.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TreeData.StructuredTrivia.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TriviaData.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TriviaDataWithList.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\FormattingDiagnosticIds.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\FormattingExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\FormattingOptions.IndentStyle.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\FormattingOptions2.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\IFormattingResult.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\ISyntaxFormattingService.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\AbstractFormattingRule.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\BaseIndentationFormattingRule.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\CompatAbstractFormattingRule.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NextAlignTokensOperationAction.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NextAnchorIndentationOperationAction.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NextGetAdjustNewLinesOperation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NextGetAdjustSpacesOperation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NextIndentBlockOperationAction.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NextSuppressOperationAction.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NoOpFormattingRule.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AdjustNewLinesOperation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AdjustNewLinesOption.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AdjustSpacesOperation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AdjustSpacesOption.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AlignTokensOperation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AlignTokensOption.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AnchorIndentationOperation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\FormattingOperations.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\IndentBlockOperation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\IndentBlockOption.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\SuppressOperation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\SuppressOption.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\StringBuilderPool.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\TriviaEngine\AbstractTriviaFormatter.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\TriviaEngine\LineColumn.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\TriviaEngine\LineColumnDelta.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\TriviaEngine\LineColumnRule.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\TriviaEngine\TriviaHelpers.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Formatting\TriviaEngine\TriviaList.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Helpers\RemoveUnnecessaryImports\IUnnecessaryImportsProvider.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Helpers\RemoveUnnecessaryImports\AbstractUnnecessaryImportsProvider.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Log\EmptyLogBlock.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Log\FunctionId.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Log\FunctionIdOptions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Log\ILogger.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Log\Logger.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Log\LogLevel.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Log\Logger.LogBlock.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Log\LogMessage.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\Capitalization.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\EditorConfig\EditorConfigNamingStyleParser.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\EditorConfig\EditorConfigNamingStyleParser_NamingRule.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\EditorConfig\EditorConfigNamingStyleParser_NamingStyle.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\EditorConfig\EditorConfigNamingStyleParser_SymbolSpec.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\NamingRule.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\NamingStyle.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\NamingStyle.WordSpanEnumerable.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\NamingStyle.WordSpanEnumerator.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\NamingStyleOptions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\NamingStyleRules.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\Serialization\AccessibilityExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\Serialization\MutableNamingStyle.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\Serialization\NamingStylePreferences.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\Serialization\SerializableNamingRule.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyles\Serialization\SymbolSpecification.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ObjectPools\PooledDictionary.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfig\EditorConfigStorageLocation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfig\EditorConfigStorageLocationExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfig\EditorConfigStorageLocation`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfig\IEditorConfigStorageLocation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfig\IEditorConfigStorageLocation2.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfig\NamingStylePreferenceEditorConfigStorageLocation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\IOption2.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\IOptionWithGroup.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\LocalUserProfileStorageLocation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\OptionGroup.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\OptionDefinition.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\OptionKey2.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\OptionStorageLocation2.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\Option2`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\PerLanguageOption2.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Options\RoamingProfileStorageLocation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\SelectedMembers\AbstractSelectedMembers.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\SemanticFacts\ForEachSymbols.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\AbstractDocumentationCommentService.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\FileBannerFacts\AbstractFileBannerFacts.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\HeaderFacts\AbstractHeaderFacts.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\ExternalSourceInfo.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\IAccessibilityFacts.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\IDocumentationCommentService.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\SemanticFacts\ISemanticFacts.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\FileBannerFacts\IFileBannerFacts.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\FileBannerFacts\IFileBannerFactsExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\HeaderFacts\IHeaderFacts.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\ISyntaxFacts.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\ISyntaxFactsExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\ISyntaxKinds.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Simplification\AliasAnnotation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Simplification\DoNotAddImportsAnnotation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Simplification\DoNotAllowVarAnnotation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Simplification\SpecialTypeAnnotation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Simplification\SymbolAnnotation.cs" /> <Compile Include="$(MSBuildThisFileDirectory)System.Text\Rune.cs" /> <Compile Include="$(MSBuildThisFileDirectory)System.Text\UnicodeDebug.cs" /> <Compile Include="$(MSBuildThisFileDirectory)System.Text\UnicodeUtility.cs" /> <Compile Include="$(MSBuildThisFileDirectory)System.Text\Utf16Utility.cs" /> <Compile Include="$(MSBuildThisFileDirectory)TestHooks\IExpeditableDelaySource.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\AbstractSpeculationAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\AliasSymbolCache.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\AnnotationTable.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\AsyncLazy`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\BidirectionalMap.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\BKTree.Builder.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\BKTree.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\BKTree.Edge.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\BKTree.Node.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\BKTree.Serialization.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\CancellableLazy.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\CancellableLazy`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\CommonFormattingHelpers.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\ComparerWithState.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\Contract.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\PathMetadataUtilities.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\PublicContract.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\EditDistance.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\EditorConfigFileGenerator_NamingStyles.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\EventMap.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\IBidirectionalMap.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\ICacheEntry.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\ICollectionExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\IDictionaryExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\IGroupingExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\IntegerUtilities.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\IReadOnlyDictionaryExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\IReadOnlyListExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\IReferenceCountedDisposable.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\LazyInitialization.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\Matcher.ChoiceMatcher.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\Matcher.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\Matcher.RepeatMatcher.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\Matcher.SequenceMatcher.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\Matcher.SingleMatcher.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\Matcher`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\NonReentrantLock.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\PooledBuilderExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\PredefinedOperator.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\PredefinedType.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\PredefinedTypeExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SemanticModelExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SimpleIntervalTreeExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SourceTextExtensions_SharedWithCodeStyle.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SpecialTypeExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\StringExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SymbolDisplayPartExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxNodeExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxNodeOrTokenExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxTokenExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxTokenListExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxTreeExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxTriviaExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxTriviaListExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\TextLineExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\TextSpanExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\CompilerUtilities\CompilerPathUtilities.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\CompilerUtilities\ImmutableDictionaryExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\CompilerUtilities\ImmutableHashMap.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\CompilerUtilities\ImmutableHashMapExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\ConcatImmutableArray`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\ReferenceCountedDisposable.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\ReferenceCountedDisposableCache.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\RestrictedInternalsVisibleToAttribute.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SemaphoreSlimFactory.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SerializableBytes.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SoftCrashException.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SpecializedTasks.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\StringBreaker.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\WordSimilarityChecker.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\StringEscapeEncoder.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\StringSlice.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SyntaxPath.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\TaskExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\TaskFactoryExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\TopologicalSorter.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\ValuesSources\ConstantValueSource.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\ValuesSources\ValueSource.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\ValuesSources\WeaklyCachedRecoverableValueSource.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\ValuesSources\WeaklyCachedValueSource.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\ValuesSources\WeakValueSource.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\WeakEventHandler.cs" /> </ItemGroup> <ItemGroup> <Compile Include="$(MSBuildThisFileDirectory)Extensions\AccessibilityUtilities.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\BasicBlockExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ControlFlowGraphExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ControlFlowRegionExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\IAssemblySymbolExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ICollectionExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ICompilationExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\IMethodSymbolExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\INamedTypeSymbolExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\INamespaceOrTypeSymbolExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\IParameterSymbolExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ISymbolExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ISymbolExtensions.RequiresUnsafeModifierVisitor.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ISymbolExtensions_Accessibility.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ITypeSymbolExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ITypeSymbolExtensions.MinimalAccessibilityVisitor.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\MethodKindExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\OperationExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\StackExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SymbolInfoExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\SymbolUsageInfo.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\TypeOrNamespaceUsageInfo.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\ValueUsageInfo.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ObjectPools\ArrayBuilder.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ObjectPools\Extensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ObjectPools\IPooled.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ObjectPools\PooledDisposer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ObjectPools\PooledHashSet.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ObjectPools\PooledObject.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ObjectPools\PooledStringBuilder.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ObjectPools\SharedPools.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolDisplayFormats.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolVisibility.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolEquivalenceComparer.AssemblyComparers.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolEquivalenceComparer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolEquivalenceComparer.EquivalenceVisitor.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolEquivalenceComparer.GetHashCodeVisitor.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolEquivalenceComparer.ParameterSymbolEqualityComparer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolEquivalenceComparer.SignatureTypeSymbolEquivalenceComparer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Diagnostics\DiagnosticAnalyzerCategory.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Diagnostics\DiagnosticCategory.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Diagnostics\IBuiltInAnalyzer.cs" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="$(MSBuildThisFileDirectory)CompilerExtensionsResources.resx" GenerateSource="true" Link="CompilerExtensionsResources.resx" /> <None Include="$(MSBuildThisFileDirectory)CompilerExtensionsResources.resx" /> </ItemGroup> <ItemGroup Condition="'$(DefaultLanguageSourceExtension)' != '' AND '$(BuildingInsideVisualStudio)' != 'true'"> <ExpectedCompile Include="$(MSBuildThisFileDirectory)**\*$(DefaultLanguageSourceExtension)" /> </ItemGroup> <ItemGroup> <Folder Include="$(MSBuildThisFileDirectory)Extensions\Compiler\" /> <Folder Include="$(MSBuildThisFileDirectory)Services\FileBannerFacts\" /> </ItemGroup> </Project>
1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ISyntaxFacts.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.Text; #if CODE_STYLE using Microsoft.CodeAnalysis.Internal.Editing; #else using Microsoft.CodeAnalysis.Editing; #endif namespace Microsoft.CodeAnalysis.LanguageServices { /// <summary> /// Contains helpers to allow features and other algorithms to run over C# and Visual Basic code in a uniform fashion. /// It should be thought of a generalized way to apply type-pattern-matching and syntax-deconstruction in a uniform /// fashion over the languages. Helpers in this type should only be one of the following forms: /// <list type="bullet"> /// <item> /// 'IsXXX' where 'XXX' exactly matches one of the same named syntax (node, token, trivia, list, etc.) constructs that /// both C# and VB have. For example 'IsSimpleName' to correspond to C# and VB's SimpleNameSyntax node. These 'checking' /// methods should never fail. For non leaf node types this should be implemented as a typecheck ('is' in C#, 'typeof ... is' /// in VB). For leaf nodes, this should be implemented by deffering to <see cref="ISyntaxKinds"/> to check against the /// raw kind of the node. /// </item> /// <item> /// 'GetPartsOfXXX(SyntaxNode node, out SyntaxNode/SyntaxToken part1, ...)' where 'XXX' one of the same named Syntax constructs /// that both C# and VB have, and where the returned parts correspond to the members those nodes have in common across the /// languages. For example 'GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken dotToken, out SyntaxNode right)' /// VB. These functions should throw if passed a node that the corresponding 'IsXXX' did not return <see langword="true"/> for. /// For nodes that only have a single child, 'GetPartsOfXXX' is not not needed and can be replaced with the easier to use /// 'GetXXXOfYYY' to get that single child. /// </item> /// <item> /// 'GetXxxOfYYY' where 'XXX' matches the name of a property on a 'YYY' syntax construct that both C# and VB have. For /// example 'GetExpressionOfMemberAccessExpression' corresponding to MemberAccessExpressionsyntax.Expression in both C# and /// VB. These functions should throw if passed a node that the corresponding 'IsYYY' did not return <see langword="true"/> for. /// For nodes that only have a single child, these functions can stay here. For nodes with multiple children, these should migrate /// to <see cref="ISyntaxFactsExtensions"/> and be built off of 'GetPartsOfXXX'. /// </item> /// <item> /// Absolutely trivial questions that relate to syntax and can be asked sensibly of each language. For example, /// if certain constructs (like 'patterns') are supported in that language or not. /// </item> /// </list> /// /// <para>Importantly, avoid:</para> /// /// <list type="bullet"> /// <item> /// Functions that attempt to blur the lines between similar constructs in the same language. For example, a QualifiedName /// is not the same as a MemberAccessExpression (despite A.B being representable as either depending on context). /// Features that need to handle both should make it clear that they are doing so, showing that they're doing the right /// thing for the contexts each can arise in (for the above example in 'type' vs 'expression' contexts). /// </item> /// <item> /// Functions which are effectively specific to a single feature are are just trying to find a place to place complex /// feature logic in a place such that it can run over VB or C#. For example, a function to determine if a position /// is on the 'header' of a node. a 'header' is a not a well defined syntax concept that can be trivially asked of /// nodes in either language. It is an excapsulation of a feature (or set of features) level idea that should be in /// its own dedicated service. /// </item> /// <item> /// Functions that mutate or update syntax constructs for example 'WithXXX'. These should be on SyntaxGenerator or /// some other feature specific service. /// </item> /// <item> /// Functions that a single item when one language may allow for multiple. For example 'GetIdentifierOfVariableDeclarator'. /// In VB a VariableDeclarator can itself have several names, so calling code must be written to check for that and handle /// it apropriately. Functions like this make it seem like that doesn't need to be considered, easily allowing for bugs /// to creep in. /// </item> /// <item> /// Abbreviating or otherwise changing the names that C# and VB share here. For example use 'ObjectCreationExpression' /// not 'ObjectCreation'. This prevents accidental duplication and keeps consistency with all members. /// </item> /// </list> /// </summary> /// <remarks> /// Many helpers in this type currently violate the above 'dos' and 'do nots'. They should be removed and either /// inlined directly into the feature that needs if (if only a single feature), or moved into a dedicated service /// for that purpose if needed by multiple features. /// </remarks> internal interface ISyntaxFacts { bool IsCaseSensitive { get; } StringComparer StringComparer { get; } SyntaxTrivia ElasticMarker { get; } SyntaxTrivia ElasticCarriageReturnLineFeed { get; } ISyntaxKinds SyntaxKinds { get; } bool SupportsIndexingInitializer(ParseOptions options); bool SupportsLocalFunctionDeclaration(ParseOptions options); bool SupportsNotPattern(ParseOptions options); bool SupportsRecord(ParseOptions options); bool SupportsRecordStruct(ParseOptions options); bool SupportsThrowExpression(ParseOptions options); SyntaxToken ParseToken(string text); SyntaxTriviaList ParseLeadingTrivia(string text); string EscapeIdentifier(string identifier); bool IsVerbatimIdentifier(SyntaxToken token); bool IsOperator(SyntaxToken token); bool IsPredefinedType(SyntaxToken token); bool IsPredefinedType(SyntaxToken token, PredefinedType type); bool IsPredefinedOperator(SyntaxToken token); bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op); /// <summary> /// Returns 'true' if this a 'reserved' keyword for the language. A 'reserved' keyword is a /// identifier that is always treated as being a special keyword, regardless of where it is /// found in the token stream. Examples of this are tokens like <see langword="class"/> and /// <see langword="Class"/> in C# and VB respectively. /// /// Importantly, this does *not* include contextual keywords. If contextual keywords are /// important for your scenario, use <see cref="IsContextualKeyword"/> or <see /// cref="ISyntaxFactsExtensions.IsReservedOrContextualKeyword"/>. Also, consider using /// <see cref="ISyntaxFactsExtensions.IsWord"/> if all you need is the ability to know /// if this is effectively any identifier in the language, regardless of whether the language /// is treating it as a keyword or not. /// </summary> bool IsReservedKeyword(SyntaxToken token); /// <summary> /// Returns <see langword="true"/> if this a 'contextual' keyword for the language. A /// 'contextual' keyword is a identifier that is only treated as being a special keyword in /// certain *syntactic* contexts. Examples of this is 'yield' in C#. This is only a /// keyword if used as 'yield return' or 'yield break'. Importantly, identifiers like <see /// langword="var"/>, <see langword="dynamic"/> and <see langword="nameof"/> are *not* /// 'contextual' keywords. This is because they are not treated as keywords depending on /// the syntactic context around them. Instead, the language always treats them identifiers /// that have special *semantic* meaning if they end up not binding to an existing symbol. /// /// Importantly, if <paramref name="token"/> is not in the syntactic construct where the /// language thinks an identifier should be contextually treated as a keyword, then this /// will return <see langword="false"/>. /// /// Or, in other words, the parser must be able to identify these cases in order to be a /// contextual keyword. If identification happens afterwards, it's not contextual. /// </summary> bool IsContextualKeyword(SyntaxToken token); /// <summary> /// The set of identifiers that have special meaning directly after the `#` token in a /// preprocessor directive. For example `if` or `pragma`. /// </summary> bool IsPreprocessorKeyword(SyntaxToken token); bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken); bool IsLiteral(SyntaxToken token); bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token); bool IsNumericLiteral(SyntaxToken token); bool IsVerbatimStringLiteral(SyntaxToken token); bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node); bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node); bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node); bool IsDeclaration(SyntaxNode node); bool IsTypeDeclaration(SyntaxNode node); bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node); bool IsRegularComment(SyntaxTrivia trivia); bool IsDocumentationComment(SyntaxTrivia trivia); bool IsElastic(SyntaxTrivia trivia); bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes); bool IsSingleLineCommentTrivia(SyntaxTrivia trivia); bool IsMultiLineCommentTrivia(SyntaxTrivia trivia); bool IsSingleLineDocCommentTrivia(SyntaxTrivia trivia); bool IsMultiLineDocCommentTrivia(SyntaxTrivia trivia); bool IsShebangDirectiveTrivia(SyntaxTrivia trivia); bool IsPreprocessorDirective(SyntaxTrivia trivia); bool IsDocumentationComment(SyntaxNode node); string GetText(int kind); bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken); bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type); bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op); bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? directive, out ExternalSourceInfo info); bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node); bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node); bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node); bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node); bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node); bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node, out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode; void GetPartsOfInterpolationExpression(SyntaxNode node, out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken); bool IsVerbatimInterpolatedStringExpression(SyntaxNode node); // Left side of = assignment. bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node); bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement); void GetPartsOfAssignmentStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); void GetPartsOfAssignmentExpressionOrStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); // Left side of any assignment (for example = or ??= or *= or += ) bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node); // Left side of compound assignment (for example ??= or *= or += ) bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetRightHandSideOfAssignment(SyntaxNode node); bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node); bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node); bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node); bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetRightSideOfDot(SyntaxNode? node); /// <summary> /// Get the node on the left side of the dot if given a dotted expression. /// </summary> /// <param name="allowImplicitTarget"> /// In VB, we have a member access expression with a null expression, this may be one of the /// following forms: /// 1) new With { .a = 1, .b = .a .a refers to the anonymous type /// 2) With obj : .m .m refers to the obj type /// 3) new T() With { .a = 1, .b = .a 'a refers to the T type /// If `allowImplicitTarget` is set to true, the returned node will be set to approperiate node, otherwise, it will return null. /// This parameter has no affect on C# node. /// </param> SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget = false); bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// Gets the containing expression that is actually a language expression and not just typed /// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side /// of qualified names and member access expressions are not language expressions, yet the /// containing qualified names or member access expressions are indeed expressions. /// </summary> [return: NotNullIfNotNull("node")] SyntaxNode? GetStandaloneExpression(SyntaxNode? node); /// <summary> /// Call on the `.y` part of a `x?.y` to get the entire `x?.y` conditional access expression. This also works /// when there are multiple chained conditional accesses. For example, calling this on '.y' or '.z' in /// `x?.y?.z` will both return the full `x?.y?.z` node. This can be used to effectively get 'out' of the RHS of /// a conditional access, and commonly represents the full standalone expression that can be operated on /// atomically. /// </summary> SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node); /// <summary> /// Returns the expression node the member is being accessed off of. If <paramref name="allowImplicitTarget"/> /// is <see langword="false"/>, this will be the node directly to the left of the dot-token. If <paramref name="allowImplicitTarget"/> /// is <see langword="true"/>, then this can return another node in the tree that the member will be accessed /// off of. For example, in VB, if you have a member-access-expression of the form ".Length" then this /// may return the expression in the surrounding With-statement. /// </summary> SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode node, bool allowImplicitTarget = false); SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node); SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node); bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node); SyntaxToken? GetNameOfParameter([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetDefaultOfParameter(SyntaxNode node); SyntaxNode? GetParameterList(SyntaxNode node); bool IsParameterList([NotNullWhen(true)] SyntaxNode? node); bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia); void GetPartsOfElementAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList); SyntaxNode GetExpressionOfArgument(SyntaxNode node); SyntaxNode GetExpressionOfInterpolation(SyntaxNode node); SyntaxNode GetNameOfAttribute(SyntaxNode node); bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node); bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node); SyntaxToken GetIdentifierOfGenericName(SyntaxNode node); SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node); SyntaxToken GetIdentifierOfParameter(SyntaxNode node); SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node); SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node); SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node); SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node); /// <summary> /// True if this is an argument with just an expression and nothing else (i.e. no ref/out, /// no named params, no omitted args). /// </summary> bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node); bool IsArgument([NotNullWhen(true)] SyntaxNode? node); RefKind GetRefKindOfArgument(SyntaxNode node); void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity); bool LooksGeneric(SyntaxNode simpleName); SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode node); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode node); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode node); bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node); bool IsAttributeName(SyntaxNode node); // Violation. Doesn't correspond to any shared structure for vb/c# SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node); bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node); 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); bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node); bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node); bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// Returns true for nodes that represent the body of a method. /// /// For VB this will be /// MethodBlockBaseSyntax. This will be true for things like constructor, method, operator /// bodies as well as accessor bodies. It will not be true for things like sub() function() /// lambdas. /// /// For C# this will be the BlockSyntax or ArrowExpressionSyntax for a /// method/constructor/deconstructor/operator/accessor. It will not be included for local /// functions. /// </summary> bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node); bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement); SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node); SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node); bool IsThisConstructorInitializer(SyntaxToken token); bool IsBaseConstructorInitializer(SyntaxToken token); bool IsQueryKeyword(SyntaxToken token); bool IsElementAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsIndexerMemberCRef([NotNullWhen(true)] SyntaxNode? node); bool IsIdentifierStartCharacter(char c); bool IsIdentifierPartCharacter(char c); bool IsIdentifierEscapeCharacter(char c); bool IsStartOfUnicodeEscapeSequence(char c); bool IsValidIdentifier(string identifier); bool IsVerbatimIdentifier(string identifier); /// <summary> /// Returns true if the given character is a character which may be included in an /// identifier to specify the type of a variable. /// </summary> bool IsTypeCharacter(char c); // Violation. This is a feature level API for QuickInfo. bool IsBindableToken(SyntaxToken token); bool IsInStaticContext(SyntaxNode node); bool IsUnsafeContext(SyntaxNode node); bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node); bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node); bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node); bool IsInConstructor(SyntaxNode node); bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node); bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node); bool HasIncompleteParentMember([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// A block that has no semantics other than introducing a new scope. That is only C# BlockSyntax. /// </summary> bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// A node that contains a list of statements. In C#, this is BlockSyntax and SwitchSectionSyntax. /// In VB, this includes all block statements such as a MultiLineIfBlockSyntax. /// </summary> bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node); // Violation. This should return a SyntaxList IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node); // Violation. This is a feature level API. SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes); /// <summary> /// A node that can host a list of statements or a single statement. In addition to /// every "executable block", this also includes C# embedded statement owners. /// </summary> // Violation. This is a feature level API. bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node); // Violation. This is a feature level API. IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node); bool AreEquivalent(SyntaxToken token1, SyntaxToken token2); bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2); string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null); // Violation. This is a feature level API. How 'position' relates to 'containment' is not defined. SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position); SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true); SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node); [return: NotNullIfNotNull("node")] SyntaxNode? WalkDownParentheses(SyntaxNode? node); // Violation. This is a feature level API. [return: NotNullIfNotNull("node")] SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false); // Violation. This is a feature level API. List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root); // Violation. This is a feature level API. List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root); SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration); // Violation. This is a feature level API. bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span); // Violation. This is a feature level API. TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree tree, int position, CancellationToken cancellationToken); /// <summary> /// Given a <see cref="SyntaxNode"/>, return the <see cref="TextSpan"/> representing the span of the member body /// it is contained within. This <see cref="TextSpan"/> is used to determine whether speculative binding should be /// used in performance-critical typing scenarios. Note: if this method fails to find a relevant span, it returns /// an empty <see cref="TextSpan"/> at position 0. /// </summary> // Violation. This is a feature level API. TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node); /// <summary> /// Returns the parent node that binds to the symbols that the IDE prefers for features like Quick Info and Find /// All References. For example, if the token is part of the type of an object creation, the parenting object /// creation expression is returned so that binding will return constructor symbols. /// </summary> // Violation. This is a feature level API. SyntaxNode? TryGetBindableParent(SyntaxToken token); // Violation. This is a feature level API. IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken); // Violation. This is a feature level API. bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace); /// <summary> /// Given a <see cref="SyntaxNode"/>, that represents and argument return the string representation of /// that arguments name. /// </summary> // Violation. This is a feature level API. string GetNameForArgument(SyntaxNode? argument); /// <summary> /// Given a <see cref="SyntaxNode"/>, that represents an attribute argument return the string representation of /// that arguments name. /// </summary> // Violation. This is a feature level API. string GetNameForAttributeArgument(SyntaxNode? argument); bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node); bool IsPropertyPatternClause(SyntaxNode node); bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node); bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node); bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node); bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node); bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node); bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node); bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node); bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node); bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node); bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node); bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node); bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node); SyntaxNode GetTypeOfTypePattern(SyntaxNode node); void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen); void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation); void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation); void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern); bool ContainsInterleavedDirective(SyntaxNode node, CancellationToken cancellationToken); bool ContainsInterleavedDirective(ImmutableArray<SyntaxNode> nodes, CancellationToken cancellationToken); SyntaxTokenList GetModifiers(SyntaxNode? node); // Violation. WithXXX methods should not be here, but should be in SyntaxGenerator. [return: NotNullIfNotNull("node")] SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers); // Violation. This is a feature level API. Location GetDeconstructionReferenceLocation(SyntaxNode node); // Violation. This is a feature level API. SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token); bool SpansPreprocessorDirective(IEnumerable<SyntaxNode> nodes); bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node); SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia); #region IsXXX members bool IsAnonymousFunctionExpression([NotNullWhen(true)] SyntaxNode? node); bool IsBaseNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node); bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node); bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node); bool IsMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsSimpleName([NotNullWhen(true)] SyntaxNode? node); #endregion #region GetPartsOfXXX members void GetPartsOfBaseNamespaceDeclaration(SyntaxNode node, out SyntaxNode name, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> members); void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression); void GetPartsOfCompilationUnit(SyntaxNode node, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> attributeLists, out SyntaxList<SyntaxNode> members); void GetPartsOfConditionalAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull); void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse); void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode? argumentList); void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right); void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name); void GetPartsOfObjectCreationExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode? argumentList, out SyntaxNode? initializer); void GetPartsOfParenthesizedExpression(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen); void GetPartsOfPrefixUnaryExpression(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode operand); void GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken dotToken, out SyntaxNode right); void GetPartsOfUsingAliasDirective(SyntaxNode node, out SyntaxToken globalKeyword, out SyntaxToken alias, out SyntaxNode name); #endregion #region GetXXXOfYYYMembers // note: this is only for nodes that have a single child nodes. If a node has multiple child nodes, then // ISyntaxFacts should have a GetPartsOfXXX helper instead, and GetXXXOfYYY should be built off of that // inside ISyntaxFactsExtensions SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node); SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node); SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode node); SyntaxNode GetExpressionOfThrowExpression(SyntaxNode node); SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node); #endregion } [Flags] internal enum DisplayNameOptions { None = 0, IncludeMemberKeyword = 1, IncludeNamespaces = 1 << 1, IncludeParameters = 1 << 2, IncludeType = 1 << 3, IncludeTypeParameters = 1 << 4 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.Text; #if CODE_STYLE using Microsoft.CodeAnalysis.Internal.Editing; #else using Microsoft.CodeAnalysis.Editing; #endif namespace Microsoft.CodeAnalysis.LanguageServices { /// <summary> /// Contains helpers to allow features and other algorithms to run over C# and Visual Basic code in a uniform fashion. /// It should be thought of a generalized way to apply type-pattern-matching and syntax-deconstruction in a uniform /// fashion over the languages. Helpers in this type should only be one of the following forms: /// <list type="bullet"> /// <item> /// 'IsXXX' where 'XXX' exactly matches one of the same named syntax (node, token, trivia, list, etc.) constructs that /// both C# and VB have. For example 'IsSimpleName' to correspond to C# and VB's SimpleNameSyntax node. These 'checking' /// methods should never fail. For non leaf node types this should be implemented as a typecheck ('is' in C#, 'typeof ... is' /// in VB). For leaf nodes, this should be implemented by deffering to <see cref="ISyntaxKinds"/> to check against the /// raw kind of the node. /// </item> /// <item> /// 'GetPartsOfXXX(SyntaxNode node, out SyntaxNode/SyntaxToken part1, ...)' where 'XXX' one of the same named Syntax constructs /// that both C# and VB have, and where the returned parts correspond to the members those nodes have in common across the /// languages. For example 'GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken dotToken, out SyntaxNode right)' /// VB. These functions should throw if passed a node that the corresponding 'IsXXX' did not return <see langword="true"/> for. /// For nodes that only have a single child, 'GetPartsOfXXX' is not not needed and can be replaced with the easier to use /// 'GetXXXOfYYY' to get that single child. /// </item> /// <item> /// 'GetXxxOfYYY' where 'XXX' matches the name of a property on a 'YYY' syntax construct that both C# and VB have. For /// example 'GetExpressionOfMemberAccessExpression' corresponding to MemberAccessExpressionsyntax.Expression in both C# and /// VB. These functions should throw if passed a node that the corresponding 'IsYYY' did not return <see langword="true"/> for. /// For nodes that only have a single child, these functions can stay here. For nodes with multiple children, these should migrate /// to <see cref="ISyntaxFactsExtensions"/> and be built off of 'GetPartsOfXXX'. /// </item> /// <item> /// Absolutely trivial questions that relate to syntax and can be asked sensibly of each language. For example, /// if certain constructs (like 'patterns') are supported in that language or not. /// </item> /// </list> /// /// <para>Importantly, avoid:</para> /// /// <list type="bullet"> /// <item> /// Functions that attempt to blur the lines between similar constructs in the same language. For example, a QualifiedName /// is not the same as a MemberAccessExpression (despite A.B being representable as either depending on context). /// Features that need to handle both should make it clear that they are doing so, showing that they're doing the right /// thing for the contexts each can arise in (for the above example in 'type' vs 'expression' contexts). /// </item> /// <item> /// Functions which are effectively specific to a single feature are are just trying to find a place to place complex /// feature logic in a place such that it can run over VB or C#. For example, a function to determine if a position /// is on the 'header' of a node. a 'header' is a not a well defined syntax concept that can be trivially asked of /// nodes in either language. It is an excapsulation of a feature (or set of features) level idea that should be in /// its own dedicated service. /// </item> /// <item> /// Functions that mutate or update syntax constructs for example 'WithXXX'. These should be on SyntaxGenerator or /// some other feature specific service. /// </item> /// <item> /// Functions that a single item when one language may allow for multiple. For example 'GetIdentifierOfVariableDeclarator'. /// In VB a VariableDeclarator can itself have several names, so calling code must be written to check for that and handle /// it apropriately. Functions like this make it seem like that doesn't need to be considered, easily allowing for bugs /// to creep in. /// </item> /// <item> /// Abbreviating or otherwise changing the names that C# and VB share here. For example use 'ObjectCreationExpression' /// not 'ObjectCreation'. This prevents accidental duplication and keeps consistency with all members. /// </item> /// </list> /// </summary> /// <remarks> /// Many helpers in this type currently violate the above 'dos' and 'do nots'. They should be removed and either /// inlined directly into the feature that needs if (if only a single feature), or moved into a dedicated service /// for that purpose if needed by multiple features. /// </remarks> internal interface ISyntaxFacts { bool IsCaseSensitive { get; } StringComparer StringComparer { get; } SyntaxTrivia ElasticMarker { get; } SyntaxTrivia ElasticCarriageReturnLineFeed { get; } ISyntaxKinds SyntaxKinds { get; } bool SupportsIndexingInitializer(ParseOptions options); bool SupportsLocalFunctionDeclaration(ParseOptions options); bool SupportsNotPattern(ParseOptions options); bool SupportsRecord(ParseOptions options); bool SupportsRecordStruct(ParseOptions options); bool SupportsThrowExpression(ParseOptions options); SyntaxToken ParseToken(string text); SyntaxTriviaList ParseLeadingTrivia(string text); string EscapeIdentifier(string identifier); bool IsVerbatimIdentifier(SyntaxToken token); bool IsOperator(SyntaxToken token); bool IsPredefinedType(SyntaxToken token); bool IsPredefinedType(SyntaxToken token, PredefinedType type); bool IsPredefinedOperator(SyntaxToken token); bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op); /// <summary> /// Returns 'true' if this a 'reserved' keyword for the language. A 'reserved' keyword is a /// identifier that is always treated as being a special keyword, regardless of where it is /// found in the token stream. Examples of this are tokens like <see langword="class"/> and /// <see langword="Class"/> in C# and VB respectively. /// /// Importantly, this does *not* include contextual keywords. If contextual keywords are /// important for your scenario, use <see cref="IsContextualKeyword"/> or <see /// cref="ISyntaxFactsExtensions.IsReservedOrContextualKeyword"/>. Also, consider using /// <see cref="ISyntaxFactsExtensions.IsWord"/> if all you need is the ability to know /// if this is effectively any identifier in the language, regardless of whether the language /// is treating it as a keyword or not. /// </summary> bool IsReservedKeyword(SyntaxToken token); /// <summary> /// Returns <see langword="true"/> if this a 'contextual' keyword for the language. A /// 'contextual' keyword is a identifier that is only treated as being a special keyword in /// certain *syntactic* contexts. Examples of this is 'yield' in C#. This is only a /// keyword if used as 'yield return' or 'yield break'. Importantly, identifiers like <see /// langword="var"/>, <see langword="dynamic"/> and <see langword="nameof"/> are *not* /// 'contextual' keywords. This is because they are not treated as keywords depending on /// the syntactic context around them. Instead, the language always treats them identifiers /// that have special *semantic* meaning if they end up not binding to an existing symbol. /// /// Importantly, if <paramref name="token"/> is not in the syntactic construct where the /// language thinks an identifier should be contextually treated as a keyword, then this /// will return <see langword="false"/>. /// /// Or, in other words, the parser must be able to identify these cases in order to be a /// contextual keyword. If identification happens afterwards, it's not contextual. /// </summary> bool IsContextualKeyword(SyntaxToken token); /// <summary> /// The set of identifiers that have special meaning directly after the `#` token in a /// preprocessor directive. For example `if` or `pragma`. /// </summary> bool IsPreprocessorKeyword(SyntaxToken token); bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken); bool IsLiteral(SyntaxToken token); bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token); bool IsNumericLiteral(SyntaxToken token); bool IsVerbatimStringLiteral(SyntaxToken token); bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node); bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node); bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node); bool IsDeclaration(SyntaxNode node); bool IsTypeDeclaration(SyntaxNode node); bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node); bool IsRegularComment(SyntaxTrivia trivia); bool IsDocumentationComment(SyntaxTrivia trivia); bool IsElastic(SyntaxTrivia trivia); bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes); bool IsPreprocessorDirective(SyntaxTrivia trivia); bool IsDocumentationComment(SyntaxNode node); string GetText(int kind); bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken); bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type); bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op); bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? directive, out ExternalSourceInfo info); bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node); bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node); bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node); bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node); bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node); bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node, out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode; void GetPartsOfInterpolationExpression(SyntaxNode node, out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken); bool IsVerbatimInterpolatedStringExpression(SyntaxNode node); // Left side of = assignment. bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node); bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement); void GetPartsOfAssignmentStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); void GetPartsOfAssignmentExpressionOrStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); // Left side of any assignment (for example = or ??= or *= or += ) bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node); // Left side of compound assignment (for example ??= or *= or += ) bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetRightHandSideOfAssignment(SyntaxNode node); bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node); bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node); bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node); bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetRightSideOfDot(SyntaxNode? node); /// <summary> /// Get the node on the left side of the dot if given a dotted expression. /// </summary> /// <param name="allowImplicitTarget"> /// In VB, we have a member access expression with a null expression, this may be one of the /// following forms: /// 1) new With { .a = 1, .b = .a .a refers to the anonymous type /// 2) With obj : .m .m refers to the obj type /// 3) new T() With { .a = 1, .b = .a 'a refers to the T type /// If `allowImplicitTarget` is set to true, the returned node will be set to approperiate node, otherwise, it will return null. /// This parameter has no affect on C# node. /// </param> SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget = false); bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// Gets the containing expression that is actually a language expression and not just typed /// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side /// of qualified names and member access expressions are not language expressions, yet the /// containing qualified names or member access expressions are indeed expressions. /// </summary> [return: NotNullIfNotNull("node")] SyntaxNode? GetStandaloneExpression(SyntaxNode? node); /// <summary> /// Call on the `.y` part of a `x?.y` to get the entire `x?.y` conditional access expression. This also works /// when there are multiple chained conditional accesses. For example, calling this on '.y' or '.z' in /// `x?.y?.z` will both return the full `x?.y?.z` node. This can be used to effectively get 'out' of the RHS of /// a conditional access, and commonly represents the full standalone expression that can be operated on /// atomically. /// </summary> SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node); /// <summary> /// Returns the expression node the member is being accessed off of. If <paramref name="allowImplicitTarget"/> /// is <see langword="false"/>, this will be the node directly to the left of the dot-token. If <paramref name="allowImplicitTarget"/> /// is <see langword="true"/>, then this can return another node in the tree that the member will be accessed /// off of. For example, in VB, if you have a member-access-expression of the form ".Length" then this /// may return the expression in the surrounding With-statement. /// </summary> SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode node, bool allowImplicitTarget = false); SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node); SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node); bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node); SyntaxToken? GetNameOfParameter([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetDefaultOfParameter(SyntaxNode node); SyntaxNode? GetParameterList(SyntaxNode node); bool IsParameterList([NotNullWhen(true)] SyntaxNode? node); bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia); void GetPartsOfElementAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList); SyntaxNode GetExpressionOfArgument(SyntaxNode node); SyntaxNode GetExpressionOfInterpolation(SyntaxNode node); SyntaxNode GetNameOfAttribute(SyntaxNode node); bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node); bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node); SyntaxToken GetIdentifierOfGenericName(SyntaxNode node); SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node); SyntaxToken GetIdentifierOfParameter(SyntaxNode node); SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node); SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node); SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node); SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node); /// <summary> /// True if this is an argument with just an expression and nothing else (i.e. no ref/out, /// no named params, no omitted args). /// </summary> bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node); bool IsArgument([NotNullWhen(true)] SyntaxNode? node); RefKind GetRefKindOfArgument(SyntaxNode node); void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity); bool LooksGeneric(SyntaxNode simpleName); SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode node); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode node); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode node); bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node); bool IsAttributeName(SyntaxNode node); // Violation. Doesn't correspond to any shared structure for vb/c# SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node); bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node); 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); bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node); bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node); bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// Returns true for nodes that represent the body of a method. /// /// For VB this will be /// MethodBlockBaseSyntax. This will be true for things like constructor, method, operator /// bodies as well as accessor bodies. It will not be true for things like sub() function() /// lambdas. /// /// For C# this will be the BlockSyntax or ArrowExpressionSyntax for a /// method/constructor/deconstructor/operator/accessor. It will not be included for local /// functions. /// </summary> bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node); bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement); SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node); SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node); bool IsThisConstructorInitializer(SyntaxToken token); bool IsBaseConstructorInitializer(SyntaxToken token); bool IsQueryKeyword(SyntaxToken token); bool IsElementAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsIndexerMemberCRef([NotNullWhen(true)] SyntaxNode? node); bool IsIdentifierStartCharacter(char c); bool IsIdentifierPartCharacter(char c); bool IsIdentifierEscapeCharacter(char c); bool IsStartOfUnicodeEscapeSequence(char c); bool IsValidIdentifier(string identifier); bool IsVerbatimIdentifier(string identifier); /// <summary> /// Returns true if the given character is a character which may be included in an /// identifier to specify the type of a variable. /// </summary> bool IsTypeCharacter(char c); // Violation. This is a feature level API for QuickInfo. bool IsBindableToken(SyntaxToken token); bool IsInStaticContext(SyntaxNode node); bool IsUnsafeContext(SyntaxNode node); bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node); bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node); bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node); bool IsInConstructor(SyntaxNode node); bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node); bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// A block that has no semantics other than introducing a new scope. That is only C# BlockSyntax. /// </summary> bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// A node that contains a list of statements. In C#, this is BlockSyntax and SwitchSectionSyntax. /// In VB, this includes all block statements such as a MultiLineIfBlockSyntax. /// </summary> bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node); // Violation. This should return a SyntaxList IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node); // Violation. This is a feature level API. SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes); /// <summary> /// A node that can host a list of statements or a single statement. In addition to /// every "executable block", this also includes C# embedded statement owners. /// </summary> // Violation. This is a feature level API. bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node); // Violation. This is a feature level API. IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node); bool AreEquivalent(SyntaxToken token1, SyntaxToken token2); bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2); string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null); // Violation. This is a feature level API. How 'position' relates to 'containment' is not defined. SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position); SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true); SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node); [return: NotNullIfNotNull("node")] SyntaxNode? WalkDownParentheses(SyntaxNode? node); // Violation. This is a feature level API. [return: NotNullIfNotNull("node")] SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false); // Violation. This is a feature level API. List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root); // Violation. This is a feature level API. List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root); SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration); // Violation. This is a feature level API. bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span); // Violation. This is a feature level API. TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree tree, int position, CancellationToken cancellationToken); /// <summary> /// Given a <see cref="SyntaxNode"/>, return the <see cref="TextSpan"/> representing the span of the member body /// it is contained within. This <see cref="TextSpan"/> is used to determine whether speculative binding should be /// used in performance-critical typing scenarios. Note: if this method fails to find a relevant span, it returns /// an empty <see cref="TextSpan"/> at position 0. /// </summary> // Violation. This is a feature level API. TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node); /// <summary> /// Returns the parent node that binds to the symbols that the IDE prefers for features like Quick Info and Find /// All References. For example, if the token is part of the type of an object creation, the parenting object /// creation expression is returned so that binding will return constructor symbols. /// </summary> // Violation. This is a feature level API. SyntaxNode? TryGetBindableParent(SyntaxToken token); // Violation. This is a feature level API. IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken); // Violation. This is a feature level API. bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace); /// <summary> /// Given a <see cref="SyntaxNode"/>, that represents and argument return the string representation of /// that arguments name. /// </summary> // Violation. This is a feature level API. string GetNameForArgument(SyntaxNode? argument); /// <summary> /// Given a <see cref="SyntaxNode"/>, that represents an attribute argument return the string representation of /// that arguments name. /// </summary> // Violation. This is a feature level API. string GetNameForAttributeArgument(SyntaxNode? argument); bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node); bool IsPropertyPatternClause(SyntaxNode node); bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node); bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node); bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node); bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node); bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node); bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node); bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node); bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node); bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node); bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node); bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node); bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node); SyntaxNode GetTypeOfTypePattern(SyntaxNode node); void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen); void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation); void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation); void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern); bool ContainsInterleavedDirective(TextSpan span, SyntaxToken token, CancellationToken cancellationToken); SyntaxTokenList GetModifiers(SyntaxNode? node); // Violation. WithXXX methods should not be here, but should be in SyntaxGenerator. [return: NotNullIfNotNull("node")] SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers); // Violation. This is a feature level API. Location GetDeconstructionReferenceLocation(SyntaxNode node); // Violation. This is a feature level API. SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token); bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node); SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia); #region IsXXX members bool IsAnonymousFunctionExpression([NotNullWhen(true)] SyntaxNode? node); bool IsBaseNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node); bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node); bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node); bool IsMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsSimpleName([NotNullWhen(true)] SyntaxNode? node); #endregion #region GetPartsOfXXX members void GetPartsOfBaseNamespaceDeclaration(SyntaxNode node, out SyntaxNode name, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> members); void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression); void GetPartsOfCompilationUnit(SyntaxNode node, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> attributeLists, out SyntaxList<SyntaxNode> members); void GetPartsOfConditionalAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull); void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse); void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode? argumentList); void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right); void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name); void GetPartsOfObjectCreationExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode? argumentList, out SyntaxNode? initializer); void GetPartsOfParenthesizedExpression(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen); void GetPartsOfPrefixUnaryExpression(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode operand); void GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken dotToken, out SyntaxNode right); void GetPartsOfUsingAliasDirective(SyntaxNode node, out SyntaxToken globalKeyword, out SyntaxToken alias, out SyntaxNode name); #endregion #region GetXXXOfYYYMembers // note: this is only for nodes that have a single child nodes. If a node has multiple child nodes, then // ISyntaxFacts should have a GetPartsOfXXX helper instead, and GetXXXOfYYY should be built off of that // inside ISyntaxFactsExtensions SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node); SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node); SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode node); SyntaxNode GetExpressionOfThrowExpression(SyntaxNode node); SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node); #endregion } [Flags] internal enum DisplayNameOptions { None = 0, IncludeMemberKeyword = 1, IncludeNamespaces = 1 << 1, IncludeParameters = 1 << 2, IncludeType = 1 << 3, IncludeTypeParameters = 1 << 4 } }
1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ISyntaxFactsExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal static class ISyntaxFactsExtensions { public static bool IsLegalIdentifier(this ISyntaxFacts syntaxFacts, string name) { if (name.Length == 0) { return false; } if (!syntaxFacts.IsIdentifierStartCharacter(name[0])) { return false; } for (var i = 1; i < name.Length; i++) { if (!syntaxFacts.IsIdentifierPartCharacter(name[i])) { return false; } } return true; } public static bool IsReservedOrContextualKeyword(this ISyntaxFacts syntaxFacts, SyntaxToken token) => syntaxFacts.IsReservedKeyword(token) || syntaxFacts.IsContextualKeyword(token); public static bool IsWord(this ISyntaxFacts syntaxFacts, SyntaxToken token) { return syntaxFacts.IsIdentifier(token) || syntaxFacts.IsReservedOrContextualKeyword(token) || syntaxFacts.IsPreprocessorKeyword(token); } public static bool IsRegularOrDocumentationComment(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia) => syntaxFacts.IsRegularComment(trivia) || syntaxFacts.IsDocumentationComment(trivia); public static void GetPartsOfAssignmentStatement( this ISyntaxFacts syntaxFacts, SyntaxNode statement, out SyntaxNode left, out SyntaxNode right) { syntaxFacts.GetPartsOfAssignmentStatement(statement, out left, out _, out right); } public static SyntaxNode GetExpressionOfInvocationExpression( this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfInvocationExpression(node, out var expression, out _); return expression; } public static SyntaxNode Unparenthesize( this ISyntaxFacts syntaxFacts, SyntaxNode node) { SyntaxToken openParenToken; SyntaxNode operand; SyntaxToken closeParenToken; if (syntaxFacts.IsParenthesizedPattern(node)) { syntaxFacts.GetPartsOfParenthesizedPattern(node, out openParenToken, out operand, out closeParenToken); } else { syntaxFacts.GetPartsOfParenthesizedExpression(node, out openParenToken, out operand, out closeParenToken); } var leadingTrivia = openParenToken.LeadingTrivia .Concat(openParenToken.TrailingTrivia) .Where(t => !syntaxFacts.IsElastic(t)) .Concat(operand.GetLeadingTrivia()); var trailingTrivia = operand.GetTrailingTrivia() .Concat(closeParenToken.LeadingTrivia) .Where(t => !syntaxFacts.IsElastic(t)) .Concat(closeParenToken.TrailingTrivia); var resultNode = operand .WithLeadingTrivia(leadingTrivia) .WithTrailingTrivia(trailingTrivia); // If there's no trivia between the original node and the tokens around it, then add // elastic markers so the formatting engine will spaces if necessary to keep things // parseable. if (resultNode.GetLeadingTrivia().Count == 0) { var previousToken = node.GetFirstToken().GetPreviousToken(); if (previousToken.TrailingTrivia.Count == 0 && syntaxFacts.IsWordOrNumber(previousToken) && syntaxFacts.IsWordOrNumber(resultNode.GetFirstToken())) { resultNode = resultNode.WithPrependedLeadingTrivia(syntaxFacts.ElasticMarker); } } if (resultNode.GetTrailingTrivia().Count == 0) { var nextToken = node.GetLastToken().GetNextToken(); if (nextToken.LeadingTrivia.Count == 0 && syntaxFacts.IsWordOrNumber(nextToken) && syntaxFacts.IsWordOrNumber(resultNode.GetLastToken())) { resultNode = resultNode.WithAppendedTrailingTrivia(syntaxFacts.ElasticMarker); } } return resultNode; } private static bool IsWordOrNumber(this ISyntaxFacts syntaxFacts, SyntaxToken token) => syntaxFacts.IsWord(token) || syntaxFacts.IsNumericLiteral(token); public static bool SpansPreprocessorDirective(this ISyntaxFacts service, SyntaxNode node) => service.SpansPreprocessorDirective(SpecializedCollections.SingletonEnumerable(node)); public static bool SpansPreprocessorDirective(this ISyntaxFacts service, params SyntaxNode[] nodes) => service.SpansPreprocessorDirective(nodes); public static bool IsWhitespaceOrEndOfLineTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia) => syntaxFacts.IsWhitespaceTrivia(trivia) || syntaxFacts.IsEndOfLineTrivia(trivia); public static void GetPartsOfBinaryExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node, out SyntaxNode left, out SyntaxNode right) => syntaxFacts.GetPartsOfBinaryExpression(node, out left, out _, out right); public static SyntaxNode GetPatternOfParenthesizedPattern(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfParenthesizedPattern(node, out _, out var pattern, out _); return pattern; } public static SyntaxToken GetOperatorTokenOfBinaryExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfBinaryExpression(node, out _, out var token, out _); return token; } public static bool IsAnonymousOrLocalFunction(this ISyntaxFacts syntaxFacts, SyntaxNode node) => syntaxFacts.IsAnonymousFunctionExpression(node) || syntaxFacts.IsLocalFunctionStatement(node); public static SyntaxNode? GetExpressionOfElementAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfElementAccessExpression(node, out var expression, out _); return expression; } public static SyntaxNode? GetArgumentListOfElementAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfElementAccessExpression(node, out _, out var argumentList); return argumentList; } public static SyntaxNode GetExpressionOfConditionalAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfConditionalAccessExpression(node, out var expression, out _); return expression; } public static SyntaxToken GetOperatorTokenOfMemberAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfMemberAccessExpression(node, out _, out var operatorToken, out _); return operatorToken; } public static void GetPartsOfMemberAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node, out SyntaxNode expression, out SyntaxNode name) => syntaxFacts.GetPartsOfMemberAccessExpression(node, out expression, out _, out name); public static void GetPartsOfConditionalAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node, out SyntaxNode expression, out SyntaxNode whenNotNull) => syntaxFacts.GetPartsOfConditionalAccessExpression(node, out expression, out _, out whenNotNull); public static TextSpan GetSpanWithoutAttributes(this ISyntaxFacts syntaxFacts, SyntaxNode root, SyntaxNode node) { // Span without AttributeLists // - No AttributeLists -> original .Span // - Some AttributeLists -> (first non-trivia/comment Token.Span.Begin, original.Span.End) // - We need to be mindful about comments due to: // // [Test1] // //Comment1 // [||]object Property1 { get; set; } // the comment node being part of the next token's (`object`) leading trivia and not the AttributeList's node. // - In case only attribute is written we need to be careful to not to use next (unrelated) token as beginning current the node. var attributeList = syntaxFacts.GetAttributeLists(node); if (attributeList.Any()) { var endOfAttributeLists = attributeList.Last().Span.End; var afterAttributesToken = root.FindTokenOnRightOfPosition(endOfAttributeLists); var endOfNode = node.Span.End; var startOfNodeWithoutAttributes = Math.Min(afterAttributesToken.Span.Start, endOfNode); return TextSpan.FromBounds(startOfNodeWithoutAttributes, endOfNode); } return node.Span; } /// <summary> /// Gets the statement container node for the statement <paramref name="node"/>. /// </summary> /// <param name="syntaxFacts">The <see cref="ISyntaxFacts"/> implementation.</param> /// <param name="node">The statement.</param> /// <returns>The statement container for <paramref name="node"/>.</returns> public static SyntaxNode? GetStatementContainer(this ISyntaxFacts syntaxFacts, SyntaxNode node) { for (var current = node; current is object; current = current.Parent) { if (syntaxFacts.IsStatementContainer(current.Parent)) { return current.Parent; } } return null; } /// <summary> /// Similar to <see cref="ISyntaxFacts.GetStandaloneExpression(SyntaxNode)"/>, this gets the containing /// expression that is actually a language expression and not just typed as an ExpressionSyntax for convenience. /// However, this goes beyond that that method in that if this expression is the RHS of a conditional access /// (i.e. <c>a?.b()</c>) it will also return the root of the conditional access expression tree. /// <para/> The intuition here is that this will give the topmost expression node that could realistically be /// replaced with any other expression. For example, with <c>a?.b()</c> technically <c>.b()</c> is an /// expression. But that cannot be replaced with something like <c>(1 + 1)</c> (as <c>a?.(1 + 1)</c> is not /// legal). However, in <c>a?.b()</c>, then <c>a</c> itself could be replaced with <c>(1 + 1)?.b()</c> to form /// a legal expression. /// </summary> public static SyntaxNode GetRootStandaloneExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { // First, make sure we're on a construct the language things is a standalone expression. var standalone = syntaxFacts.GetStandaloneExpression(node); // Then, if this is the RHS of a `?`, walk up to the top of that tree to get the final standalone expression. return syntaxFacts.GetRootConditionalAccessExpression(standalone) ?? standalone; } #region GetXXXOfYYY Members public static SyntaxNode? GetArgumentListOfInvocationExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfInvocationExpression(node, out _, out var argumentList); return argumentList; } public static SyntaxNode? GetArgumentListOfObjectCreationExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfObjectCreationExpression(node, out _, out var argumentList, out _); return argumentList; } public static SyntaxNode GetExpressionOfParenthesizedExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfParenthesizedExpression(node, out _, out var expression, out _); return expression; } public static SyntaxList<SyntaxNode> GetImportsOfBaseNamespaceDeclaration(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfBaseNamespaceDeclaration(node, out _, out var imports, out _); return imports; } public static SyntaxList<SyntaxNode> GetImportsOfCompilationUnit(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfCompilationUnit(node, out var imports, out _, out _); return imports; } public static SyntaxNode? GetInitializerOfObjectCreationExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfObjectCreationExpression(node, out _, out _, out var initializer); return initializer; } public static SyntaxList<SyntaxNode> GetMembersOfBaseNamespaceDeclaration(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfBaseNamespaceDeclaration(node, out _, out _, out var members); return members; } public static SyntaxList<SyntaxNode> GetMembersOfCompilationUnit(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfCompilationUnit(node, out _, out _, out var members); return members; } public static SyntaxNode GetNameOfBaseNamespaceDeclaration(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfBaseNamespaceDeclaration(node, out var name, out _, out _); return name; } public static SyntaxNode GetNameOfMemberAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfMemberAccessExpression(node, out _, out var name); return name; } public static SyntaxNode GetOperandOfPrefixUnaryExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfPrefixUnaryExpression(node, out _, out var operand); return operand; } public static SyntaxToken GetOperatorTokenOfPrefixUnaryExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfPrefixUnaryExpression(node, out var operatorToken, out _); return operatorToken; } public static SyntaxNode GetTypeOfObjectCreationExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfObjectCreationExpression(node, out var type, out _, out _); return type; } #endregion #region IsXXXOfYYY members public static bool IsExpressionOfAwaitExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) { var parent = node?.Parent; if (!syntaxFacts.IsAwaitExpression(parent)) return false; return node == syntaxFacts.GetExpressionOfAwaitExpression(parent); } public static bool IsExpressionOfInvocationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) { var parent = node?.Parent; if (!syntaxFacts.IsInvocationExpression(parent)) return false; syntaxFacts.GetPartsOfInvocationExpression(parent, out var expression, out _); return node == expression; } public static bool IsExpressionOfMemberAccessExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) { var parent = node?.Parent; if (!syntaxFacts.IsMemberAccessExpression(parent)) return false; syntaxFacts.GetPartsOfMemberAccessExpression(parent, out var expression, out _); return node == expression; } public static bool IsRightOfQualifiedName(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) { var parent = node?.Parent; if (!syntaxFacts.IsQualifiedName(parent)) return false; syntaxFacts.GetPartsOfQualifiedName(parent, out _, out _, out var right); return node == right; } public static bool IsTypeOfObjectCreationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) { var parent = node?.Parent; if (!syntaxFacts.IsObjectCreationExpression(parent)) return false; syntaxFacts.GetPartsOfObjectCreationExpression(parent, out var type, out _, out _); return type == node; } #endregion #region ISyntaxKinds forwarding methods #region trivia public static bool IsEndOfLineTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia) => trivia.RawKind == syntaxFacts.SyntaxKinds.EndOfLineTrivia; public static bool IsWhitespaceTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia) => trivia.RawKind == syntaxFacts.SyntaxKinds.WhitespaceTrivia; public static bool IsSkippedTokensTrivia(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.SkippedTokensTrivia; #endregion #region keywords public static bool IsAwaitKeyword(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.AwaitKeyword; public static bool IsGlobalNamespaceKeyword(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.GlobalKeyword; #endregion #region literal tokens public static bool IsCharacterLiteral(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.CharacterLiteralToken; public static bool IsStringLiteral(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.StringLiteralToken; #endregion #region tokens public static bool IsIdentifier(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.IdentifierToken; public static bool IsHashToken(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.HashToken; public static bool IsInterpolatedStringTextToken(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.InterpolatedStringTextToken; #endregion #region names public static bool IsGenericName(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.GenericName; public static bool IsIdentifierName(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.IdentifierName; public static bool IsQualifiedName(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.QualifiedName; #endregion #region types public static bool IsTupleType(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.TupleType; #endregion #region literal expressions public static bool IsCharacterLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.CharacterLiteralExpression; public static bool IsDefaultLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.DefaultLiteralExpression; public static bool IsFalseLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.FalseLiteralExpression; public static bool IsNumericLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.NumericLiteralExpression; public static bool IsNullLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.NullLiteralExpression; public static bool IsStringLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.StringLiteralExpression; public static bool IsTrueLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.TrueLiteralExpression; #endregion #region expressions public static bool IsAwaitExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.AwaitExpression; public static bool IsBaseExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.BaseExpression; public static bool IsConditionalAccessExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ConditionalAccessExpression; public static bool IsImplicitObjectCreationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node != null && node.RawKind == syntaxFacts.SyntaxKinds.ImplicitObjectCreationExpression; public static bool IsInterpolatedStringExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.InterpolatedStringExpression; public static bool IsInterpolation(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.Interpolation; public static bool IsInterpolatedStringText(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.InterpolatedStringText; public static bool IsInvocationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.InvocationExpression; public static bool IsLogicalAndExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.LogicalAndExpression; public static bool IsLogicalOrExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.LogicalOrExpression; public static bool IsLogicalNotExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.LogicalNotExpression; public static bool IsObjectCreationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ObjectCreationExpression; public static bool IsParenthesizedExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ParenthesizedExpression; public static bool IsQueryExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.QueryExpression; public static bool IsSimpleMemberAccessExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.SimpleMemberAccessExpression; public static bool IsThisExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ThisExpression; public static bool IsThrowExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node != null && node.RawKind == syntaxFacts.SyntaxKinds.ThrowExpression; public static bool IsTupleExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.TupleExpression; public static bool ContainsGlobalStatement(this ISyntaxFacts syntaxFacts, SyntaxNode node) => node.ChildNodes().Any(c => c.RawKind == syntaxFacts.SyntaxKinds.GlobalStatement); #endregion #region statements public static bool IsExpressionStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ExpressionStatement; public static bool IsForEachStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ForEachStatement; public static bool IsLocalDeclarationStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.LocalDeclarationStatement; public static bool IsLocalFunctionStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node != null && node.RawKind == syntaxFacts.SyntaxKinds.LocalFunctionStatement; public static bool IsLockStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.LockStatement; public static bool IsReturnStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode node) => node?.RawKind == syntaxFacts.SyntaxKinds.ReturnStatement; public static bool IsThrowStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ThrowStatement; public static bool IsUsingStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.UsingStatement; #endregion #region members/declarations public static bool IsAttribute(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.Attribute; public static bool IsClassDeclaration(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ClassDeclaration; public static bool IsGlobalAttribute(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => syntaxFacts.IsGlobalAssemblyAttribute(node) || syntaxFacts.IsGlobalModuleAttribute(node); public static bool IsParameter(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.Parameter; public static bool IsTypeConstraint(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.TypeConstraint; public static bool IsVariableDeclarator(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.VariableDeclarator; public static bool IsFieldDeclaration(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.FieldDeclaration; public static bool IsTypeArgumentList(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.TypeArgumentList; #endregion #region clauses public static bool IsEqualsValueClause(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.EqualsValueClause; #endregion #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal static class ISyntaxFactsExtensions { private static readonly ObjectPool<Stack<(SyntaxNodeOrToken nodeOrToken, bool leading, bool trailing)>> s_stackPool = SharedPools.Default<Stack<(SyntaxNodeOrToken nodeOrToken, bool leading, bool trailing)>>(); public static bool IsOnSingleLine(this ISyntaxFacts syntaxFacts, SyntaxNode node, bool fullSpan) { // The stack logic assumes the initial node is not null Contract.ThrowIfNull(node); // Use an actual Stack so we can write out deeply recursive structures without overflowing. // Note: algorithm is taken from GreenNode.WriteTo. // // General approach is that we recurse down the nodes, using a real stack object to // keep track of what node we're on. If full-span is true we'll examine all tokens // and all the trivia on each token. If full-span is false we'll examine all tokens // but we'll ignore the leading trivia on the very first trivia and the trailing trivia // on the very last token. var stack = s_stackPool.Allocate(); stack.Push((node, leading: fullSpan, trailing: fullSpan)); var result = IsOnSingleLine(syntaxFacts, stack); s_stackPool.ClearAndFree(stack); return result; } private static bool IsOnSingleLine( ISyntaxFacts syntaxFacts, Stack<(SyntaxNodeOrToken nodeOrToken, bool leading, bool trailing)> stack) { while (stack.Count > 0) { var (currentNodeOrToken, currentLeading, currentTrailing) = stack.Pop(); if (currentNodeOrToken.IsToken) { // If this token isn't on a single line, then the original node definitely // isn't on a single line. if (!IsOnSingleLine(syntaxFacts, currentNodeOrToken.AsToken(), currentLeading, currentTrailing)) return false; } else { var currentNode = currentNodeOrToken.AsNode()!; var childNodesAndTokens = currentNode.ChildNodesAndTokens(); var childCount = childNodesAndTokens.Count; // Walk the children of this node in reverse, putting on the stack to process. // This way we process the children in the actual child-order they are in for // this node. var index = 0; foreach (var child in childNodesAndTokens.Reverse()) { // Since we're walking the children in reverse, if we're on hte 0th item, // that's the last child. var last = index == 0; // Once we get all the way to the end of the reversed list, we're actually // on the first. var first = index == childCount - 1; // We want the leading trivia if we've asked for it, or if we're not the first // token being processed. We want the trailing trivia if we've asked for it, // or if we're not the last token being processed. stack.Push((child, currentLeading | !first, currentTrailing | !last)); index++; } } } // All tokens were on a single line. This node is on a single line. return true; } private static bool IsOnSingleLine(ISyntaxFacts syntaxFacts, SyntaxToken token, bool leading, bool trailing) { // If any of our trivia is not on a single line, then we're not on a single line. if (!IsOnSingleLine(syntaxFacts, token.LeadingTrivia, leading) || !IsOnSingleLine(syntaxFacts, token.TrailingTrivia, trailing)) { return false; } // Only string literals can span multiple lines. Only need to check those. if (syntaxFacts.SyntaxKinds.StringLiteralToken == token.RawKind || syntaxFacts.SyntaxKinds.InterpolatedStringTextToken == token.RawKind) { // This allocated. But we only do it in the string case. For all other tokens // we don't need any allocations. if (!IsOnSingleLine(token.ToString())) { return false; } } // Any other type of token is on a single line. return true; } private static bool IsOnSingleLine(ISyntaxFacts syntaxFacts, SyntaxTriviaList triviaList, bool checkTrivia) { if (checkTrivia) { foreach (var trivia in triviaList) { if (trivia.HasStructure) { // For structured trivia, we recurse into the trivia to see if it // is on a single line or not. If it isn't, then we're definitely // not on a single line. if (!IsOnSingleLine(syntaxFacts, trivia.GetStructure()!, fullSpan: true)) { return false; } } else if (syntaxFacts.IsEndOfLineTrivia(trivia)) { // Contained an end-of-line trivia. Definitely not on a single line. return false; } else if (!syntaxFacts.IsWhitespaceTrivia(trivia)) { // Was some other form of trivia (like a comment). Easiest thing // to do is just stringify this and count the number of newlines. // these should be rare. So the allocation here is ok. if (!IsOnSingleLine(trivia.ToString())) { return false; } } } } return true; } private static bool IsOnSingleLine(string value) => value.GetNumberOfLineBreaks() == 0; public static bool ContainsInterleavedDirective( this ISyntaxFacts syntaxFacts, ImmutableArray<SyntaxNode> nodes, CancellationToken cancellationToken) { if (nodes.Length > 0) { var span = TextSpan.FromBounds(nodes.First().Span.Start, nodes.Last().Span.End); foreach (var node in nodes) { cancellationToken.ThrowIfCancellationRequested(); if (ContainsInterleavedDirective(syntaxFacts, span, node, cancellationToken)) return true; } } return false; } public static bool ContainsInterleavedDirective(this ISyntaxFacts syntaxFacts, SyntaxNode node, CancellationToken cancellationToken) => ContainsInterleavedDirective(syntaxFacts, node.Span, node, cancellationToken); public static bool ContainsInterleavedDirective( this ISyntaxFacts syntaxFacts, TextSpan span, SyntaxNode node, CancellationToken cancellationToken) { foreach (var token in node.DescendantTokens()) { if (syntaxFacts.ContainsInterleavedDirective(span, token, cancellationToken)) return true; } return false; } public static bool SpansPreprocessorDirective(this ISyntaxFacts syntaxFacts, IEnumerable<SyntaxNode> nodes) { if (nodes == null || nodes.IsEmpty()) { return false; } return SpansPreprocessorDirective(syntaxFacts, nodes.SelectMany(n => n.DescendantTokens())); } /// <summary> /// Determines if there is preprocessor trivia *between* any of the <paramref name="tokens"/> /// provided. The <paramref name="tokens"/> will be deduped and then ordered by position. /// Specifically, the first token will not have it's leading trivia checked, and the last /// token will not have it's trailing trivia checked. All other trivia will be checked to /// see if it contains a preprocessor directive. /// </summary> public static bool SpansPreprocessorDirective(this ISyntaxFacts syntaxFacts, IEnumerable<SyntaxToken> tokens) { // we want to check all leading trivia of all tokens (except the // first one), and all trailing trivia of all tokens (except the // last one). var first = true; var previousToken = default(SyntaxToken); // Allow duplicate nodes/tokens to be passed in. Also, allow the nodes/tokens // to not be in any particular order when passed in. var orderedTokens = tokens.Distinct().OrderBy(t => t.SpanStart); foreach (var token in orderedTokens) { if (first) { first = false; } else { // check the leading trivia of this token, and the trailing trivia // of the previous token. if (SpansPreprocessorDirective(syntaxFacts, token.LeadingTrivia) || SpansPreprocessorDirective(syntaxFacts, previousToken.TrailingTrivia)) { return true; } } previousToken = token; } return false; } private static bool SpansPreprocessorDirective(this ISyntaxFacts syntaxFacts, SyntaxTriviaList list) => list.Any(t => syntaxFacts.IsPreprocessorDirective(t)); public static bool IsLegalIdentifier(this ISyntaxFacts syntaxFacts, string name) { if (name.Length == 0) { return false; } if (!syntaxFacts.IsIdentifierStartCharacter(name[0])) { return false; } for (var i = 1; i < name.Length; i++) { if (!syntaxFacts.IsIdentifierPartCharacter(name[i])) { return false; } } return true; } public static bool IsReservedOrContextualKeyword(this ISyntaxFacts syntaxFacts, SyntaxToken token) => syntaxFacts.IsReservedKeyword(token) || syntaxFacts.IsContextualKeyword(token); public static bool IsWord(this ISyntaxFacts syntaxFacts, SyntaxToken token) { return syntaxFacts.IsIdentifier(token) || syntaxFacts.IsReservedOrContextualKeyword(token) || syntaxFacts.IsPreprocessorKeyword(token); } public static bool IsRegularOrDocumentationComment(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia) => syntaxFacts.IsRegularComment(trivia) || syntaxFacts.IsDocumentationComment(trivia); public static void GetPartsOfAssignmentStatement( this ISyntaxFacts syntaxFacts, SyntaxNode statement, out SyntaxNode left, out SyntaxNode right) { syntaxFacts.GetPartsOfAssignmentStatement(statement, out left, out _, out right); } public static SyntaxNode GetExpressionOfInvocationExpression( this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfInvocationExpression(node, out var expression, out _); return expression; } public static SyntaxNode Unparenthesize( this ISyntaxFacts syntaxFacts, SyntaxNode node) { SyntaxToken openParenToken; SyntaxNode operand; SyntaxToken closeParenToken; if (syntaxFacts.IsParenthesizedPattern(node)) { syntaxFacts.GetPartsOfParenthesizedPattern(node, out openParenToken, out operand, out closeParenToken); } else { syntaxFacts.GetPartsOfParenthesizedExpression(node, out openParenToken, out operand, out closeParenToken); } var leadingTrivia = openParenToken.LeadingTrivia .Concat(openParenToken.TrailingTrivia) .Where(t => !syntaxFacts.IsElastic(t)) .Concat(operand.GetLeadingTrivia()); var trailingTrivia = operand.GetTrailingTrivia() .Concat(closeParenToken.LeadingTrivia) .Where(t => !syntaxFacts.IsElastic(t)) .Concat(closeParenToken.TrailingTrivia); var resultNode = operand .WithLeadingTrivia(leadingTrivia) .WithTrailingTrivia(trailingTrivia); // If there's no trivia between the original node and the tokens around it, then add // elastic markers so the formatting engine will spaces if necessary to keep things // parseable. if (resultNode.GetLeadingTrivia().Count == 0) { var previousToken = node.GetFirstToken().GetPreviousToken(); if (previousToken.TrailingTrivia.Count == 0 && syntaxFacts.IsWordOrNumber(previousToken) && syntaxFacts.IsWordOrNumber(resultNode.GetFirstToken())) { resultNode = resultNode.WithPrependedLeadingTrivia(syntaxFacts.ElasticMarker); } } if (resultNode.GetTrailingTrivia().Count == 0) { var nextToken = node.GetLastToken().GetNextToken(); if (nextToken.LeadingTrivia.Count == 0 && syntaxFacts.IsWordOrNumber(nextToken) && syntaxFacts.IsWordOrNumber(resultNode.GetLastToken())) { resultNode = resultNode.WithAppendedTrailingTrivia(syntaxFacts.ElasticMarker); } } return resultNode; } private static bool IsWordOrNumber(this ISyntaxFacts syntaxFacts, SyntaxToken token) => syntaxFacts.IsWord(token) || syntaxFacts.IsNumericLiteral(token); public static bool SpansPreprocessorDirective(this ISyntaxFacts service, SyntaxNode node) => service.SpansPreprocessorDirective(SpecializedCollections.SingletonEnumerable(node)); public static bool SpansPreprocessorDirective(this ISyntaxFacts service, params SyntaxNode[] nodes) => service.SpansPreprocessorDirective((IEnumerable<SyntaxNode>)nodes); public static bool IsWhitespaceOrEndOfLineTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia) => syntaxFacts.IsWhitespaceTrivia(trivia) || syntaxFacts.IsEndOfLineTrivia(trivia); public static void GetPartsOfBinaryExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node, out SyntaxNode left, out SyntaxNode right) => syntaxFacts.GetPartsOfBinaryExpression(node, out left, out _, out right); public static SyntaxNode GetPatternOfParenthesizedPattern(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfParenthesizedPattern(node, out _, out var pattern, out _); return pattern; } public static SyntaxToken GetOperatorTokenOfBinaryExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfBinaryExpression(node, out _, out var token, out _); return token; } public static bool IsAnonymousOrLocalFunction(this ISyntaxFacts syntaxFacts, SyntaxNode node) => syntaxFacts.IsAnonymousFunctionExpression(node) || syntaxFacts.IsLocalFunctionStatement(node); public static SyntaxNode? GetExpressionOfElementAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfElementAccessExpression(node, out var expression, out _); return expression; } public static SyntaxNode? GetArgumentListOfElementAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfElementAccessExpression(node, out _, out var argumentList); return argumentList; } public static SyntaxNode GetExpressionOfConditionalAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfConditionalAccessExpression(node, out var expression, out _); return expression; } public static SyntaxToken GetOperatorTokenOfMemberAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfMemberAccessExpression(node, out _, out var operatorToken, out _); return operatorToken; } public static void GetPartsOfMemberAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node, out SyntaxNode expression, out SyntaxNode name) => syntaxFacts.GetPartsOfMemberAccessExpression(node, out expression, out _, out name); public static void GetPartsOfConditionalAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node, out SyntaxNode expression, out SyntaxNode whenNotNull) => syntaxFacts.GetPartsOfConditionalAccessExpression(node, out expression, out _, out whenNotNull); public static TextSpan GetSpanWithoutAttributes(this ISyntaxFacts syntaxFacts, SyntaxNode root, SyntaxNode node) { // Span without AttributeLists // - No AttributeLists -> original .Span // - Some AttributeLists -> (first non-trivia/comment Token.Span.Begin, original.Span.End) // - We need to be mindful about comments due to: // // [Test1] // //Comment1 // [||]object Property1 { get; set; } // the comment node being part of the next token's (`object`) leading trivia and not the AttributeList's node. // - In case only attribute is written we need to be careful to not to use next (unrelated) token as beginning current the node. var attributeList = syntaxFacts.GetAttributeLists(node); if (attributeList.Any()) { var endOfAttributeLists = attributeList.Last().Span.End; var afterAttributesToken = root.FindTokenOnRightOfPosition(endOfAttributeLists); var endOfNode = node.Span.End; var startOfNodeWithoutAttributes = Math.Min(afterAttributesToken.Span.Start, endOfNode); return TextSpan.FromBounds(startOfNodeWithoutAttributes, endOfNode); } return node.Span; } /// <summary> /// Gets the statement container node for the statement <paramref name="node"/>. /// </summary> /// <param name="syntaxFacts">The <see cref="ISyntaxFacts"/> implementation.</param> /// <param name="node">The statement.</param> /// <returns>The statement container for <paramref name="node"/>.</returns> public static SyntaxNode? GetStatementContainer(this ISyntaxFacts syntaxFacts, SyntaxNode node) { for (var current = node; current is object; current = current.Parent) { if (syntaxFacts.IsStatementContainer(current.Parent)) { return current.Parent; } } return null; } /// <summary> /// Similar to <see cref="ISyntaxFacts.GetStandaloneExpression(SyntaxNode)"/>, this gets the containing /// expression that is actually a language expression and not just typed as an ExpressionSyntax for convenience. /// However, this goes beyond that that method in that if this expression is the RHS of a conditional access /// (i.e. <c>a?.b()</c>) it will also return the root of the conditional access expression tree. /// <para/> The intuition here is that this will give the topmost expression node that could realistically be /// replaced with any other expression. For example, with <c>a?.b()</c> technically <c>.b()</c> is an /// expression. But that cannot be replaced with something like <c>(1 + 1)</c> (as <c>a?.(1 + 1)</c> is not /// legal). However, in <c>a?.b()</c>, then <c>a</c> itself could be replaced with <c>(1 + 1)?.b()</c> to form /// a legal expression. /// </summary> public static SyntaxNode GetRootStandaloneExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { // First, make sure we're on a construct the language things is a standalone expression. var standalone = syntaxFacts.GetStandaloneExpression(node); // Then, if this is the RHS of a `?`, walk up to the top of that tree to get the final standalone expression. return syntaxFacts.GetRootConditionalAccessExpression(standalone) ?? standalone; } #region GetXXXOfYYY Members public static SyntaxNode? GetArgumentListOfInvocationExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfInvocationExpression(node, out _, out var argumentList); return argumentList; } public static SyntaxNode? GetArgumentListOfObjectCreationExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfObjectCreationExpression(node, out _, out var argumentList, out _); return argumentList; } public static SyntaxNode GetExpressionOfParenthesizedExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfParenthesizedExpression(node, out _, out var expression, out _); return expression; } public static SyntaxList<SyntaxNode> GetImportsOfBaseNamespaceDeclaration(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfBaseNamespaceDeclaration(node, out _, out var imports, out _); return imports; } public static SyntaxList<SyntaxNode> GetImportsOfCompilationUnit(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfCompilationUnit(node, out var imports, out _, out _); return imports; } public static SyntaxNode? GetInitializerOfObjectCreationExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfObjectCreationExpression(node, out _, out _, out var initializer); return initializer; } public static SyntaxList<SyntaxNode> GetMembersOfBaseNamespaceDeclaration(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfBaseNamespaceDeclaration(node, out _, out _, out var members); return members; } public static SyntaxList<SyntaxNode> GetMembersOfCompilationUnit(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfCompilationUnit(node, out _, out _, out var members); return members; } public static SyntaxNode GetNameOfBaseNamespaceDeclaration(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfBaseNamespaceDeclaration(node, out var name, out _, out _); return name; } public static SyntaxNode GetNameOfMemberAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfMemberAccessExpression(node, out _, out var name); return name; } public static SyntaxNode GetOperandOfPrefixUnaryExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfPrefixUnaryExpression(node, out _, out var operand); return operand; } public static SyntaxToken GetOperatorTokenOfPrefixUnaryExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfPrefixUnaryExpression(node, out var operatorToken, out _); return operatorToken; } public static SyntaxNode GetTypeOfObjectCreationExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfObjectCreationExpression(node, out var type, out _, out _); return type; } #endregion #region IsXXXOfYYY members public static bool IsExpressionOfAwaitExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) { var parent = node?.Parent; if (!syntaxFacts.IsAwaitExpression(parent)) return false; return node == syntaxFacts.GetExpressionOfAwaitExpression(parent); } public static bool IsExpressionOfInvocationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) { var parent = node?.Parent; if (!syntaxFacts.IsInvocationExpression(parent)) return false; syntaxFacts.GetPartsOfInvocationExpression(parent, out var expression, out _); return node == expression; } public static bool IsExpressionOfMemberAccessExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) { var parent = node?.Parent; if (!syntaxFacts.IsMemberAccessExpression(parent)) return false; syntaxFacts.GetPartsOfMemberAccessExpression(parent, out var expression, out _); return node == expression; } public static bool IsRightOfQualifiedName(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) { var parent = node?.Parent; if (!syntaxFacts.IsQualifiedName(parent)) return false; syntaxFacts.GetPartsOfQualifiedName(parent, out _, out _, out var right); return node == right; } public static bool IsTypeOfObjectCreationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) { var parent = node?.Parent; if (!syntaxFacts.IsObjectCreationExpression(parent)) return false; syntaxFacts.GetPartsOfObjectCreationExpression(parent, out var type, out _, out _); return type == node; } #endregion #region ISyntaxKinds forwarding methods #region trivia public static bool IsEndOfLineTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia) => trivia.RawKind == syntaxFacts.SyntaxKinds.EndOfLineTrivia; public static bool IsMultiLineCommentTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia) => trivia.RawKind == syntaxFacts.SyntaxKinds.MultiLineCommentTrivia; public static bool IsMultiLineDocCommentTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia) => trivia.RawKind == syntaxFacts.SyntaxKinds.MultiLineDocCommentTrivia; public static bool IsShebangDirectiveTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia) => trivia.RawKind == syntaxFacts.SyntaxKinds.ShebangDirectiveTrivia; public static bool IsSingleLineCommentTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia) => trivia.RawKind == syntaxFacts.SyntaxKinds.SingleLineCommentTrivia; public static bool IsSingleLineDocCommentTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia) => trivia.RawKind == syntaxFacts.SyntaxKinds.SingleLineDocCommentTrivia; public static bool IsWhitespaceTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia) => trivia.RawKind == syntaxFacts.SyntaxKinds.WhitespaceTrivia; public static bool IsSkippedTokensTrivia(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.SkippedTokensTrivia; #endregion #region keywords public static bool IsAwaitKeyword(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.AwaitKeyword; public static bool IsGlobalNamespaceKeyword(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.GlobalKeyword; #endregion #region literal tokens public static bool IsCharacterLiteral(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.CharacterLiteralToken; public static bool IsStringLiteral(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.StringLiteralToken; #endregion #region tokens public static bool IsIdentifier(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.IdentifierToken; public static bool IsHashToken(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.HashToken; public static bool IsInterpolatedStringTextToken(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.InterpolatedStringTextToken; #endregion #region names public static bool IsGenericName(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.GenericName; public static bool IsIdentifierName(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.IdentifierName; public static bool IsQualifiedName(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.QualifiedName; #endregion #region types public static bool IsTupleType(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.TupleType; #endregion #region literal expressions public static bool IsCharacterLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.CharacterLiteralExpression; public static bool IsDefaultLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.DefaultLiteralExpression; public static bool IsFalseLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.FalseLiteralExpression; public static bool IsNumericLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.NumericLiteralExpression; public static bool IsNullLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.NullLiteralExpression; public static bool IsStringLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.StringLiteralExpression; public static bool IsTrueLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.TrueLiteralExpression; #endregion #region expressions public static bool IsAwaitExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.AwaitExpression; public static bool IsBaseExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.BaseExpression; public static bool IsConditionalAccessExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ConditionalAccessExpression; public static bool IsImplicitObjectCreationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node != null && node.RawKind == syntaxFacts.SyntaxKinds.ImplicitObjectCreationExpression; public static bool IsInterpolatedStringExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.InterpolatedStringExpression; public static bool IsInterpolation(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.Interpolation; public static bool IsInterpolatedStringText(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.InterpolatedStringText; public static bool IsInvocationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.InvocationExpression; public static bool IsLogicalAndExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.LogicalAndExpression; public static bool IsLogicalOrExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.LogicalOrExpression; public static bool IsLogicalNotExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.LogicalNotExpression; public static bool IsObjectCreationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ObjectCreationExpression; public static bool IsParenthesizedExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ParenthesizedExpression; public static bool IsQueryExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.QueryExpression; public static bool IsSimpleMemberAccessExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.SimpleMemberAccessExpression; public static bool IsThisExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ThisExpression; public static bool IsThrowExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node != null && node.RawKind == syntaxFacts.SyntaxKinds.ThrowExpression; public static bool IsTupleExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.TupleExpression; public static bool ContainsGlobalStatement(this ISyntaxFacts syntaxFacts, SyntaxNode node) => node.ChildNodes().Any(c => c.RawKind == syntaxFacts.SyntaxKinds.GlobalStatement); #endregion #region statements public static bool IsExpressionStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ExpressionStatement; public static bool IsForEachStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ForEachStatement; public static bool IsLocalDeclarationStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.LocalDeclarationStatement; public static bool IsLocalFunctionStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node != null && node.RawKind == syntaxFacts.SyntaxKinds.LocalFunctionStatement; public static bool IsLockStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.LockStatement; public static bool IsReturnStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode node) => node?.RawKind == syntaxFacts.SyntaxKinds.ReturnStatement; public static bool IsThrowStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ThrowStatement; public static bool IsUsingStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.UsingStatement; #endregion #region members/declarations public static bool IsAttribute(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.Attribute; public static bool IsClassDeclaration(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ClassDeclaration; public static bool IsGlobalAttribute(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => syntaxFacts.IsGlobalAssemblyAttribute(node) || syntaxFacts.IsGlobalModuleAttribute(node); public static bool IsParameter(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.Parameter; public static bool IsTypeConstraint(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.TypeConstraint; public static bool IsVariableDeclarator(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.VariableDeclarator; public static bool IsFieldDeclaration(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.FieldDeclaration; public static bool IsTypeArgumentList(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.TypeArgumentList; #endregion #region clauses public static bool IsEqualsValueClause(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.EqualsValueClause; #endregion #endregion } }
1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxFacts.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts Imports System.Diagnostics.CodeAnalysis #If CODE_STYLE Then Imports Microsoft.CodeAnalysis.Internal.Editing #Else Imports Microsoft.CodeAnalysis.Editing #End If Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageServices Friend Class VisualBasicSyntaxFacts Inherits AbstractSyntaxFacts Implements ISyntaxFacts Public Shared ReadOnly Property Instance As New VisualBasicSyntaxFacts Protected Sub New() End Sub Public ReadOnly Property IsCaseSensitive As Boolean Implements ISyntaxFacts.IsCaseSensitive Get Return False End Get End Property Public ReadOnly Property StringComparer As StringComparer Implements ISyntaxFacts.StringComparer Get Return CaseInsensitiveComparison.Comparer End Get End Property Public ReadOnly Property ElasticMarker As SyntaxTrivia Implements ISyntaxFacts.ElasticMarker Get Return SyntaxFactory.ElasticMarker End Get End Property Public ReadOnly Property ElasticCarriageReturnLineFeed As SyntaxTrivia Implements ISyntaxFacts.ElasticCarriageReturnLineFeed Get Return SyntaxFactory.ElasticCarriageReturnLineFeed End Get End Property Public Overrides ReadOnly Property SyntaxKinds As ISyntaxKinds = VisualBasicSyntaxKinds.Instance Implements ISyntaxFacts.SyntaxKinds Public Function SupportsIndexingInitializer(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsIndexingInitializer Return False End Function Public Function SupportsThrowExpression(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsThrowExpression Return False End Function Public Function SupportsLocalFunctionDeclaration(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsLocalFunctionDeclaration Return False End Function Public Function SupportsRecord(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecord Return False End Function Public Function SupportsRecordStruct(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecordStruct Return False End Function Public Function ParseToken(text As String) As SyntaxToken Implements ISyntaxFacts.ParseToken Return SyntaxFactory.ParseToken(text, startStatement:=True) End Function Public Function ParseLeadingTrivia(text As String) As SyntaxTriviaList Implements ISyntaxFacts.ParseLeadingTrivia Return SyntaxFactory.ParseLeadingTrivia(text) End Function Public Function EscapeIdentifier(identifier As String) As String Implements ISyntaxFacts.EscapeIdentifier Dim keywordKind = SyntaxFacts.GetKeywordKind(identifier) Dim needsEscaping = keywordKind <> SyntaxKind.None Return If(needsEscaping, "[" & identifier & "]", identifier) End Function Public Function IsVerbatimIdentifier(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier Return False End Function Public Function IsOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsOperator Return (IsUnaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is UnaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) OrElse (IsBinaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is BinaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) End Function Public Function IsContextualKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsContextualKeyword Return token.IsContextualKeyword() End Function Public Function IsReservedKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsReservedKeyword Return token.IsReservedKeyword() End Function Public Function IsPreprocessorKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPreprocessorKeyword Return token.IsPreprocessorKeyword() End Function Public Function IsPreProcessorDirectiveContext(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsPreProcessorDirectiveContext Return syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken) End Function Public Function TryGetCorrespondingOpenBrace(token As SyntaxToken, ByRef openBrace As SyntaxToken) As Boolean Implements ISyntaxFacts.TryGetCorrespondingOpenBrace If token.Kind = SyntaxKind.CloseBraceToken Then Dim tuples = token.Parent.GetBraces() openBrace = tuples.openBrace Return openBrace.Kind = SyntaxKind.OpenBraceToken End If Return False End Function Public Function IsEntirelyWithinStringOrCharOrNumericLiteral(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsEntirelyWithinStringOrCharOrNumericLiteral If syntaxTree Is Nothing Then Return False End If Return syntaxTree.IsEntirelyWithinStringOrCharOrNumericLiteral(position, cancellationToken) End Function Public Function IsDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDirective Return TypeOf node Is DirectiveTriviaSyntax End Function Public Function TryGetExternalSourceInfo(node As SyntaxNode, ByRef info As ExternalSourceInfo) As Boolean Implements ISyntaxFacts.TryGetExternalSourceInfo Select Case node.Kind Case SyntaxKind.ExternalSourceDirectiveTrivia info = New ExternalSourceInfo(CInt(DirectCast(node, ExternalSourceDirectiveTriviaSyntax).LineStart.Value), False) Return True Case SyntaxKind.EndExternalSourceDirectiveTrivia info = New ExternalSourceInfo(Nothing, True) Return True End Select Return False End Function Public Function IsDeclarationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationExpression ' VB doesn't support declaration expressions Return False End Function Public Function IsAttributeName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeName Return node.IsParentKind(SyntaxKind.Attribute) AndAlso DirectCast(node.Parent, AttributeSyntax).Name Is node End Function Public Function IsNameOfSimpleMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSimpleMemberAccessExpression Dim vbNode = TryCast(node, ExpressionSyntax) Return vbNode IsNot Nothing AndAlso vbNode.IsSimpleMemberAccessExpressionName() End Function Public Function IsNameOfAnyMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfAnyMemberAccessExpression Dim memberAccess = TryCast(node?.Parent, MemberAccessExpressionSyntax) Return memberAccess IsNot Nothing AndAlso memberAccess.Name Is node End Function Public Function GetStandaloneExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetStandaloneExpression Return SyntaxFactory.GetStandaloneExpression(TryCast(node, ExpressionSyntax)) End Function Public Function GetRootConditionalAccessExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRootConditionalAccessExpression Return TryCast(node, ExpressionSyntax).GetRootConditionalAccessExpression() End Function Public Function IsNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamedArgument Dim arg = TryCast(node, SimpleArgumentSyntax) Return arg?.NameColonEquals IsNot Nothing End Function Public Function IsNameOfNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfNamedArgument Return node.CheckParent(Of SimpleArgumentSyntax)(Function(p) p.IsNamed AndAlso p.NameColonEquals.Name Is node) End Function Public Function GetNameOfParameter(node As SyntaxNode) As SyntaxToken? Implements ISyntaxFacts.GetNameOfParameter Return DirectCast(node, ParameterSyntax).Identifier?.Identifier End Function Public Function GetDefaultOfParameter(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetDefaultOfParameter Return DirectCast(node, ParameterSyntax).Default End Function Public Function GetParameterList(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetParameterList Return node.GetParameterList() End Function Public Function IsParameterList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterList Return node.IsKind(SyntaxKind.ParameterList) End Function Public Function ISyntaxFacts_HasIncompleteParentMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.HasIncompleteParentMember Return HasIncompleteParentMember(node) End Function Public Function GetIdentifierOfGenericName(genericName As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfGenericName Return DirectCast(genericName, GenericNameSyntax).Identifier End Function Public Function IsUsingDirectiveName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingDirectiveName Return node.IsParentKind(SyntaxKind.SimpleImportsClause) AndAlso DirectCast(node.Parent, SimpleImportsClauseSyntax).Name Is node End Function Public Function IsDeconstructionAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionAssignment Return False End Function Public Function IsDeconstructionForEachStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionForEachStatement Return False End Function Public Function IsStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatement Return TypeOf node Is StatementSyntax End Function Public Function IsExecutableStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableStatement Return TypeOf node Is ExecutableStatementSyntax End Function Public Function IsMethodBody(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodBody Return TypeOf node Is MethodBlockBaseSyntax End Function Public Function GetExpressionOfReturnStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfReturnStatement Return DirectCast(node, ReturnStatementSyntax).Expression End Function Public Function IsThisConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsThisConstructorInitializer If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax) Return memberAccess.IsThisConstructorInitializer() End If Return False End Function Public Function IsBaseConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsBaseConstructorInitializer If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax) Return memberAccess.IsBaseConstructorInitializer() End If Return False End Function Public Function IsQueryKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsQueryKeyword Select Case token.Kind() Case _ SyntaxKind.JoinKeyword, SyntaxKind.IntoKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword, SyntaxKind.ByKeyword, SyntaxKind.OrderKeyword, SyntaxKind.WhereKeyword, SyntaxKind.OnKeyword, SyntaxKind.FromKeyword, SyntaxKind.WhileKeyword, SyntaxKind.SelectKeyword Return TypeOf token.Parent Is QueryClauseSyntax Case SyntaxKind.GroupKeyword Return (TypeOf token.Parent Is QueryClauseSyntax) OrElse (token.Parent.IsKind(SyntaxKind.GroupAggregation)) Case SyntaxKind.EqualsKeyword Return TypeOf token.Parent Is JoinConditionSyntax Case SyntaxKind.AscendingKeyword, SyntaxKind.DescendingKeyword Return TypeOf token.Parent Is OrderingSyntax Case SyntaxKind.InKeyword Return TypeOf token.Parent Is CollectionRangeVariableSyntax Case Else Return False End Select End Function Public Function IsPredefinedType(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedType Dim actualType As PredefinedType = PredefinedType.None Return TryGetPredefinedType(token, actualType) AndAlso actualType <> PredefinedType.None End Function Public Function IsPredefinedType(token As SyntaxToken, type As PredefinedType) As Boolean Implements ISyntaxFacts.IsPredefinedType Dim actualType As PredefinedType = PredefinedType.None Return TryGetPredefinedType(token, actualType) AndAlso actualType = type End Function Public Function TryGetPredefinedType(token As SyntaxToken, ByRef type As PredefinedType) As Boolean Implements ISyntaxFacts.TryGetPredefinedType type = GetPredefinedType(token) Return type <> PredefinedType.None End Function Private Shared Function GetPredefinedType(token As SyntaxToken) As PredefinedType Select Case token.Kind Case SyntaxKind.BooleanKeyword Return PredefinedType.Boolean Case SyntaxKind.ByteKeyword Return PredefinedType.Byte Case SyntaxKind.SByteKeyword Return PredefinedType.SByte Case SyntaxKind.IntegerKeyword Return PredefinedType.Int32 Case SyntaxKind.UIntegerKeyword Return PredefinedType.UInt32 Case SyntaxKind.ShortKeyword Return PredefinedType.Int16 Case SyntaxKind.UShortKeyword Return PredefinedType.UInt16 Case SyntaxKind.LongKeyword Return PredefinedType.Int64 Case SyntaxKind.ULongKeyword Return PredefinedType.UInt64 Case SyntaxKind.SingleKeyword Return PredefinedType.Single Case SyntaxKind.DoubleKeyword Return PredefinedType.Double Case SyntaxKind.DecimalKeyword Return PredefinedType.Decimal Case SyntaxKind.StringKeyword Return PredefinedType.String Case SyntaxKind.CharKeyword Return PredefinedType.Char Case SyntaxKind.ObjectKeyword Return PredefinedType.Object Case SyntaxKind.DateKeyword Return PredefinedType.DateTime Case Else Return PredefinedType.None End Select End Function Public Function IsPredefinedOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedOperator Dim actualOp As PredefinedOperator = PredefinedOperator.None Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp <> PredefinedOperator.None End Function Public Function IsPredefinedOperator(token As SyntaxToken, op As PredefinedOperator) As Boolean Implements ISyntaxFacts.IsPredefinedOperator Dim actualOp As PredefinedOperator = PredefinedOperator.None Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp = op End Function Public Function TryGetPredefinedOperator(token As SyntaxToken, ByRef op As PredefinedOperator) As Boolean Implements ISyntaxFacts.TryGetPredefinedOperator op = GetPredefinedOperator(token) Return op <> PredefinedOperator.None End Function Private Shared Function GetPredefinedOperator(token As SyntaxToken) As PredefinedOperator Select Case token.Kind Case SyntaxKind.PlusToken, SyntaxKind.PlusEqualsToken Return PredefinedOperator.Addition Case SyntaxKind.MinusToken, SyntaxKind.MinusEqualsToken Return PredefinedOperator.Subtraction Case SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword Return PredefinedOperator.BitwiseAnd Case SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword Return PredefinedOperator.BitwiseOr Case SyntaxKind.AmpersandToken, SyntaxKind.AmpersandEqualsToken Return PredefinedOperator.Concatenate Case SyntaxKind.SlashToken, SyntaxKind.SlashEqualsToken Return PredefinedOperator.Division Case SyntaxKind.EqualsToken Return PredefinedOperator.Equality Case SyntaxKind.XorKeyword Return PredefinedOperator.ExclusiveOr Case SyntaxKind.CaretToken, SyntaxKind.CaretEqualsToken Return PredefinedOperator.Exponent Case SyntaxKind.GreaterThanToken Return PredefinedOperator.GreaterThan Case SyntaxKind.GreaterThanEqualsToken Return PredefinedOperator.GreaterThanOrEqual Case SyntaxKind.LessThanGreaterThanToken Return PredefinedOperator.Inequality Case SyntaxKind.BackslashToken, SyntaxKind.BackslashEqualsToken Return PredefinedOperator.IntegerDivision Case SyntaxKind.LessThanLessThanToken, SyntaxKind.LessThanLessThanEqualsToken Return PredefinedOperator.LeftShift Case SyntaxKind.LessThanToken Return PredefinedOperator.LessThan Case SyntaxKind.LessThanEqualsToken Return PredefinedOperator.LessThanOrEqual Case SyntaxKind.LikeKeyword Return PredefinedOperator.Like Case SyntaxKind.NotKeyword Return PredefinedOperator.Complement Case SyntaxKind.ModKeyword Return PredefinedOperator.Modulus Case SyntaxKind.AsteriskToken, SyntaxKind.AsteriskEqualsToken Return PredefinedOperator.Multiplication Case SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.GreaterThanGreaterThanEqualsToken Return PredefinedOperator.RightShift Case Else Return PredefinedOperator.None End Select End Function Public Function GetText(kind As Integer) As String Implements ISyntaxFacts.GetText Return SyntaxFacts.GetText(CType(kind, SyntaxKind)) End Function Public Function IsIdentifierPartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierPartCharacter Return SyntaxFacts.IsIdentifierPartCharacter(c) End Function Public Function IsIdentifierStartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierStartCharacter Return SyntaxFacts.IsIdentifierStartCharacter(c) End Function Public Function IsIdentifierEscapeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierEscapeCharacter Return c = "["c OrElse c = "]"c End Function Public Function IsValidIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsValidIdentifier Dim token = SyntaxFactory.ParseToken(identifier) ' TODO: There is no way to get the diagnostics to see if any are actually errors? Return IsIdentifier(token) AndAlso Not token.ContainsDiagnostics AndAlso token.ToString().Length = identifier.Length End Function Public Function IsVerbatimIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier Return IsValidIdentifier(identifier) AndAlso MakeHalfWidthIdentifier(identifier.First()) = "[" AndAlso MakeHalfWidthIdentifier(identifier.Last()) = "]" End Function Public Function IsTypeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsTypeCharacter Return c = "%"c OrElse c = "&"c OrElse c = "@"c OrElse c = "!"c OrElse c = "#"c OrElse c = "$"c End Function Public Function IsStartOfUnicodeEscapeSequence(c As Char) As Boolean Implements ISyntaxFacts.IsStartOfUnicodeEscapeSequence Return False ' VB does not support identifiers with escaped unicode characters End Function Public Function IsLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsLiteral Select Case token.Kind() Case _ SyntaxKind.IntegerLiteralToken, SyntaxKind.CharacterLiteralToken, SyntaxKind.DecimalLiteralToken, SyntaxKind.FloatingLiteralToken, SyntaxKind.DateLiteralToken, SyntaxKind.StringLiteralToken, SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.DoubleQuoteToken, SyntaxKind.InterpolatedStringTextToken, SyntaxKind.TrueKeyword, SyntaxKind.FalseKeyword, SyntaxKind.NothingKeyword Return True End Select Return False End Function Public Function IsStringLiteralOrInterpolatedStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsStringLiteralOrInterpolatedStringLiteral Return token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken) End Function Public Function IsBindableToken(token As Microsoft.CodeAnalysis.SyntaxToken) As Boolean Implements ISyntaxFacts.IsBindableToken Return Me.IsWord(token) OrElse Me.IsLiteral(token) OrElse Me.IsOperator(token) End Function Public Function IsPointerMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPointerMemberAccessExpression Return False End Function Public Sub GetNameAndArityOfSimpleName(node As SyntaxNode, ByRef name As String, ByRef arity As Integer) Implements ISyntaxFacts.GetNameAndArityOfSimpleName Dim simpleName = DirectCast(node, SimpleNameSyntax) name = simpleName.Identifier.ValueText arity = simpleName.Arity End Sub Public Function LooksGeneric(name As SyntaxNode) As Boolean Implements ISyntaxFacts.LooksGeneric Return name.IsKind(SyntaxKind.GenericName) End Function Public Function GetExpressionOfMemberAccessExpression(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfMemberAccessExpression Return TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget) End Function Public Function GetTargetOfMemberBinding(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTargetOfMemberBinding ' Member bindings are a C# concept. Return Nothing End Function Public Function GetNameOfMemberBindingExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberBindingExpression ' Member bindings are a C# concept. Return Nothing End Function Public Sub GetPartsOfElementAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfElementAccessExpression Dim invocation = TryCast(node, InvocationExpressionSyntax) If invocation IsNot Nothing Then expression = invocation?.Expression argumentList = invocation?.ArgumentList Return End If If node.Kind() = SyntaxKind.DictionaryAccessExpression Then GetPartsOfMemberAccessExpression(node, expression, argumentList) Return End If Throw ExceptionUtilities.UnexpectedValue(node.Kind()) End Sub Public Function GetExpressionOfInterpolation(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfInterpolation Return DirectCast(node, InterpolationSyntax).Expression End Function Public Function IsInNamespaceOrTypeContext(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInNamespaceOrTypeContext Return SyntaxFacts.IsInNamespaceOrTypeContext(node) End Function Public Function IsBaseTypeList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBaseTypeList Return TryCast(node, InheritsOrImplementsStatementSyntax) IsNot Nothing End Function Public Function IsInStaticContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInStaticContext Return node.IsInStaticContext() End Function Public Function GetExpressionOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetExpressionOfArgument Return DirectCast(node, ArgumentSyntax).GetArgumentExpression() End Function Public Function GetRefKindOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.RefKind Implements ISyntaxFacts.GetRefKindOfArgument ' TODO(cyrusn): Consider the method this argument is passed to, to determine this. Return RefKind.None End Function Public Function IsArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsArgument Return TypeOf node Is ArgumentSyntax End Function Public Function IsSimpleArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleArgument Dim argument = TryCast(node, ArgumentSyntax) Return argument IsNot Nothing AndAlso Not argument.IsNamed AndAlso Not argument.IsOmitted End Function Public Function IsInConstantContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstantContext Return node.IsInConstantContext() End Function Public Function IsInConstructor(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstructor Return node.GetAncestors(Of StatementSyntax).Any(Function(s) s.Kind = SyntaxKind.ConstructorBlock) End Function Public Function IsUnsafeContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnsafeContext Return False End Function Public Function GetNameOfAttribute(node As SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetNameOfAttribute Return DirectCast(node, AttributeSyntax).Name End Function Public Function IsAttributeNamedArgumentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeNamedArgumentIdentifier Dim identifierName = TryCast(node, IdentifierNameSyntax) Return identifierName.IsParentKind(SyntaxKind.NameColonEquals) AndAlso identifierName.Parent.IsParentKind(SyntaxKind.SimpleArgument) AndAlso identifierName.Parent.Parent.IsParentKind(SyntaxKind.ArgumentList) AndAlso identifierName.Parent.Parent.Parent.IsParentKind(SyntaxKind.Attribute) End Function Public Function GetContainingTypeDeclaration(root As SyntaxNode, position As Integer) As SyntaxNode Implements ISyntaxFacts.GetContainingTypeDeclaration If root Is Nothing Then Throw New ArgumentNullException(NameOf(root)) End If If position < 0 OrElse position > root.Span.End Then Throw New ArgumentOutOfRangeException(NameOf(position)) End If Return root. FindToken(position). GetAncestors(Of SyntaxNode)(). FirstOrDefault(Function(n) TypeOf n Is TypeBlockSyntax OrElse TypeOf n Is DelegateStatementSyntax) End Function Public Function GetContainingVariableDeclaratorOfFieldDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetContainingVariableDeclaratorOfFieldDeclaration If node Is Nothing Then Throw New ArgumentNullException(NameOf(node)) End If Dim parent = node.Parent While node IsNot Nothing If node.Kind = SyntaxKind.VariableDeclarator AndAlso node.IsParentKind(SyntaxKind.FieldDeclaration) Then Return node End If node = node.Parent End While Return Nothing End Function Public Function IsMemberInitializerNamedAssignmentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier Dim unused As SyntaxNode = Nothing Return IsMemberInitializerNamedAssignmentIdentifier(node, unused) End Function Public Function IsMemberInitializerNamedAssignmentIdentifier( node As SyntaxNode, ByRef initializedInstance As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier Dim identifier = TryCast(node, IdentifierNameSyntax) If identifier?.IsChildNode(Of NamedFieldInitializerSyntax)(Function(n) n.Name) Then ' .parent is the NamedField. ' .parent.parent is the ObjectInitializer. ' .parent.parent.parent will be the ObjectCreationExpression. initializedInstance = identifier.Parent.Parent.Parent Return True End If Return False End Function Public Function IsNameOfSubpattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSubpattern Return False End Function Public Function IsPropertyPatternClause(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPropertyPatternClause Return False End Function Public Function IsElementAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsElementAccessExpression ' VB doesn't have a specialized node for element access. Instead, it just uses an ' invocation expression or dictionary access expression. Return node.Kind = SyntaxKind.InvocationExpression OrElse node.Kind = SyntaxKind.DictionaryAccessExpression End Function Public Function IsIndexerMemberCRef(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIndexerMemberCRef Return False End Function Public Function GetContainingMemberDeclaration(root As SyntaxNode, position As Integer, Optional useFullSpan As Boolean = True) As SyntaxNode Implements ISyntaxFacts.GetContainingMemberDeclaration Contract.ThrowIfNull(root, NameOf(root)) Contract.ThrowIfTrue(position < 0 OrElse position > root.FullSpan.End, NameOf(position)) Dim [end] = root.FullSpan.End If [end] = 0 Then ' empty file Return Nothing End If ' make sure position doesn't touch end of root position = Math.Min(position, [end] - 1) Dim node = root.FindToken(position).Parent While node IsNot Nothing If useFullSpan OrElse node.Span.Contains(position) Then If TypeOf node Is MethodBlockBaseSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return node End If If TypeOf node Is MethodBaseSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return node End If If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return node End If If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then Return node End If If TypeOf node Is PropertyBlockSyntax OrElse TypeOf node Is TypeBlockSyntax OrElse TypeOf node Is EnumBlockSyntax OrElse TypeOf node Is NamespaceBlockSyntax OrElse TypeOf node Is EventBlockSyntax OrElse TypeOf node Is FieldDeclarationSyntax Then Return node End If End If node = node.Parent End While Return Nothing End Function Public Function IsMethodLevelMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodLevelMember ' Note: Derived types of MethodBaseSyntax are expanded explicitly, since PropertyStatementSyntax and ' EventStatementSyntax will NOT be parented by MethodBlockBaseSyntax. Additionally, there are things ' like AccessorStatementSyntax and DelegateStatementSyntax that we never want to tread as method level ' members. If TypeOf node Is MethodStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is SubNewStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is OperatorStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return True End If If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then Return True End If If TypeOf node Is DeclareStatementSyntax Then Return True End If Return TypeOf node Is ConstructorBlockSyntax OrElse TypeOf node Is MethodBlockSyntax OrElse TypeOf node Is OperatorBlockSyntax OrElse TypeOf node Is EventBlockSyntax OrElse TypeOf node Is PropertyBlockSyntax OrElse TypeOf node Is EnumMemberDeclarationSyntax OrElse TypeOf node Is FieldDeclarationSyntax End Function Public Function GetMemberBodySpanForSpeculativeBinding(node As SyntaxNode) As TextSpan Implements ISyntaxFacts.GetMemberBodySpanForSpeculativeBinding Dim member = GetContainingMemberDeclaration(node, node.SpanStart) If member Is Nothing Then Return Nothing End If ' TODO: currently we only support method for now Dim method = TryCast(member, MethodBlockBaseSyntax) If method IsNot Nothing Then If method.BlockStatement Is Nothing OrElse method.EndBlockStatement Is Nothing Then Return Nothing End If ' We don't want to include the BlockStatement or any trailing trivia up to and including its statement ' terminator in the span. Instead, we use the start of the first statement's leading trivia (if any) up ' to the start of the EndBlockStatement. If there aren't any statements in the block, we use the start ' of the EndBlockStatements leading trivia. Dim firstStatement = method.Statements.FirstOrDefault() Dim spanStart = If(firstStatement IsNot Nothing, firstStatement.FullSpan.Start, method.EndBlockStatement.FullSpan.Start) Return TextSpan.FromBounds(spanStart, method.EndBlockStatement.SpanStart) End If Return Nothing End Function Public Function ContainsInMemberBody(node As SyntaxNode, span As TextSpan) As Boolean Implements ISyntaxFacts.ContainsInMemberBody Dim method = TryCast(node, MethodBlockBaseSyntax) If method IsNot Nothing Then Return method.Statements.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan(method.Statements), span) End If Dim [event] = TryCast(node, EventBlockSyntax) If [event] IsNot Nothing Then Return [event].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([event].Accessors), span) End If Dim [property] = TryCast(node, PropertyBlockSyntax) If [property] IsNot Nothing Then Return [property].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([property].Accessors), span) End If Dim field = TryCast(node, FieldDeclarationSyntax) If field IsNot Nothing Then Return field.Declarators.Count > 0 AndAlso ContainsExclusively(GetSeparatedSyntaxListSpan(field.Declarators), span) End If Dim [enum] = TryCast(node, EnumMemberDeclarationSyntax) If [enum] IsNot Nothing Then Return [enum].Initializer IsNot Nothing AndAlso ContainsExclusively([enum].Initializer.Span, span) End If Dim propStatement = TryCast(node, PropertyStatementSyntax) If propStatement IsNot Nothing Then Return propStatement.Initializer IsNot Nothing AndAlso ContainsExclusively(propStatement.Initializer.Span, span) End If Return False End Function Private Shared Function ContainsExclusively(outerSpan As TextSpan, innerSpan As TextSpan) As Boolean If innerSpan.IsEmpty Then Return outerSpan.Contains(innerSpan.Start) End If Return outerSpan.Contains(innerSpan) End Function Private Shared Function GetSyntaxListSpan(Of T As SyntaxNode)(list As SyntaxList(Of T)) As TextSpan Debug.Assert(list.Count > 0) Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End) End Function Private Shared Function GetSeparatedSyntaxListSpan(Of T As SyntaxNode)(list As SeparatedSyntaxList(Of T)) As TextSpan Debug.Assert(list.Count > 0) Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End) End Function Public Function GetTopLevelAndMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetTopLevelAndMethodLevelMembers Dim list = New List(Of SyntaxNode)() AppendMembers(root, list, topLevel:=True, methodLevel:=True) Return list End Function Public Function GetMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetMethodLevelMembers Dim list = New List(Of SyntaxNode)() AppendMembers(root, list, topLevel:=False, methodLevel:=True) Return list End Function Public Function GetMembersOfTypeDeclaration(typeDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfTypeDeclaration Return DirectCast(typeDeclaration, TypeBlockSyntax).Members End Function Public Function IsTopLevelNodeWithMembers(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTopLevelNodeWithMembers Return TypeOf node Is NamespaceBlockSyntax OrElse TypeOf node Is TypeBlockSyntax OrElse TypeOf node Is EnumBlockSyntax End Function Private Const s_dotToken As String = "." Public Function GetDisplayName(node As SyntaxNode, options As DisplayNameOptions, Optional rootNamespace As String = Nothing) As String Implements ISyntaxFacts.GetDisplayName If node Is Nothing Then Return String.Empty End If Dim pooled = PooledStringBuilder.GetInstance() Dim builder = pooled.Builder ' member keyword (if any) Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax) If (options And DisplayNameOptions.IncludeMemberKeyword) <> 0 Then Dim keywordToken = memberDeclaration.GetMemberKeywordToken() If keywordToken <> Nothing AndAlso Not keywordToken.IsMissing Then builder.Append(keywordToken.Text) builder.Append(" "c) End If End If Dim names = ArrayBuilder(Of String).GetInstance() ' containing type(s) Dim parent = node.Parent While TypeOf parent Is TypeBlockSyntax names.Push(GetName(parent, options, containsGlobalKeyword:=False)) parent = parent.Parent End While If (options And DisplayNameOptions.IncludeNamespaces) <> 0 Then ' containing namespace(s) in source (if any) Dim containsGlobalKeyword As Boolean = False While parent IsNot Nothing AndAlso parent.Kind() = SyntaxKind.NamespaceBlock names.Push(GetName(parent, options, containsGlobalKeyword)) parent = parent.Parent End While ' root namespace (if any) If Not containsGlobalKeyword AndAlso Not String.IsNullOrEmpty(rootNamespace) Then builder.Append(rootNamespace) builder.Append(s_dotToken) End If End If While Not names.IsEmpty() Dim name = names.Pop() If name IsNot Nothing Then builder.Append(name) builder.Append(s_dotToken) End If End While names.Free() ' name (include generic type parameters) builder.Append(GetName(node, options, containsGlobalKeyword:=False)) ' parameter list (if any) If (options And DisplayNameOptions.IncludeParameters) <> 0 Then builder.Append(memberDeclaration.GetParameterList()) End If ' As clause (if any) If (options And DisplayNameOptions.IncludeType) <> 0 Then Dim asClause = memberDeclaration.GetAsClause() If asClause IsNot Nothing Then builder.Append(" "c) builder.Append(asClause) End If End If Return pooled.ToStringAndFree() End Function Private Shared Function GetName(node As SyntaxNode, options As DisplayNameOptions, ByRef containsGlobalKeyword As Boolean) As String Const missingTokenPlaceholder As String = "?" Select Case node.Kind() Case SyntaxKind.CompilationUnit Return Nothing Case SyntaxKind.IdentifierName Dim identifier = DirectCast(node, IdentifierNameSyntax).Identifier Return If(identifier.IsMissing, missingTokenPlaceholder, identifier.Text) Case SyntaxKind.IncompleteMember Return missingTokenPlaceholder Case SyntaxKind.NamespaceBlock Dim nameSyntax = CType(node, NamespaceBlockSyntax).NamespaceStatement.Name If nameSyntax.Kind() = SyntaxKind.GlobalName Then containsGlobalKeyword = True Return Nothing Else Return GetName(nameSyntax, options, containsGlobalKeyword) End If Case SyntaxKind.QualifiedName Dim qualified = CType(node, QualifiedNameSyntax) If qualified.Left.Kind() = SyntaxKind.GlobalName Then containsGlobalKeyword = True Return GetName(qualified.Right, options, containsGlobalKeyword) ' don't use the Global prefix if specified Else Return GetName(qualified.Left, options, containsGlobalKeyword) + s_dotToken + GetName(qualified.Right, options, containsGlobalKeyword) End If End Select Dim name As String = Nothing Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax) If memberDeclaration IsNot Nothing Then Dim nameToken = memberDeclaration.GetNameToken() If nameToken <> Nothing Then name = If(nameToken.IsMissing, missingTokenPlaceholder, nameToken.Text) If (options And DisplayNameOptions.IncludeTypeParameters) <> 0 Then Dim pooled = PooledStringBuilder.GetInstance() Dim builder = pooled.Builder builder.Append(name) AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList()) name = pooled.ToStringAndFree() End If End If End If Debug.Assert(name IsNot Nothing, "Unexpected node type " + node.Kind().ToString()) Return name End Function Private Shared Sub AppendTypeParameterList(builder As StringBuilder, typeParameterList As TypeParameterListSyntax) If typeParameterList IsNot Nothing AndAlso typeParameterList.Parameters.Count > 0 Then builder.Append("(Of ") builder.Append(typeParameterList.Parameters(0).Identifier.Text) For i = 1 To typeParameterList.Parameters.Count - 1 builder.Append(", ") builder.Append(typeParameterList.Parameters(i).Identifier.Text) Next builder.Append(")"c) End If End Sub Private Sub AppendMembers(node As SyntaxNode, list As List(Of SyntaxNode), topLevel As Boolean, methodLevel As Boolean) Debug.Assert(topLevel OrElse methodLevel) For Each member In node.GetMembers() If IsTopLevelNodeWithMembers(member) Then If topLevel Then list.Add(member) End If AppendMembers(member, list, topLevel, methodLevel) Continue For End If If methodLevel AndAlso IsMethodLevelMember(member) Then list.Add(member) End If Next End Sub Public Function TryGetBindableParent(token As SyntaxToken) As SyntaxNode Implements ISyntaxFacts.TryGetBindableParent Dim node = token.Parent While node IsNot Nothing Dim parent = node.Parent ' If this node is on the left side of a member access expression, don't ascend ' further or we'll end up binding to something else. Dim memberAccess = TryCast(parent, MemberAccessExpressionSyntax) If memberAccess IsNot Nothing Then If memberAccess.Expression Is node Then Exit While End If End If ' If this node is on the left side of a qualified name, don't ascend ' further or we'll end up binding to something else. Dim qualifiedName = TryCast(parent, QualifiedNameSyntax) If qualifiedName IsNot Nothing Then If qualifiedName.Left Is node Then Exit While End If End If ' If this node is the type of an object creation expression, return the ' object creation expression. Dim objectCreation = TryCast(parent, ObjectCreationExpressionSyntax) If objectCreation IsNot Nothing Then If objectCreation.Type Is node Then node = parent Exit While End If End If ' The inside of an interpolated string is treated as its own token so we ' need to force navigation to the parent expression syntax. If TypeOf node Is InterpolatedStringTextSyntax AndAlso TypeOf parent Is InterpolatedStringExpressionSyntax Then node = parent Exit While End If ' If this node is not parented by a name, we're done. Dim name = TryCast(parent, NameSyntax) If name Is Nothing Then Exit While End If node = parent End While Return node End Function Public Function GetConstructors(root As SyntaxNode, cancellationToken As CancellationToken) As IEnumerable(Of SyntaxNode) Implements ISyntaxFacts.GetConstructors Dim compilationUnit = TryCast(root, CompilationUnitSyntax) If compilationUnit Is Nothing Then Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If Dim constructors = New List(Of SyntaxNode)() AppendConstructors(compilationUnit.Members, constructors, cancellationToken) Return constructors End Function Private Sub AppendConstructors(members As SyntaxList(Of StatementSyntax), constructors As List(Of SyntaxNode), cancellationToken As CancellationToken) For Each member As StatementSyntax In members cancellationToken.ThrowIfCancellationRequested() Dim constructor = TryCast(member, ConstructorBlockSyntax) If constructor IsNot Nothing Then constructors.Add(constructor) Continue For End If Dim [namespace] = TryCast(member, NamespaceBlockSyntax) If [namespace] IsNot Nothing Then AppendConstructors([namespace].Members, constructors, cancellationToken) End If Dim [class] = TryCast(member, ClassBlockSyntax) If [class] IsNot Nothing Then AppendConstructors([class].Members, constructors, cancellationToken) End If Dim [struct] = TryCast(member, StructureBlockSyntax) If [struct] IsNot Nothing Then AppendConstructors([struct].Members, constructors, cancellationToken) End If Next End Sub Public Function GetInactiveRegionSpanAroundPosition(tree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As TextSpan Implements ISyntaxFacts.GetInactiveRegionSpanAroundPosition Dim trivia = tree.FindTriviaToLeft(position, cancellationToken) If trivia.Kind = SyntaxKind.DisabledTextTrivia Then Return trivia.FullSpan End If Return Nothing End Function Public Function GetNameForArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForArgument If TryCast(argument, ArgumentSyntax)?.IsNamed Then Return DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.Identifier.ValueText End If Return String.Empty End Function Public Function GetNameForAttributeArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForAttributeArgument ' All argument types are ArgumentSyntax in VB. Return GetNameForArgument(argument) End Function Public Function IsLeftSideOfDot(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfDot Return TryCast(node, ExpressionSyntax).IsLeftSideOfDot() End Function Public Function GetRightSideOfDot(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightSideOfDot Return If(TryCast(node, QualifiedNameSyntax)?.Right, TryCast(node, MemberAccessExpressionSyntax)?.Name) End Function Public Function GetLeftSideOfDot(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetLeftSideOfDot Return If(TryCast(node, QualifiedNameSyntax)?.Left, TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget)) End Function Public Function IsLeftSideOfExplicitInterfaceSpecifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfExplicitInterfaceSpecifier Return IsLeftSideOfDot(node) AndAlso TryCast(node.Parent.Parent, ImplementsClauseSyntax) IsNot Nothing End Function Public Function IsLeftSideOfAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfSimpleAssignmentStatement End Function Public Function IsLeftSideOfAnyAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAnyAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfAnyAssignmentStatement End Function Public Function IsLeftSideOfCompoundAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfCompoundAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfCompoundAssignmentStatement End Function Public Function GetRightHandSideOfAssignment(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightHandSideOfAssignment Return DirectCast(node, AssignmentStatementSyntax).Right End Function Public Function IsInferredAnonymousObjectMemberDeclarator(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInferredAnonymousObjectMemberDeclarator Return node.IsKind(SyntaxKind.InferredFieldInitializer) End Function Public Function IsOperandOfIncrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementExpression Return False End Function Public Function IsOperandOfIncrementOrDecrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementOrDecrementExpression Return False End Function Public Function GetContentsOfInterpolatedString(interpolatedString As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentsOfInterpolatedString Return (TryCast(interpolatedString, InterpolatedStringExpressionSyntax)?.Contents).Value End Function Public Function IsNumericLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsNumericLiteral Return token.Kind = SyntaxKind.DecimalLiteralToken OrElse token.Kind = SyntaxKind.FloatingLiteralToken OrElse token.Kind = SyntaxKind.IntegerLiteralToken End Function Public Function IsVerbatimStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimStringLiteral ' VB does not have verbatim strings Return False End Function Public Function GetArgumentsOfInvocationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfInvocationExpression Dim argumentList = DirectCast(node, InvocationExpressionSyntax).ArgumentList Return If(argumentList Is Nothing, Nothing, GetArgumentsOfArgumentList(argumentList)) End Function Public Function GetArgumentsOfObjectCreationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfObjectCreationExpression Dim argumentList = DirectCast(node, ObjectCreationExpressionSyntax).ArgumentList Return If(argumentList Is Nothing, Nothing, GetArgumentsOfArgumentList(argumentList)) End Function Public Function GetArgumentsOfArgumentList(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfArgumentList Return DirectCast(node, ArgumentListSyntax).Arguments End Function Public Function ConvertToSingleLine(node As SyntaxNode, Optional useElasticTrivia As Boolean = False) As SyntaxNode Implements ISyntaxFacts.ConvertToSingleLine Return node.ConvertToSingleLine(useElasticTrivia) End Function Public Function IsDocumentationComment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDocumentationComment Return node.IsKind(SyntaxKind.DocumentationCommentTrivia) End Function Public Function IsUsingOrExternOrImport(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingOrExternOrImport Return node.IsKind(SyntaxKind.ImportsStatement) End Function Public Function IsGlobalAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalAssemblyAttribute Return IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword) End Function Public Function IsModuleAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalModuleAttribute Return IsGlobalAttribute(node, SyntaxKind.ModuleKeyword) End Function Private Shared Function IsGlobalAttribute(node As SyntaxNode, attributeTarget As SyntaxKind) As Boolean If node.IsKind(SyntaxKind.Attribute) Then Dim attributeNode = CType(node, AttributeSyntax) If attributeNode.Target IsNot Nothing Then Return attributeNode.Target.AttributeModifier.IsKind(attributeTarget) End If End If Return False End Function Public Function IsDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaration ' From the Visual Basic language spec: ' NamespaceMemberDeclaration := ' NamespaceDeclaration | ' TypeDeclaration ' TypeDeclaration ::= ' ModuleDeclaration | ' NonModuleDeclaration ' NonModuleDeclaration ::= ' EnumDeclaration | ' StructureDeclaration | ' InterfaceDeclaration | ' ClassDeclaration | ' DelegateDeclaration ' ClassMemberDeclaration ::= ' NonModuleDeclaration | ' EventMemberDeclaration | ' VariableMemberDeclaration | ' ConstantMemberDeclaration | ' MethodMemberDeclaration | ' PropertyMemberDeclaration | ' ConstructorMemberDeclaration | ' OperatorDeclaration Select Case node.Kind() ' Because fields declarations can define multiple symbols "Public a, b As Integer" ' We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name. Case SyntaxKind.VariableDeclarator If (node.Parent.IsKind(SyntaxKind.FieldDeclaration)) Then Return True End If Return False Case SyntaxKind.NamespaceStatement, SyntaxKind.NamespaceBlock, SyntaxKind.ModuleStatement, SyntaxKind.ModuleBlock, SyntaxKind.EnumStatement, SyntaxKind.EnumBlock, SyntaxKind.StructureStatement, SyntaxKind.StructureBlock, SyntaxKind.InterfaceStatement, SyntaxKind.InterfaceBlock, SyntaxKind.ClassStatement, SyntaxKind.ClassBlock, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement, SyntaxKind.EventStatement, SyntaxKind.EventBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.FieldDeclaration, SyntaxKind.SubStatement, SyntaxKind.SubBlock, SyntaxKind.FunctionStatement, SyntaxKind.FunctionBlock, SyntaxKind.PropertyStatement, SyntaxKind.PropertyBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.SubNewStatement, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorStatement, SyntaxKind.OperatorBlock Return True End Select Return False End Function ' TypeDeclaration ::= ' ModuleDeclaration | ' NonModuleDeclaration ' NonModuleDeclaration ::= ' EnumDeclaration | ' StructureDeclaration | ' InterfaceDeclaration | ' ClassDeclaration | ' DelegateDeclaration Public Function IsTypeDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeDeclaration Select Case node.Kind() Case SyntaxKind.EnumBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ClassBlock, SyntaxKind.ModuleBlock, SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return True End Select Return False End Function Public Function IsSimpleAssignmentStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleAssignmentStatement Return node.IsKind(SyntaxKind.SimpleAssignmentStatement) End Function Public Sub GetPartsOfAssignmentStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentStatement ' VB only has assignment statements, so this can just delegate to that helper GetPartsOfAssignmentExpressionOrStatement(statement, left, operatorToken, right) End Sub Public Sub GetPartsOfAssignmentExpressionOrStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentExpressionOrStatement Dim assignment = DirectCast(statement, AssignmentStatementSyntax) left = assignment.Left operatorToken = assignment.OperatorToken right = assignment.Right End Sub Public Function GetIdentifierOfSimpleName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfSimpleName Return DirectCast(node, SimpleNameSyntax).Identifier End Function Public Function GetIdentifierOfVariableDeclarator(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfVariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Names.Last().Identifier End Function Public Function GetIdentifierOfParameter(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfParameter Return DirectCast(node, ParameterSyntax).Identifier.Identifier End Function Public Function GetIdentifierOfTypeDeclaration(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfTypeDeclaration Select Case node.Kind() Case SyntaxKind.EnumStatement, SyntaxKind.StructureStatement, SyntaxKind.InterfaceStatement, SyntaxKind.ClassStatement, SyntaxKind.ModuleStatement Return DirectCast(node, TypeStatementSyntax).Identifier Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return DirectCast(node, DelegateStatementSyntax).Identifier End Select Throw ExceptionUtilities.UnexpectedValue(node) End Function Public Function GetIdentifierOfIdentifierName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfIdentifierName Return DirectCast(node, IdentifierNameSyntax).Identifier End Function Public Function IsDeclaratorOfLocalDeclarationStatement(declarator As SyntaxNode, localDeclarationStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaratorOfLocalDeclarationStatement Return DirectCast(localDeclarationStatement, LocalDeclarationStatementSyntax).Declarators. Contains(DirectCast(declarator, VariableDeclaratorSyntax)) End Function Public Function AreEquivalent(token1 As SyntaxToken, token2 As SyntaxToken) As Boolean Implements ISyntaxFacts.AreEquivalent Return SyntaxFactory.AreEquivalent(token1, token2) End Function Public Function AreEquivalent(node1 As SyntaxNode, node2 As SyntaxNode) As Boolean Implements ISyntaxFacts.AreEquivalent Return SyntaxFactory.AreEquivalent(node1, node2) End Function Public Function IsExpressionOfForeach(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfForeach Return node IsNot Nothing AndAlso TryCast(node.Parent, ForEachStatementSyntax)?.Expression Is node End Function Public Function GetExpressionOfExpressionStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfExpressionStatement Return DirectCast(node, ExpressionStatementSyntax).Expression End Function Public Function IsIsExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsExpression Return node.IsKind(SyntaxKind.TypeOfIsExpression) End Function Public Function WalkDownParentheses(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.WalkDownParentheses Return If(TryCast(node, ExpressionSyntax)?.WalkDownParentheses(), node) End Function Public Sub GetPartsOfTupleExpression(Of TArgumentSyntax As SyntaxNode)( node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef arguments As SeparatedSyntaxList(Of TArgumentSyntax), ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfTupleExpression Dim tupleExpr = DirectCast(node, TupleExpressionSyntax) openParen = tupleExpr.OpenParenToken arguments = CType(CType(tupleExpr.Arguments, SeparatedSyntaxList(Of SyntaxNode)), SeparatedSyntaxList(Of TArgumentSyntax)) closeParen = tupleExpr.CloseParenToken End Sub Private Function ISyntaxFacts_IsSingleLineCommentTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsSingleLineCommentTrivia Return MyBase.IsSingleLineCommentTrivia(trivia) End Function Private Function ISyntaxFacts_IsMultiLineCommentTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsMultiLineCommentTrivia Return MyBase.IsMultiLineCommentTrivia(trivia) End Function Private Function ISyntaxFacts_IsSingleLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsSingleLineDocCommentTrivia Return MyBase.IsSingleLineDocCommentTrivia(trivia) End Function Private Function ISyntaxFacts_IsMultiLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsMultiLineDocCommentTrivia Return MyBase.IsMultiLineDocCommentTrivia(trivia) Return False End Function Private Function ISyntaxFacts_IsShebangDirectiveTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsShebangDirectiveTrivia Return MyBase.IsShebangDirectiveTrivia(trivia) End Function Public Overrides Function IsPreprocessorDirective(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsPreprocessorDirective Return SyntaxFacts.IsPreprocessorDirective(trivia.Kind()) End Function Public Function IsRegularComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsRegularComment Return trivia.Kind = SyntaxKind.CommentTrivia End Function Public Function IsDocumentationComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationComment Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia End Function Public Function IsElastic(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsElastic Return trivia.IsElastic() End Function Public Function IsPragmaDirective(trivia As SyntaxTrivia, ByRef isDisable As Boolean, ByRef isActive As Boolean, ByRef errorCodes As SeparatedSyntaxList(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.IsPragmaDirective Return trivia.IsPragmaDirective(isDisable, isActive, errorCodes) End Function Protected Overrides Function ContainsInterleavedDirective(span As TextSpan, token As SyntaxToken, cancellationToken As CancellationToken) As Boolean Return token.ContainsInterleavedDirective(span, cancellationToken) End Function Private Function ISyntaxFacts_ContainsInterleavedDirective(node As SyntaxNode, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective Return ContainsInterleavedDirective(node, cancellationToken) End Function Private Function ISyntaxFacts_ContainsInterleavedDirective1(nodes As ImmutableArray(Of SyntaxNode), cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective Return ContainsInterleavedDirective(nodes, cancellationToken) End Function Public Function IsDocumentationCommentExteriorTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationCommentExteriorTrivia Return trivia.Kind() = SyntaxKind.DocumentationCommentExteriorTrivia End Function Public Function GetModifiers(node As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifiers Return node.GetModifiers() End Function Public Function WithModifiers(node As SyntaxNode, modifiers As SyntaxTokenList) As SyntaxNode Implements ISyntaxFacts.WithModifiers Return node.WithModifiers(modifiers) End Function Public Function GetVariablesOfLocalDeclarationStatement(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetVariablesOfLocalDeclarationStatement Return DirectCast(node, LocalDeclarationStatementSyntax).Declarators End Function Public Function GetInitializerOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetInitializerOfVariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Initializer End Function Public Function GetTypeOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfVariableDeclarator Dim declarator = DirectCast(node, VariableDeclaratorSyntax) Return TryCast(declarator.AsClause, SimpleAsClauseSyntax)?.Type End Function Public Function GetValueOfEqualsValueClause(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetValueOfEqualsValueClause Return DirectCast(node, EqualsValueSyntax).Value End Function Public Function IsScopeBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsScopeBlock ' VB has no equivalent of curly braces. Return False End Function Public Function IsExecutableBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableBlock Return node.IsExecutableBlock() End Function Public Function GetExecutableBlockStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetExecutableBlockStatements Return node.GetExecutableBlockStatements() End Function Public Function FindInnermostCommonExecutableBlock(nodes As IEnumerable(Of SyntaxNode)) As SyntaxNode Implements ISyntaxFacts.FindInnermostCommonExecutableBlock Return nodes.FindInnermostCommonExecutableBlock() End Function Public Function IsStatementContainer(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatementContainer Return IsExecutableBlock(node) End Function Public Function GetStatementContainerStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetStatementContainerStatements Return GetExecutableBlockStatements(node) End Function Public Function IsConversionExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConversionExpression Return node.Kind = SyntaxKind.CTypeExpression End Function Public Function IsCastExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsCastExpression Return node.Kind = SyntaxKind.DirectCastExpression End Function Public Sub GetPartsOfCastExpression(node As SyntaxNode, ByRef type As SyntaxNode, ByRef expression As SyntaxNode) Implements ISyntaxFacts.GetPartsOfCastExpression Dim cast = DirectCast(node, DirectCastExpressionSyntax) type = cast.Type expression = cast.Expression End Sub Public Function GetDeconstructionReferenceLocation(node As SyntaxNode) As Location Implements ISyntaxFacts.GetDeconstructionReferenceLocation Throw New NotImplementedException() End Function Public Function GetDeclarationIdentifierIfOverride(token As SyntaxToken) As SyntaxToken? Implements ISyntaxFacts.GetDeclarationIdentifierIfOverride If token.Kind() = SyntaxKind.OverridesKeyword Then Dim parent = token.Parent Select Case parent.Kind() Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Dim method = DirectCast(parent, MethodStatementSyntax) Return method.Identifier Case SyntaxKind.PropertyStatement Dim [property] = DirectCast(parent, PropertyStatementSyntax) Return [property].Identifier End Select End If Return Nothing End Function Public Shadows Function SpansPreprocessorDirective(nodes As IEnumerable(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.SpansPreprocessorDirective Return MyBase.SpansPreprocessorDirective(nodes) End Function Public Shadows Function SpansPreprocessorDirective(tokens As IEnumerable(Of SyntaxToken)) As Boolean Return MyBase.SpansPreprocessorDirective(tokens) End Function Public Function IsPostfixUnaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPostfixUnaryExpression ' Does not exist in VB. Return False End Function Public Function IsMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberBindingExpression ' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target. Return False End Function Public Function IsNameOfMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfMemberBindingExpression ' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target. Return False End Function Public Overrides Function GetAttributeLists(node As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetAttributeLists Return node.GetAttributeLists() End Function Public Function IsUsingAliasDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingAliasDirective Dim importStatement = TryCast(node, ImportsStatementSyntax) If (importStatement IsNot Nothing) Then For Each importsClause In importStatement.ImportsClauses If importsClause.Kind = SyntaxKind.SimpleImportsClause Then Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax) If simpleImportsClause.Alias IsNot Nothing Then Return True End If End If Next End If Return False End Function Public Sub GetPartsOfUsingAliasDirective( node As SyntaxNode, ByRef globalKeyword As SyntaxToken, ByRef [alias] As SyntaxToken, ByRef name As SyntaxNode) Implements ISyntaxFacts.GetPartsOfUsingAliasDirective Dim importStatement = DirectCast(node, ImportsStatementSyntax) For Each importsClause In importStatement.ImportsClauses If importsClause.Kind = SyntaxKind.SimpleImportsClause Then Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax) If simpleImportsClause.Alias IsNot Nothing Then globalKeyword = Nothing [alias] = simpleImportsClause.Alias.Identifier name = simpleImportsClause.Name Return End If End If Next Throw ExceptionUtilities.Unreachable End Sub Public Overrides Function IsParameterNameXmlElementSyntax(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterNameXmlElementSyntax Dim xmlElement = TryCast(node, XmlElementSyntax) If xmlElement IsNot Nothing Then Dim name = TryCast(xmlElement.StartTag.Name, XmlNameSyntax) Return name?.LocalName.ValueText = DocumentationCommentXmlNames.ParameterElementName End If Return False End Function Public Overrides Function GetContentFromDocumentationCommentTriviaSyntax(trivia As SyntaxTrivia) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentFromDocumentationCommentTriviaSyntax Dim documentationCommentTrivia = TryCast(trivia.GetStructure(), DocumentationCommentTriviaSyntax) If documentationCommentTrivia IsNot Nothing Then Return documentationCommentTrivia.Content End If Return Nothing End Function Friend Shared Function IsChildOf(node As SyntaxNode, kind As SyntaxKind) As Boolean Return node.Parent IsNot Nothing AndAlso node.Parent.IsKind(kind) End Function Friend Shared Function IsChildOfVariableDeclaration(node As SyntaxNode) As Boolean Return IsChildOf(node, SyntaxKind.FieldDeclaration) OrElse IsChildOf(node, SyntaxKind.LocalDeclarationStatement) End Function Private Shared Function GetDeclarationCount(nodes As IReadOnlyList(Of SyntaxNode)) As Integer Dim count As Integer = 0 For i = 0 To nodes.Count - 1 count = count + GetDeclarationCount(nodes(i)) Next Return count End Function Friend Shared Function GetDeclarationCount(node As SyntaxNode) As Integer Select Case node.Kind Case SyntaxKind.FieldDeclaration Return GetDeclarationCount(DirectCast(node, FieldDeclarationSyntax).Declarators) Case SyntaxKind.LocalDeclarationStatement Return GetDeclarationCount(DirectCast(node, LocalDeclarationStatementSyntax).Declarators) Case SyntaxKind.VariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Names.Count Case SyntaxKind.AttributesStatement Return GetDeclarationCount(DirectCast(node, AttributesStatementSyntax).AttributeLists) Case SyntaxKind.AttributeList Return DirectCast(node, AttributeListSyntax).Attributes.Count Case SyntaxKind.ImportsStatement Return DirectCast(node, ImportsStatementSyntax).ImportsClauses.Count End Select Return 1 End Function Public Function SupportsNotPattern(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsNotPattern Return False End Function Public Function IsIsPatternExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsPatternExpression Return False End Function Public Function IsAnyPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnyPattern Return False End Function Public Function IsAndPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAndPattern Return False End Function Public Function IsBinaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryPattern Return False End Function Public Function IsConstantPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConstantPattern Return False End Function Public Function IsDeclarationPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationPattern Return False End Function Public Function IsNotPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNotPattern Return False End Function Public Function IsOrPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOrPattern Return False End Function Public Function IsParenthesizedPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParenthesizedPattern Return False End Function Public Function IsRecursivePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRecursivePattern Return False End Function Public Function IsUnaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnaryPattern Return False End Function Public Function IsTypePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypePattern Return False End Function Public Function IsVarPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVarPattern Return False End Function Public Sub GetPartsOfIsPatternExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef isToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfIsPatternExpression Throw ExceptionUtilities.Unreachable End Sub Public Function GetExpressionOfConstantPattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfConstantPattern Throw ExceptionUtilities.Unreachable End Function Public Sub GetPartsOfParenthesizedPattern(node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef pattern As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfBinaryPattern(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfUnaryPattern(node As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef pattern As SyntaxNode) Implements ISyntaxFacts.GetPartsOfUnaryPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfDeclarationPattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfDeclarationPattern Throw New NotImplementedException() End Sub Public Sub GetPartsOfRecursivePattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef positionalPart As SyntaxNode, ByRef propertyPart As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfRecursivePattern Throw New NotImplementedException() End Sub Public Function GetTypeOfTypePattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfTypePattern Throw New NotImplementedException() End Function Public Sub GetPartsOfInterpolationExpression(node As SyntaxNode, ByRef stringStartToken As SyntaxToken, ByRef contents As SyntaxList(Of SyntaxNode), ByRef stringEndToken As SyntaxToken) Implements ISyntaxFacts.GetPartsOfInterpolationExpression Dim interpolatedStringExpressionSyntax As InterpolatedStringExpressionSyntax = DirectCast(node, InterpolatedStringExpressionSyntax) stringStartToken = interpolatedStringExpressionSyntax.DollarSignDoubleQuoteToken contents = interpolatedStringExpressionSyntax.Contents stringEndToken = interpolatedStringExpressionSyntax.DoubleQuoteToken End Sub Public Function IsVerbatimInterpolatedStringExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVerbatimInterpolatedStringExpression Return False End Function #Region "IsXXX members" Public Function IsAnonymousFunctionExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnonymousFunctionExpression Return TypeOf node Is LambdaExpressionSyntax End Function Public Function IsBaseNamespaceDeclaration(<NotNullWhen(True)> node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBaseNamespaceDeclaration Return TypeOf node Is NamespaceBlockSyntax End Function Public Function IsBinaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryExpression Return TypeOf node Is BinaryExpressionSyntax End Function Public Function IsLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLiteralExpression Return TypeOf node Is LiteralExpressionSyntax End Function Public Function IsMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberAccessExpression Return TypeOf node Is MemberAccessExpressionSyntax End Function Public Function IsSimpleName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleName Return TypeOf node Is SimpleNameSyntax End Function #End Region #Region "GetPartsOfXXX members" Public Sub GetPartsOfBinaryExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryExpression Dim binaryExpression = DirectCast(node, BinaryExpressionSyntax) left = binaryExpression.Left operatorToken = binaryExpression.OperatorToken right = binaryExpression.Right End Sub Public Sub GetPartsOfCompilationUnit(node As SyntaxNode, ByRef [imports] As SyntaxList(Of SyntaxNode), ByRef attributeLists As SyntaxList(Of SyntaxNode), ByRef members As SyntaxList(Of SyntaxNode)) Implements ISyntaxFacts.GetPartsOfCompilationUnit Dim compilationUnit = DirectCast(node, CompilationUnitSyntax) [imports] = compilationUnit.Imports attributeLists = compilationUnit.Attributes members = compilationUnit.Members End Sub Public Sub GetPartsOfConditionalAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef whenNotNull As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalAccessExpression Dim conditionalAccess = DirectCast(node, ConditionalAccessExpressionSyntax) expression = conditionalAccess.Expression operatorToken = conditionalAccess.QuestionMarkToken whenNotNull = conditionalAccess.WhenNotNull End Sub Public Sub GetPartsOfConditionalExpression(node As SyntaxNode, ByRef condition As SyntaxNode, ByRef whenTrue As SyntaxNode, ByRef whenFalse As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalExpression Dim conditionalExpression = DirectCast(node, TernaryConditionalExpressionSyntax) condition = conditionalExpression.Condition whenTrue = conditionalExpression.WhenTrue whenFalse = conditionalExpression.WhenFalse End Sub Public Sub GetPartsOfInvocationExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfInvocationExpression Dim invocation = DirectCast(node, InvocationExpressionSyntax) expression = invocation.Expression argumentList = invocation.ArgumentList End Sub Public Sub GetPartsOfMemberAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef name As SyntaxNode) Implements ISyntaxFacts.GetPartsOfMemberAccessExpression Dim memberAccess = DirectCast(node, MemberAccessExpressionSyntax) expression = memberAccess.Expression operatorToken = memberAccess.OperatorToken name = memberAccess.Name End Sub Public Sub GetPartsOfBaseNamespaceDeclaration(node As SyntaxNode, ByRef name As SyntaxNode, ByRef [imports] As SyntaxList(Of SyntaxNode), ByRef members As SyntaxList(Of SyntaxNode)) Implements ISyntaxFacts.GetPartsOfBaseNamespaceDeclaration Dim namespaceBlock = DirectCast(node, NamespaceBlockSyntax) name = namespaceBlock.NamespaceStatement.Name [imports] = Nothing members = namespaceBlock.Members End Sub Public Sub GetPartsOfObjectCreationExpression(node As SyntaxNode, ByRef type As SyntaxNode, ByRef argumentList As SyntaxNode, ByRef initializer As SyntaxNode) Implements ISyntaxFacts.GetPartsOfObjectCreationExpression Dim objectCreationExpression = DirectCast(node, ObjectCreationExpressionSyntax) type = objectCreationExpression.Type argumentList = objectCreationExpression.ArgumentList initializer = objectCreationExpression.Initializer End Sub Public Sub GetPartsOfParenthesizedExpression(node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef expression As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedExpression Dim parenthesizedExpression = DirectCast(node, ParenthesizedExpressionSyntax) openParen = parenthesizedExpression.OpenParenToken expression = parenthesizedExpression.Expression closeParen = parenthesizedExpression.CloseParenToken End Sub Public Sub GetPartsOfPrefixUnaryExpression(node As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef operand As SyntaxNode) Implements ISyntaxFacts.GetPartsOfPrefixUnaryExpression Dim unaryExpression = DirectCast(node, UnaryExpressionSyntax) operatorToken = unaryExpression.OperatorToken operand = unaryExpression.Operand End Sub Public Sub GetPartsOfQualifiedName(node As SyntaxNode, ByRef left As SyntaxNode, ByRef dotToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfQualifiedName Dim qualifiedName = DirectCast(node, QualifiedNameSyntax) left = qualifiedName.Left dotToken = qualifiedName.DotToken right = qualifiedName.Right End Sub #End Region #Region "GetXXXOfYYY members" Public Function GetExpressionOfAwaitExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfAwaitExpression Return DirectCast(node, AwaitExpressionSyntax).Expression End Function Public Function GetExpressionOfThrowExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfThrowExpression ' ThrowExpression doesn't exist in VB Throw New NotImplementedException() End Function #End Region End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts Imports System.Diagnostics.CodeAnalysis #If CODE_STYLE Then Imports Microsoft.CodeAnalysis.Internal.Editing #Else Imports Microsoft.CodeAnalysis.Editing #End If Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageServices Friend Class VisualBasicSyntaxFacts Implements ISyntaxFacts Public Shared ReadOnly Property Instance As New VisualBasicSyntaxFacts Protected Sub New() End Sub Public ReadOnly Property IsCaseSensitive As Boolean Implements ISyntaxFacts.IsCaseSensitive Get Return False End Get End Property Public ReadOnly Property StringComparer As StringComparer Implements ISyntaxFacts.StringComparer Get Return CaseInsensitiveComparison.Comparer End Get End Property Public ReadOnly Property ElasticMarker As SyntaxTrivia Implements ISyntaxFacts.ElasticMarker Get Return SyntaxFactory.ElasticMarker End Get End Property Public ReadOnly Property ElasticCarriageReturnLineFeed As SyntaxTrivia Implements ISyntaxFacts.ElasticCarriageReturnLineFeed Get Return SyntaxFactory.ElasticCarriageReturnLineFeed End Get End Property Public ReadOnly Property SyntaxKinds As ISyntaxKinds = VisualBasicSyntaxKinds.Instance Implements ISyntaxFacts.SyntaxKinds Public Function SupportsIndexingInitializer(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsIndexingInitializer Return False End Function Public Function SupportsThrowExpression(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsThrowExpression Return False End Function Public Function SupportsLocalFunctionDeclaration(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsLocalFunctionDeclaration Return False End Function Public Function SupportsRecord(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecord Return False End Function Public Function SupportsRecordStruct(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecordStruct Return False End Function Public Function ParseToken(text As String) As SyntaxToken Implements ISyntaxFacts.ParseToken Return SyntaxFactory.ParseToken(text, startStatement:=True) End Function Public Function ParseLeadingTrivia(text As String) As SyntaxTriviaList Implements ISyntaxFacts.ParseLeadingTrivia Return SyntaxFactory.ParseLeadingTrivia(text) End Function Public Function EscapeIdentifier(identifier As String) As String Implements ISyntaxFacts.EscapeIdentifier Dim keywordKind = SyntaxFacts.GetKeywordKind(identifier) Dim needsEscaping = keywordKind <> SyntaxKind.None Return If(needsEscaping, "[" & identifier & "]", identifier) End Function Public Function IsVerbatimIdentifier(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier Return False End Function Public Function IsOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsOperator Return (IsUnaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is UnaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) OrElse (IsBinaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is BinaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) End Function Public Function IsContextualKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsContextualKeyword Return token.IsContextualKeyword() End Function Public Function IsReservedKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsReservedKeyword Return token.IsReservedKeyword() End Function Public Function IsPreprocessorKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPreprocessorKeyword Return token.IsPreprocessorKeyword() End Function Public Function IsPreProcessorDirectiveContext(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsPreProcessorDirectiveContext Return syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken) End Function Public Function TryGetCorrespondingOpenBrace(token As SyntaxToken, ByRef openBrace As SyntaxToken) As Boolean Implements ISyntaxFacts.TryGetCorrespondingOpenBrace If token.Kind = SyntaxKind.CloseBraceToken Then Dim tuples = token.Parent.GetBraces() openBrace = tuples.openBrace Return openBrace.Kind = SyntaxKind.OpenBraceToken End If Return False End Function Public Function IsEntirelyWithinStringOrCharOrNumericLiteral(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsEntirelyWithinStringOrCharOrNumericLiteral If syntaxTree Is Nothing Then Return False End If Return syntaxTree.IsEntirelyWithinStringOrCharOrNumericLiteral(position, cancellationToken) End Function Public Function IsDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDirective Return TypeOf node Is DirectiveTriviaSyntax End Function Public Function TryGetExternalSourceInfo(node As SyntaxNode, ByRef info As ExternalSourceInfo) As Boolean Implements ISyntaxFacts.TryGetExternalSourceInfo Select Case node.Kind Case SyntaxKind.ExternalSourceDirectiveTrivia info = New ExternalSourceInfo(CInt(DirectCast(node, ExternalSourceDirectiveTriviaSyntax).LineStart.Value), False) Return True Case SyntaxKind.EndExternalSourceDirectiveTrivia info = New ExternalSourceInfo(Nothing, True) Return True End Select Return False End Function Public Function IsDeclarationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationExpression ' VB doesn't support declaration expressions Return False End Function Public Function IsAttributeName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeName Return node.IsParentKind(SyntaxKind.Attribute) AndAlso DirectCast(node.Parent, AttributeSyntax).Name Is node End Function Public Function IsNameOfSimpleMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSimpleMemberAccessExpression Dim vbNode = TryCast(node, ExpressionSyntax) Return vbNode IsNot Nothing AndAlso vbNode.IsSimpleMemberAccessExpressionName() End Function Public Function IsNameOfAnyMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfAnyMemberAccessExpression Dim memberAccess = TryCast(node?.Parent, MemberAccessExpressionSyntax) Return memberAccess IsNot Nothing AndAlso memberAccess.Name Is node End Function Public Function GetStandaloneExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetStandaloneExpression Return SyntaxFactory.GetStandaloneExpression(TryCast(node, ExpressionSyntax)) End Function Public Function GetRootConditionalAccessExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRootConditionalAccessExpression Return TryCast(node, ExpressionSyntax).GetRootConditionalAccessExpression() End Function Public Function IsNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamedArgument Dim arg = TryCast(node, SimpleArgumentSyntax) Return arg?.NameColonEquals IsNot Nothing End Function Public Function IsNameOfNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfNamedArgument Return node.CheckParent(Of SimpleArgumentSyntax)(Function(p) p.IsNamed AndAlso p.NameColonEquals.Name Is node) End Function Public Function GetNameOfParameter(node As SyntaxNode) As SyntaxToken? Implements ISyntaxFacts.GetNameOfParameter Return DirectCast(node, ParameterSyntax).Identifier?.Identifier End Function Public Function GetDefaultOfParameter(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetDefaultOfParameter Return DirectCast(node, ParameterSyntax).Default End Function Public Function GetParameterList(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetParameterList Return node.GetParameterList() End Function Public Function IsParameterList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterList Return node.IsKind(SyntaxKind.ParameterList) End Function Public Function GetIdentifierOfGenericName(genericName As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfGenericName Return DirectCast(genericName, GenericNameSyntax).Identifier End Function Public Function IsUsingDirectiveName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingDirectiveName Return node.IsParentKind(SyntaxKind.SimpleImportsClause) AndAlso DirectCast(node.Parent, SimpleImportsClauseSyntax).Name Is node End Function Public Function IsDeconstructionAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionAssignment Return False End Function Public Function IsDeconstructionForEachStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionForEachStatement Return False End Function Public Function IsStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatement Return TypeOf node Is StatementSyntax End Function Public Function IsExecutableStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableStatement Return TypeOf node Is ExecutableStatementSyntax End Function Public Function IsMethodBody(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodBody Return TypeOf node Is MethodBlockBaseSyntax End Function Public Function GetExpressionOfReturnStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfReturnStatement Return DirectCast(node, ReturnStatementSyntax).Expression End Function Public Function IsThisConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsThisConstructorInitializer If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax) Return memberAccess.IsThisConstructorInitializer() End If Return False End Function Public Function IsBaseConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsBaseConstructorInitializer If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax) Return memberAccess.IsBaseConstructorInitializer() End If Return False End Function Public Function IsQueryKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsQueryKeyword Select Case token.Kind() Case _ SyntaxKind.JoinKeyword, SyntaxKind.IntoKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword, SyntaxKind.ByKeyword, SyntaxKind.OrderKeyword, SyntaxKind.WhereKeyword, SyntaxKind.OnKeyword, SyntaxKind.FromKeyword, SyntaxKind.WhileKeyword, SyntaxKind.SelectKeyword Return TypeOf token.Parent Is QueryClauseSyntax Case SyntaxKind.GroupKeyword Return (TypeOf token.Parent Is QueryClauseSyntax) OrElse (token.Parent.IsKind(SyntaxKind.GroupAggregation)) Case SyntaxKind.EqualsKeyword Return TypeOf token.Parent Is JoinConditionSyntax Case SyntaxKind.AscendingKeyword, SyntaxKind.DescendingKeyword Return TypeOf token.Parent Is OrderingSyntax Case SyntaxKind.InKeyword Return TypeOf token.Parent Is CollectionRangeVariableSyntax Case Else Return False End Select End Function Public Function IsPredefinedType(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedType Dim actualType As PredefinedType = PredefinedType.None Return TryGetPredefinedType(token, actualType) AndAlso actualType <> PredefinedType.None End Function Public Function IsPredefinedType(token As SyntaxToken, type As PredefinedType) As Boolean Implements ISyntaxFacts.IsPredefinedType Dim actualType As PredefinedType = PredefinedType.None Return TryGetPredefinedType(token, actualType) AndAlso actualType = type End Function Public Function TryGetPredefinedType(token As SyntaxToken, ByRef type As PredefinedType) As Boolean Implements ISyntaxFacts.TryGetPredefinedType type = GetPredefinedType(token) Return type <> PredefinedType.None End Function Private Shared Function GetPredefinedType(token As SyntaxToken) As PredefinedType Select Case token.Kind Case SyntaxKind.BooleanKeyword Return PredefinedType.Boolean Case SyntaxKind.ByteKeyword Return PredefinedType.Byte Case SyntaxKind.SByteKeyword Return PredefinedType.SByte Case SyntaxKind.IntegerKeyword Return PredefinedType.Int32 Case SyntaxKind.UIntegerKeyword Return PredefinedType.UInt32 Case SyntaxKind.ShortKeyword Return PredefinedType.Int16 Case SyntaxKind.UShortKeyword Return PredefinedType.UInt16 Case SyntaxKind.LongKeyword Return PredefinedType.Int64 Case SyntaxKind.ULongKeyword Return PredefinedType.UInt64 Case SyntaxKind.SingleKeyword Return PredefinedType.Single Case SyntaxKind.DoubleKeyword Return PredefinedType.Double Case SyntaxKind.DecimalKeyword Return PredefinedType.Decimal Case SyntaxKind.StringKeyword Return PredefinedType.String Case SyntaxKind.CharKeyword Return PredefinedType.Char Case SyntaxKind.ObjectKeyword Return PredefinedType.Object Case SyntaxKind.DateKeyword Return PredefinedType.DateTime Case Else Return PredefinedType.None End Select End Function Public Function IsPredefinedOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedOperator Dim actualOp As PredefinedOperator = PredefinedOperator.None Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp <> PredefinedOperator.None End Function Public Function IsPredefinedOperator(token As SyntaxToken, op As PredefinedOperator) As Boolean Implements ISyntaxFacts.IsPredefinedOperator Dim actualOp As PredefinedOperator = PredefinedOperator.None Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp = op End Function Public Function TryGetPredefinedOperator(token As SyntaxToken, ByRef op As PredefinedOperator) As Boolean Implements ISyntaxFacts.TryGetPredefinedOperator op = GetPredefinedOperator(token) Return op <> PredefinedOperator.None End Function Private Shared Function GetPredefinedOperator(token As SyntaxToken) As PredefinedOperator Select Case token.Kind Case SyntaxKind.PlusToken, SyntaxKind.PlusEqualsToken Return PredefinedOperator.Addition Case SyntaxKind.MinusToken, SyntaxKind.MinusEqualsToken Return PredefinedOperator.Subtraction Case SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword Return PredefinedOperator.BitwiseAnd Case SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword Return PredefinedOperator.BitwiseOr Case SyntaxKind.AmpersandToken, SyntaxKind.AmpersandEqualsToken Return PredefinedOperator.Concatenate Case SyntaxKind.SlashToken, SyntaxKind.SlashEqualsToken Return PredefinedOperator.Division Case SyntaxKind.EqualsToken Return PredefinedOperator.Equality Case SyntaxKind.XorKeyword Return PredefinedOperator.ExclusiveOr Case SyntaxKind.CaretToken, SyntaxKind.CaretEqualsToken Return PredefinedOperator.Exponent Case SyntaxKind.GreaterThanToken Return PredefinedOperator.GreaterThan Case SyntaxKind.GreaterThanEqualsToken Return PredefinedOperator.GreaterThanOrEqual Case SyntaxKind.LessThanGreaterThanToken Return PredefinedOperator.Inequality Case SyntaxKind.BackslashToken, SyntaxKind.BackslashEqualsToken Return PredefinedOperator.IntegerDivision Case SyntaxKind.LessThanLessThanToken, SyntaxKind.LessThanLessThanEqualsToken Return PredefinedOperator.LeftShift Case SyntaxKind.LessThanToken Return PredefinedOperator.LessThan Case SyntaxKind.LessThanEqualsToken Return PredefinedOperator.LessThanOrEqual Case SyntaxKind.LikeKeyword Return PredefinedOperator.Like Case SyntaxKind.NotKeyword Return PredefinedOperator.Complement Case SyntaxKind.ModKeyword Return PredefinedOperator.Modulus Case SyntaxKind.AsteriskToken, SyntaxKind.AsteriskEqualsToken Return PredefinedOperator.Multiplication Case SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.GreaterThanGreaterThanEqualsToken Return PredefinedOperator.RightShift Case Else Return PredefinedOperator.None End Select End Function Public Function GetText(kind As Integer) As String Implements ISyntaxFacts.GetText Return SyntaxFacts.GetText(CType(kind, SyntaxKind)) End Function Public Function IsIdentifierPartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierPartCharacter Return SyntaxFacts.IsIdentifierPartCharacter(c) End Function Public Function IsIdentifierStartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierStartCharacter Return SyntaxFacts.IsIdentifierStartCharacter(c) End Function Public Function IsIdentifierEscapeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierEscapeCharacter Return c = "["c OrElse c = "]"c End Function Public Function IsValidIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsValidIdentifier Dim token = SyntaxFactory.ParseToken(identifier) ' TODO: There is no way to get the diagnostics to see if any are actually errors? Return IsIdentifier(token) AndAlso Not token.ContainsDiagnostics AndAlso token.ToString().Length = identifier.Length End Function Public Function IsVerbatimIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier Return IsValidIdentifier(identifier) AndAlso MakeHalfWidthIdentifier(identifier.First()) = "[" AndAlso MakeHalfWidthIdentifier(identifier.Last()) = "]" End Function Public Function IsTypeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsTypeCharacter Return c = "%"c OrElse c = "&"c OrElse c = "@"c OrElse c = "!"c OrElse c = "#"c OrElse c = "$"c End Function Public Function IsStartOfUnicodeEscapeSequence(c As Char) As Boolean Implements ISyntaxFacts.IsStartOfUnicodeEscapeSequence Return False ' VB does not support identifiers with escaped unicode characters End Function Public Function IsLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsLiteral Select Case token.Kind() Case _ SyntaxKind.IntegerLiteralToken, SyntaxKind.CharacterLiteralToken, SyntaxKind.DecimalLiteralToken, SyntaxKind.FloatingLiteralToken, SyntaxKind.DateLiteralToken, SyntaxKind.StringLiteralToken, SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.DoubleQuoteToken, SyntaxKind.InterpolatedStringTextToken, SyntaxKind.TrueKeyword, SyntaxKind.FalseKeyword, SyntaxKind.NothingKeyword Return True End Select Return False End Function Public Function IsStringLiteralOrInterpolatedStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsStringLiteralOrInterpolatedStringLiteral Return token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken) End Function Public Function IsBindableToken(token As Microsoft.CodeAnalysis.SyntaxToken) As Boolean Implements ISyntaxFacts.IsBindableToken Return Me.IsWord(token) OrElse Me.IsLiteral(token) OrElse Me.IsOperator(token) End Function Public Function IsPointerMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPointerMemberAccessExpression Return False End Function Public Sub GetNameAndArityOfSimpleName(node As SyntaxNode, ByRef name As String, ByRef arity As Integer) Implements ISyntaxFacts.GetNameAndArityOfSimpleName Dim simpleName = DirectCast(node, SimpleNameSyntax) name = simpleName.Identifier.ValueText arity = simpleName.Arity End Sub Public Function LooksGeneric(name As SyntaxNode) As Boolean Implements ISyntaxFacts.LooksGeneric Return name.IsKind(SyntaxKind.GenericName) End Function Public Function GetExpressionOfMemberAccessExpression(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfMemberAccessExpression Return TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget) End Function Public Function GetTargetOfMemberBinding(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTargetOfMemberBinding ' Member bindings are a C# concept. Return Nothing End Function Public Function GetNameOfMemberBindingExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberBindingExpression ' Member bindings are a C# concept. Return Nothing End Function Public Sub GetPartsOfElementAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfElementAccessExpression Dim invocation = TryCast(node, InvocationExpressionSyntax) If invocation IsNot Nothing Then expression = invocation?.Expression argumentList = invocation?.ArgumentList Return End If If node.Kind() = SyntaxKind.DictionaryAccessExpression Then GetPartsOfMemberAccessExpression(node, expression, argumentList) Return End If Throw ExceptionUtilities.UnexpectedValue(node.Kind()) End Sub Public Function GetExpressionOfInterpolation(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfInterpolation Return DirectCast(node, InterpolationSyntax).Expression End Function Public Function IsInNamespaceOrTypeContext(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInNamespaceOrTypeContext Return SyntaxFacts.IsInNamespaceOrTypeContext(node) End Function Public Function IsBaseTypeList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBaseTypeList Return TryCast(node, InheritsOrImplementsStatementSyntax) IsNot Nothing End Function Public Function IsInStaticContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInStaticContext Return node.IsInStaticContext() End Function Public Function GetExpressionOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetExpressionOfArgument Return DirectCast(node, ArgumentSyntax).GetArgumentExpression() End Function Public Function GetRefKindOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.RefKind Implements ISyntaxFacts.GetRefKindOfArgument ' TODO(cyrusn): Consider the method this argument is passed to, to determine this. Return RefKind.None End Function Public Function IsArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsArgument Return TypeOf node Is ArgumentSyntax End Function Public Function IsSimpleArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleArgument Dim argument = TryCast(node, ArgumentSyntax) Return argument IsNot Nothing AndAlso Not argument.IsNamed AndAlso Not argument.IsOmitted End Function Public Function IsInConstantContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstantContext Return node.IsInConstantContext() End Function Public Function IsInConstructor(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstructor Return node.GetAncestors(Of StatementSyntax).Any(Function(s) s.Kind = SyntaxKind.ConstructorBlock) End Function Public Function IsUnsafeContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnsafeContext Return False End Function Public Function GetNameOfAttribute(node As SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetNameOfAttribute Return DirectCast(node, AttributeSyntax).Name End Function Public Function IsAttributeNamedArgumentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeNamedArgumentIdentifier Dim identifierName = TryCast(node, IdentifierNameSyntax) Return identifierName.IsParentKind(SyntaxKind.NameColonEquals) AndAlso identifierName.Parent.IsParentKind(SyntaxKind.SimpleArgument) AndAlso identifierName.Parent.Parent.IsParentKind(SyntaxKind.ArgumentList) AndAlso identifierName.Parent.Parent.Parent.IsParentKind(SyntaxKind.Attribute) End Function Public Function GetContainingTypeDeclaration(root As SyntaxNode, position As Integer) As SyntaxNode Implements ISyntaxFacts.GetContainingTypeDeclaration If root Is Nothing Then Throw New ArgumentNullException(NameOf(root)) End If If position < 0 OrElse position > root.Span.End Then Throw New ArgumentOutOfRangeException(NameOf(position)) End If Return root. FindToken(position). GetAncestors(Of SyntaxNode)(). FirstOrDefault(Function(n) TypeOf n Is TypeBlockSyntax OrElse TypeOf n Is DelegateStatementSyntax) End Function Public Function GetContainingVariableDeclaratorOfFieldDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetContainingVariableDeclaratorOfFieldDeclaration If node Is Nothing Then Throw New ArgumentNullException(NameOf(node)) End If Dim parent = node.Parent While node IsNot Nothing If node.Kind = SyntaxKind.VariableDeclarator AndAlso node.IsParentKind(SyntaxKind.FieldDeclaration) Then Return node End If node = node.Parent End While Return Nothing End Function Public Function IsMemberInitializerNamedAssignmentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier Dim unused As SyntaxNode = Nothing Return IsMemberInitializerNamedAssignmentIdentifier(node, unused) End Function Public Function IsMemberInitializerNamedAssignmentIdentifier( node As SyntaxNode, ByRef initializedInstance As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier Dim identifier = TryCast(node, IdentifierNameSyntax) If identifier?.IsChildNode(Of NamedFieldInitializerSyntax)(Function(n) n.Name) Then ' .parent is the NamedField. ' .parent.parent is the ObjectInitializer. ' .parent.parent.parent will be the ObjectCreationExpression. initializedInstance = identifier.Parent.Parent.Parent Return True End If Return False End Function Public Function IsNameOfSubpattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSubpattern Return False End Function Public Function IsPropertyPatternClause(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPropertyPatternClause Return False End Function Public Function IsElementAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsElementAccessExpression ' VB doesn't have a specialized node for element access. Instead, it just uses an ' invocation expression or dictionary access expression. Return node.Kind = SyntaxKind.InvocationExpression OrElse node.Kind = SyntaxKind.DictionaryAccessExpression End Function Public Function IsIndexerMemberCRef(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIndexerMemberCRef Return False End Function Public Function GetContainingMemberDeclaration(root As SyntaxNode, position As Integer, Optional useFullSpan As Boolean = True) As SyntaxNode Implements ISyntaxFacts.GetContainingMemberDeclaration Contract.ThrowIfNull(root, NameOf(root)) Contract.ThrowIfTrue(position < 0 OrElse position > root.FullSpan.End, NameOf(position)) Dim [end] = root.FullSpan.End If [end] = 0 Then ' empty file Return Nothing End If ' make sure position doesn't touch end of root position = Math.Min(position, [end] - 1) Dim node = root.FindToken(position).Parent While node IsNot Nothing If useFullSpan OrElse node.Span.Contains(position) Then If TypeOf node Is MethodBlockBaseSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return node End If If TypeOf node Is MethodBaseSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return node End If If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return node End If If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then Return node End If If TypeOf node Is PropertyBlockSyntax OrElse TypeOf node Is TypeBlockSyntax OrElse TypeOf node Is EnumBlockSyntax OrElse TypeOf node Is NamespaceBlockSyntax OrElse TypeOf node Is EventBlockSyntax OrElse TypeOf node Is FieldDeclarationSyntax Then Return node End If End If node = node.Parent End While Return Nothing End Function Public Function IsMethodLevelMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodLevelMember ' Note: Derived types of MethodBaseSyntax are expanded explicitly, since PropertyStatementSyntax and ' EventStatementSyntax will NOT be parented by MethodBlockBaseSyntax. Additionally, there are things ' like AccessorStatementSyntax and DelegateStatementSyntax that we never want to tread as method level ' members. If TypeOf node Is MethodStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is SubNewStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is OperatorStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return True End If If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then Return True End If If TypeOf node Is DeclareStatementSyntax Then Return True End If Return TypeOf node Is ConstructorBlockSyntax OrElse TypeOf node Is MethodBlockSyntax OrElse TypeOf node Is OperatorBlockSyntax OrElse TypeOf node Is EventBlockSyntax OrElse TypeOf node Is PropertyBlockSyntax OrElse TypeOf node Is EnumMemberDeclarationSyntax OrElse TypeOf node Is FieldDeclarationSyntax End Function Public Function GetMemberBodySpanForSpeculativeBinding(node As SyntaxNode) As TextSpan Implements ISyntaxFacts.GetMemberBodySpanForSpeculativeBinding Dim member = GetContainingMemberDeclaration(node, node.SpanStart) If member Is Nothing Then Return Nothing End If ' TODO: currently we only support method for now Dim method = TryCast(member, MethodBlockBaseSyntax) If method IsNot Nothing Then If method.BlockStatement Is Nothing OrElse method.EndBlockStatement Is Nothing Then Return Nothing End If ' We don't want to include the BlockStatement or any trailing trivia up to and including its statement ' terminator in the span. Instead, we use the start of the first statement's leading trivia (if any) up ' to the start of the EndBlockStatement. If there aren't any statements in the block, we use the start ' of the EndBlockStatements leading trivia. Dim firstStatement = method.Statements.FirstOrDefault() Dim spanStart = If(firstStatement IsNot Nothing, firstStatement.FullSpan.Start, method.EndBlockStatement.FullSpan.Start) Return TextSpan.FromBounds(spanStart, method.EndBlockStatement.SpanStart) End If Return Nothing End Function Public Function ContainsInMemberBody(node As SyntaxNode, span As TextSpan) As Boolean Implements ISyntaxFacts.ContainsInMemberBody Dim method = TryCast(node, MethodBlockBaseSyntax) If method IsNot Nothing Then Return method.Statements.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan(method.Statements), span) End If Dim [event] = TryCast(node, EventBlockSyntax) If [event] IsNot Nothing Then Return [event].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([event].Accessors), span) End If Dim [property] = TryCast(node, PropertyBlockSyntax) If [property] IsNot Nothing Then Return [property].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([property].Accessors), span) End If Dim field = TryCast(node, FieldDeclarationSyntax) If field IsNot Nothing Then Return field.Declarators.Count > 0 AndAlso ContainsExclusively(GetSeparatedSyntaxListSpan(field.Declarators), span) End If Dim [enum] = TryCast(node, EnumMemberDeclarationSyntax) If [enum] IsNot Nothing Then Return [enum].Initializer IsNot Nothing AndAlso ContainsExclusively([enum].Initializer.Span, span) End If Dim propStatement = TryCast(node, PropertyStatementSyntax) If propStatement IsNot Nothing Then Return propStatement.Initializer IsNot Nothing AndAlso ContainsExclusively(propStatement.Initializer.Span, span) End If Return False End Function Private Shared Function ContainsExclusively(outerSpan As TextSpan, innerSpan As TextSpan) As Boolean If innerSpan.IsEmpty Then Return outerSpan.Contains(innerSpan.Start) End If Return outerSpan.Contains(innerSpan) End Function Private Shared Function GetSyntaxListSpan(Of T As SyntaxNode)(list As SyntaxList(Of T)) As TextSpan Debug.Assert(list.Count > 0) Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End) End Function Private Shared Function GetSeparatedSyntaxListSpan(Of T As SyntaxNode)(list As SeparatedSyntaxList(Of T)) As TextSpan Debug.Assert(list.Count > 0) Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End) End Function Public Function GetTopLevelAndMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetTopLevelAndMethodLevelMembers Dim list = New List(Of SyntaxNode)() AppendMembers(root, list, topLevel:=True, methodLevel:=True) Return list End Function Public Function GetMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetMethodLevelMembers Dim list = New List(Of SyntaxNode)() AppendMembers(root, list, topLevel:=False, methodLevel:=True) Return list End Function Public Function GetMembersOfTypeDeclaration(typeDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfTypeDeclaration Return DirectCast(typeDeclaration, TypeBlockSyntax).Members End Function Public Function IsTopLevelNodeWithMembers(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTopLevelNodeWithMembers Return TypeOf node Is NamespaceBlockSyntax OrElse TypeOf node Is TypeBlockSyntax OrElse TypeOf node Is EnumBlockSyntax End Function Private Const s_dotToken As String = "." Public Function GetDisplayName(node As SyntaxNode, options As DisplayNameOptions, Optional rootNamespace As String = Nothing) As String Implements ISyntaxFacts.GetDisplayName If node Is Nothing Then Return String.Empty End If Dim pooled = PooledStringBuilder.GetInstance() Dim builder = pooled.Builder ' member keyword (if any) Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax) If (options And DisplayNameOptions.IncludeMemberKeyword) <> 0 Then Dim keywordToken = memberDeclaration.GetMemberKeywordToken() If keywordToken <> Nothing AndAlso Not keywordToken.IsMissing Then builder.Append(keywordToken.Text) builder.Append(" "c) End If End If Dim names = ArrayBuilder(Of String).GetInstance() ' containing type(s) Dim parent = node.Parent While TypeOf parent Is TypeBlockSyntax names.Push(GetName(parent, options, containsGlobalKeyword:=False)) parent = parent.Parent End While If (options And DisplayNameOptions.IncludeNamespaces) <> 0 Then ' containing namespace(s) in source (if any) Dim containsGlobalKeyword As Boolean = False While parent IsNot Nothing AndAlso parent.Kind() = SyntaxKind.NamespaceBlock names.Push(GetName(parent, options, containsGlobalKeyword)) parent = parent.Parent End While ' root namespace (if any) If Not containsGlobalKeyword AndAlso Not String.IsNullOrEmpty(rootNamespace) Then builder.Append(rootNamespace) builder.Append(s_dotToken) End If End If While Not names.IsEmpty() Dim name = names.Pop() If name IsNot Nothing Then builder.Append(name) builder.Append(s_dotToken) End If End While names.Free() ' name (include generic type parameters) builder.Append(GetName(node, options, containsGlobalKeyword:=False)) ' parameter list (if any) If (options And DisplayNameOptions.IncludeParameters) <> 0 Then builder.Append(memberDeclaration.GetParameterList()) End If ' As clause (if any) If (options And DisplayNameOptions.IncludeType) <> 0 Then Dim asClause = memberDeclaration.GetAsClause() If asClause IsNot Nothing Then builder.Append(" "c) builder.Append(asClause) End If End If Return pooled.ToStringAndFree() End Function Private Shared Function GetName(node As SyntaxNode, options As DisplayNameOptions, ByRef containsGlobalKeyword As Boolean) As String Const missingTokenPlaceholder As String = "?" Select Case node.Kind() Case SyntaxKind.CompilationUnit Return Nothing Case SyntaxKind.IdentifierName Dim identifier = DirectCast(node, IdentifierNameSyntax).Identifier Return If(identifier.IsMissing, missingTokenPlaceholder, identifier.Text) Case SyntaxKind.IncompleteMember Return missingTokenPlaceholder Case SyntaxKind.NamespaceBlock Dim nameSyntax = CType(node, NamespaceBlockSyntax).NamespaceStatement.Name If nameSyntax.Kind() = SyntaxKind.GlobalName Then containsGlobalKeyword = True Return Nothing Else Return GetName(nameSyntax, options, containsGlobalKeyword) End If Case SyntaxKind.QualifiedName Dim qualified = CType(node, QualifiedNameSyntax) If qualified.Left.Kind() = SyntaxKind.GlobalName Then containsGlobalKeyword = True Return GetName(qualified.Right, options, containsGlobalKeyword) ' don't use the Global prefix if specified Else Return GetName(qualified.Left, options, containsGlobalKeyword) + s_dotToken + GetName(qualified.Right, options, containsGlobalKeyword) End If End Select Dim name As String = Nothing Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax) If memberDeclaration IsNot Nothing Then Dim nameToken = memberDeclaration.GetNameToken() If nameToken <> Nothing Then name = If(nameToken.IsMissing, missingTokenPlaceholder, nameToken.Text) If (options And DisplayNameOptions.IncludeTypeParameters) <> 0 Then Dim pooled = PooledStringBuilder.GetInstance() Dim builder = pooled.Builder builder.Append(name) AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList()) name = pooled.ToStringAndFree() End If End If End If Debug.Assert(name IsNot Nothing, "Unexpected node type " + node.Kind().ToString()) Return name End Function Private Shared Sub AppendTypeParameterList(builder As StringBuilder, typeParameterList As TypeParameterListSyntax) If typeParameterList IsNot Nothing AndAlso typeParameterList.Parameters.Count > 0 Then builder.Append("(Of ") builder.Append(typeParameterList.Parameters(0).Identifier.Text) For i = 1 To typeParameterList.Parameters.Count - 1 builder.Append(", ") builder.Append(typeParameterList.Parameters(i).Identifier.Text) Next builder.Append(")"c) End If End Sub Private Sub AppendMembers(node As SyntaxNode, list As List(Of SyntaxNode), topLevel As Boolean, methodLevel As Boolean) Debug.Assert(topLevel OrElse methodLevel) For Each member In node.GetMembers() If IsTopLevelNodeWithMembers(member) Then If topLevel Then list.Add(member) End If AppendMembers(member, list, topLevel, methodLevel) Continue For End If If methodLevel AndAlso IsMethodLevelMember(member) Then list.Add(member) End If Next End Sub Public Function TryGetBindableParent(token As SyntaxToken) As SyntaxNode Implements ISyntaxFacts.TryGetBindableParent Dim node = token.Parent While node IsNot Nothing Dim parent = node.Parent ' If this node is on the left side of a member access expression, don't ascend ' further or we'll end up binding to something else. Dim memberAccess = TryCast(parent, MemberAccessExpressionSyntax) If memberAccess IsNot Nothing Then If memberAccess.Expression Is node Then Exit While End If End If ' If this node is on the left side of a qualified name, don't ascend ' further or we'll end up binding to something else. Dim qualifiedName = TryCast(parent, QualifiedNameSyntax) If qualifiedName IsNot Nothing Then If qualifiedName.Left Is node Then Exit While End If End If ' If this node is the type of an object creation expression, return the ' object creation expression. Dim objectCreation = TryCast(parent, ObjectCreationExpressionSyntax) If objectCreation IsNot Nothing Then If objectCreation.Type Is node Then node = parent Exit While End If End If ' The inside of an interpolated string is treated as its own token so we ' need to force navigation to the parent expression syntax. If TypeOf node Is InterpolatedStringTextSyntax AndAlso TypeOf parent Is InterpolatedStringExpressionSyntax Then node = parent Exit While End If ' If this node is not parented by a name, we're done. Dim name = TryCast(parent, NameSyntax) If name Is Nothing Then Exit While End If node = parent End While Return node End Function Public Function GetConstructors(root As SyntaxNode, cancellationToken As CancellationToken) As IEnumerable(Of SyntaxNode) Implements ISyntaxFacts.GetConstructors Dim compilationUnit = TryCast(root, CompilationUnitSyntax) If compilationUnit Is Nothing Then Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If Dim constructors = New List(Of SyntaxNode)() AppendConstructors(compilationUnit.Members, constructors, cancellationToken) Return constructors End Function Private Sub AppendConstructors(members As SyntaxList(Of StatementSyntax), constructors As List(Of SyntaxNode), cancellationToken As CancellationToken) For Each member As StatementSyntax In members cancellationToken.ThrowIfCancellationRequested() Dim constructor = TryCast(member, ConstructorBlockSyntax) If constructor IsNot Nothing Then constructors.Add(constructor) Continue For End If Dim [namespace] = TryCast(member, NamespaceBlockSyntax) If [namespace] IsNot Nothing Then AppendConstructors([namespace].Members, constructors, cancellationToken) End If Dim [class] = TryCast(member, ClassBlockSyntax) If [class] IsNot Nothing Then AppendConstructors([class].Members, constructors, cancellationToken) End If Dim [struct] = TryCast(member, StructureBlockSyntax) If [struct] IsNot Nothing Then AppendConstructors([struct].Members, constructors, cancellationToken) End If Next End Sub Public Function GetInactiveRegionSpanAroundPosition(tree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As TextSpan Implements ISyntaxFacts.GetInactiveRegionSpanAroundPosition Dim trivia = tree.FindTriviaToLeft(position, cancellationToken) If trivia.Kind = SyntaxKind.DisabledTextTrivia Then Return trivia.FullSpan End If Return Nothing End Function Public Function GetNameForArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForArgument If TryCast(argument, ArgumentSyntax)?.IsNamed Then Return DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.Identifier.ValueText End If Return String.Empty End Function Public Function GetNameForAttributeArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForAttributeArgument ' All argument types are ArgumentSyntax in VB. Return GetNameForArgument(argument) End Function Public Function IsLeftSideOfDot(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfDot Return TryCast(node, ExpressionSyntax).IsLeftSideOfDot() End Function Public Function GetRightSideOfDot(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightSideOfDot Return If(TryCast(node, QualifiedNameSyntax)?.Right, TryCast(node, MemberAccessExpressionSyntax)?.Name) End Function Public Function GetLeftSideOfDot(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetLeftSideOfDot Return If(TryCast(node, QualifiedNameSyntax)?.Left, TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget)) End Function Public Function IsLeftSideOfExplicitInterfaceSpecifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfExplicitInterfaceSpecifier Return IsLeftSideOfDot(node) AndAlso TryCast(node.Parent.Parent, ImplementsClauseSyntax) IsNot Nothing End Function Public Function IsLeftSideOfAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfSimpleAssignmentStatement End Function Public Function IsLeftSideOfAnyAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAnyAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfAnyAssignmentStatement End Function Public Function IsLeftSideOfCompoundAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfCompoundAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfCompoundAssignmentStatement End Function Public Function GetRightHandSideOfAssignment(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightHandSideOfAssignment Return DirectCast(node, AssignmentStatementSyntax).Right End Function Public Function IsInferredAnonymousObjectMemberDeclarator(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInferredAnonymousObjectMemberDeclarator Return node.IsKind(SyntaxKind.InferredFieldInitializer) End Function Public Function IsOperandOfIncrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementExpression Return False End Function Public Function IsOperandOfIncrementOrDecrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementOrDecrementExpression Return False End Function Public Function GetContentsOfInterpolatedString(interpolatedString As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentsOfInterpolatedString Return (TryCast(interpolatedString, InterpolatedStringExpressionSyntax)?.Contents).Value End Function Public Function IsNumericLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsNumericLiteral Return token.Kind = SyntaxKind.DecimalLiteralToken OrElse token.Kind = SyntaxKind.FloatingLiteralToken OrElse token.Kind = SyntaxKind.IntegerLiteralToken End Function Public Function IsVerbatimStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimStringLiteral ' VB does not have verbatim strings Return False End Function Public Function GetArgumentsOfInvocationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfInvocationExpression Dim argumentList = DirectCast(node, InvocationExpressionSyntax).ArgumentList Return If(argumentList Is Nothing, Nothing, GetArgumentsOfArgumentList(argumentList)) End Function Public Function GetArgumentsOfObjectCreationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfObjectCreationExpression Dim argumentList = DirectCast(node, ObjectCreationExpressionSyntax).ArgumentList Return If(argumentList Is Nothing, Nothing, GetArgumentsOfArgumentList(argumentList)) End Function Public Function GetArgumentsOfArgumentList(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfArgumentList Return DirectCast(node, ArgumentListSyntax).Arguments End Function Public Function ConvertToSingleLine(node As SyntaxNode, Optional useElasticTrivia As Boolean = False) As SyntaxNode Implements ISyntaxFacts.ConvertToSingleLine Return node.ConvertToSingleLine(useElasticTrivia) End Function Public Function IsDocumentationComment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDocumentationComment Return node.IsKind(SyntaxKind.DocumentationCommentTrivia) End Function Public Function IsUsingOrExternOrImport(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingOrExternOrImport Return node.IsKind(SyntaxKind.ImportsStatement) End Function Public Function IsGlobalAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalAssemblyAttribute Return IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword) End Function Public Function IsGlobalModuleAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalModuleAttribute Return IsGlobalAttribute(node, SyntaxKind.ModuleKeyword) End Function Private Shared Function IsGlobalAttribute(node As SyntaxNode, attributeTarget As SyntaxKind) As Boolean If node.IsKind(SyntaxKind.Attribute) Then Dim attributeNode = CType(node, AttributeSyntax) If attributeNode.Target IsNot Nothing Then Return attributeNode.Target.AttributeModifier.IsKind(attributeTarget) End If End If Return False End Function Public Function IsDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaration ' From the Visual Basic language spec: ' NamespaceMemberDeclaration := ' NamespaceDeclaration | ' TypeDeclaration ' TypeDeclaration ::= ' ModuleDeclaration | ' NonModuleDeclaration ' NonModuleDeclaration ::= ' EnumDeclaration | ' StructureDeclaration | ' InterfaceDeclaration | ' ClassDeclaration | ' DelegateDeclaration ' ClassMemberDeclaration ::= ' NonModuleDeclaration | ' EventMemberDeclaration | ' VariableMemberDeclaration | ' ConstantMemberDeclaration | ' MethodMemberDeclaration | ' PropertyMemberDeclaration | ' ConstructorMemberDeclaration | ' OperatorDeclaration Select Case node.Kind() ' Because fields declarations can define multiple symbols "Public a, b As Integer" ' We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name. Case SyntaxKind.VariableDeclarator If (node.Parent.IsKind(SyntaxKind.FieldDeclaration)) Then Return True End If Return False Case SyntaxKind.NamespaceStatement, SyntaxKind.NamespaceBlock, SyntaxKind.ModuleStatement, SyntaxKind.ModuleBlock, SyntaxKind.EnumStatement, SyntaxKind.EnumBlock, SyntaxKind.StructureStatement, SyntaxKind.StructureBlock, SyntaxKind.InterfaceStatement, SyntaxKind.InterfaceBlock, SyntaxKind.ClassStatement, SyntaxKind.ClassBlock, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement, SyntaxKind.EventStatement, SyntaxKind.EventBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.FieldDeclaration, SyntaxKind.SubStatement, SyntaxKind.SubBlock, SyntaxKind.FunctionStatement, SyntaxKind.FunctionBlock, SyntaxKind.PropertyStatement, SyntaxKind.PropertyBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.SubNewStatement, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorStatement, SyntaxKind.OperatorBlock Return True End Select Return False End Function ' TypeDeclaration ::= ' ModuleDeclaration | ' NonModuleDeclaration ' NonModuleDeclaration ::= ' EnumDeclaration | ' StructureDeclaration | ' InterfaceDeclaration | ' ClassDeclaration | ' DelegateDeclaration Public Function IsTypeDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeDeclaration Select Case node.Kind() Case SyntaxKind.EnumBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ClassBlock, SyntaxKind.ModuleBlock, SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return True End Select Return False End Function Public Function IsSimpleAssignmentStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleAssignmentStatement Return node.IsKind(SyntaxKind.SimpleAssignmentStatement) End Function Public Sub GetPartsOfAssignmentStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentStatement ' VB only has assignment statements, so this can just delegate to that helper GetPartsOfAssignmentExpressionOrStatement(statement, left, operatorToken, right) End Sub Public Sub GetPartsOfAssignmentExpressionOrStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentExpressionOrStatement Dim assignment = DirectCast(statement, AssignmentStatementSyntax) left = assignment.Left operatorToken = assignment.OperatorToken right = assignment.Right End Sub Public Function GetIdentifierOfSimpleName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfSimpleName Return DirectCast(node, SimpleNameSyntax).Identifier End Function Public Function GetIdentifierOfVariableDeclarator(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfVariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Names.Last().Identifier End Function Public Function GetIdentifierOfParameter(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfParameter Return DirectCast(node, ParameterSyntax).Identifier.Identifier End Function Public Function GetIdentifierOfTypeDeclaration(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfTypeDeclaration Select Case node.Kind() Case SyntaxKind.EnumStatement, SyntaxKind.StructureStatement, SyntaxKind.InterfaceStatement, SyntaxKind.ClassStatement, SyntaxKind.ModuleStatement Return DirectCast(node, TypeStatementSyntax).Identifier Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return DirectCast(node, DelegateStatementSyntax).Identifier End Select Throw ExceptionUtilities.UnexpectedValue(node) End Function Public Function GetIdentifierOfIdentifierName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfIdentifierName Return DirectCast(node, IdentifierNameSyntax).Identifier End Function Public Function IsDeclaratorOfLocalDeclarationStatement(declarator As SyntaxNode, localDeclarationStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaratorOfLocalDeclarationStatement Return DirectCast(localDeclarationStatement, LocalDeclarationStatementSyntax).Declarators. Contains(DirectCast(declarator, VariableDeclaratorSyntax)) End Function Public Function AreEquivalent(token1 As SyntaxToken, token2 As SyntaxToken) As Boolean Implements ISyntaxFacts.AreEquivalent Return SyntaxFactory.AreEquivalent(token1, token2) End Function Public Function AreEquivalent(node1 As SyntaxNode, node2 As SyntaxNode) As Boolean Implements ISyntaxFacts.AreEquivalent Return SyntaxFactory.AreEquivalent(node1, node2) End Function Public Function IsExpressionOfForeach(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfForeach Return node IsNot Nothing AndAlso TryCast(node.Parent, ForEachStatementSyntax)?.Expression Is node End Function Public Function GetExpressionOfExpressionStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfExpressionStatement Return DirectCast(node, ExpressionStatementSyntax).Expression End Function Public Function IsIsExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsExpression Return node.IsKind(SyntaxKind.TypeOfIsExpression) End Function Public Function WalkDownParentheses(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.WalkDownParentheses Return If(TryCast(node, ExpressionSyntax)?.WalkDownParentheses(), node) End Function Public Sub GetPartsOfTupleExpression(Of TArgumentSyntax As SyntaxNode)(node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef arguments As SeparatedSyntaxList(Of TArgumentSyntax), ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfTupleExpression Dim tupleExpr = DirectCast(node, TupleExpressionSyntax) openParen = tupleExpr.OpenParenToken arguments = CType(CType(tupleExpr.Arguments, SeparatedSyntaxList(Of SyntaxNode)), SeparatedSyntaxList(Of TArgumentSyntax)) closeParen = tupleExpr.CloseParenToken End Sub Public Function IsPreprocessorDirective(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsPreprocessorDirective Return SyntaxFacts.IsPreprocessorDirective(trivia.Kind()) End Function Public Function IsRegularComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsRegularComment Return trivia.Kind = SyntaxKind.CommentTrivia End Function Public Function IsDocumentationComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationComment Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia End Function Public Function IsElastic(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsElastic Return trivia.IsElastic() End Function Public Function IsPragmaDirective(trivia As SyntaxTrivia, ByRef isDisable As Boolean, ByRef isActive As Boolean, ByRef errorCodes As SeparatedSyntaxList(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.IsPragmaDirective Return trivia.IsPragmaDirective(isDisable, isActive, errorCodes) End Function Public Function ContainsInterleavedDirective(span As TextSpan, token As SyntaxToken, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective Return token.ContainsInterleavedDirective(span, cancellationToken) End Function Public Function IsDocumentationCommentExteriorTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationCommentExteriorTrivia Return trivia.Kind() = SyntaxKind.DocumentationCommentExteriorTrivia End Function Public Function GetModifiers(node As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifiers Return node.GetModifiers() End Function Public Function WithModifiers(node As SyntaxNode, modifiers As SyntaxTokenList) As SyntaxNode Implements ISyntaxFacts.WithModifiers Return node.WithModifiers(modifiers) End Function Public Function GetVariablesOfLocalDeclarationStatement(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetVariablesOfLocalDeclarationStatement Return DirectCast(node, LocalDeclarationStatementSyntax).Declarators End Function Public Function GetInitializerOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetInitializerOfVariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Initializer End Function Public Function GetTypeOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfVariableDeclarator Dim declarator = DirectCast(node, VariableDeclaratorSyntax) Return TryCast(declarator.AsClause, SimpleAsClauseSyntax)?.Type End Function Public Function GetValueOfEqualsValueClause(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetValueOfEqualsValueClause Return DirectCast(node, EqualsValueSyntax).Value End Function Public Function IsScopeBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsScopeBlock ' VB has no equivalent of curly braces. Return False End Function Public Function IsExecutableBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableBlock Return node.IsExecutableBlock() End Function Public Function GetExecutableBlockStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetExecutableBlockStatements Return node.GetExecutableBlockStatements() End Function Public Function FindInnermostCommonExecutableBlock(nodes As IEnumerable(Of SyntaxNode)) As SyntaxNode Implements ISyntaxFacts.FindInnermostCommonExecutableBlock Return nodes.FindInnermostCommonExecutableBlock() End Function Public Function IsStatementContainer(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatementContainer Return IsExecutableBlock(node) End Function Public Function GetStatementContainerStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetStatementContainerStatements Return GetExecutableBlockStatements(node) End Function Public Function IsConversionExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConversionExpression Return node.Kind = SyntaxKind.CTypeExpression End Function Public Function IsCastExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsCastExpression Return node.Kind = SyntaxKind.DirectCastExpression End Function Public Sub GetPartsOfCastExpression(node As SyntaxNode, ByRef type As SyntaxNode, ByRef expression As SyntaxNode) Implements ISyntaxFacts.GetPartsOfCastExpression Dim cast = DirectCast(node, DirectCastExpressionSyntax) type = cast.Type expression = cast.Expression End Sub Public Function GetDeconstructionReferenceLocation(node As SyntaxNode) As Location Implements ISyntaxFacts.GetDeconstructionReferenceLocation Throw New NotImplementedException() End Function Public Function GetDeclarationIdentifierIfOverride(token As SyntaxToken) As SyntaxToken? Implements ISyntaxFacts.GetDeclarationIdentifierIfOverride If token.Kind() = SyntaxKind.OverridesKeyword Then Dim parent = token.Parent Select Case parent.Kind() Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Dim method = DirectCast(parent, MethodStatementSyntax) Return method.Identifier Case SyntaxKind.PropertyStatement Dim [property] = DirectCast(parent, PropertyStatementSyntax) Return [property].Identifier End Select End If Return Nothing End Function Public Function IsPostfixUnaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPostfixUnaryExpression ' Does not exist in VB. Return False End Function Public Function IsMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberBindingExpression ' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target. Return False End Function Public Function IsNameOfMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfMemberBindingExpression ' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target. Return False End Function Public Function GetAttributeLists(node As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetAttributeLists Return node.GetAttributeLists() End Function Public Function IsUsingAliasDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingAliasDirective Dim importStatement = TryCast(node, ImportsStatementSyntax) If (importStatement IsNot Nothing) Then For Each importsClause In importStatement.ImportsClauses If importsClause.Kind = SyntaxKind.SimpleImportsClause Then Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax) If simpleImportsClause.Alias IsNot Nothing Then Return True End If End If Next End If Return False End Function Public Sub GetPartsOfUsingAliasDirective( node As SyntaxNode, ByRef globalKeyword As SyntaxToken, ByRef [alias] As SyntaxToken, ByRef name As SyntaxNode) Implements ISyntaxFacts.GetPartsOfUsingAliasDirective Dim importStatement = DirectCast(node, ImportsStatementSyntax) For Each importsClause In importStatement.ImportsClauses If importsClause.Kind = SyntaxKind.SimpleImportsClause Then Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax) If simpleImportsClause.Alias IsNot Nothing Then globalKeyword = Nothing [alias] = simpleImportsClause.Alias.Identifier name = simpleImportsClause.Name Return End If End If Next Throw ExceptionUtilities.Unreachable End Sub Public Function IsParameterNameXmlElementSyntax(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterNameXmlElementSyntax Dim xmlElement = TryCast(node, XmlElementSyntax) If xmlElement IsNot Nothing Then Dim name = TryCast(xmlElement.StartTag.Name, XmlNameSyntax) Return name?.LocalName.ValueText = DocumentationCommentXmlNames.ParameterElementName End If Return False End Function Public Function GetContentFromDocumentationCommentTriviaSyntax(trivia As SyntaxTrivia) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentFromDocumentationCommentTriviaSyntax Dim documentationCommentTrivia = TryCast(trivia.GetStructure(), DocumentationCommentTriviaSyntax) If documentationCommentTrivia IsNot Nothing Then Return documentationCommentTrivia.Content End If Return Nothing End Function Friend Shared Function IsChildOf(node As SyntaxNode, kind As SyntaxKind) As Boolean Return node.Parent IsNot Nothing AndAlso node.Parent.IsKind(kind) End Function Friend Shared Function IsChildOfVariableDeclaration(node As SyntaxNode) As Boolean Return IsChildOf(node, SyntaxKind.FieldDeclaration) OrElse IsChildOf(node, SyntaxKind.LocalDeclarationStatement) End Function Private Shared Function GetDeclarationCount(nodes As IReadOnlyList(Of SyntaxNode)) As Integer Dim count As Integer = 0 For i = 0 To nodes.Count - 1 count = count + GetDeclarationCount(nodes(i)) Next Return count End Function Friend Shared Function GetDeclarationCount(node As SyntaxNode) As Integer Select Case node.Kind Case SyntaxKind.FieldDeclaration Return GetDeclarationCount(DirectCast(node, FieldDeclarationSyntax).Declarators) Case SyntaxKind.LocalDeclarationStatement Return GetDeclarationCount(DirectCast(node, LocalDeclarationStatementSyntax).Declarators) Case SyntaxKind.VariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Names.Count Case SyntaxKind.AttributesStatement Return GetDeclarationCount(DirectCast(node, AttributesStatementSyntax).AttributeLists) Case SyntaxKind.AttributeList Return DirectCast(node, AttributeListSyntax).Attributes.Count Case SyntaxKind.ImportsStatement Return DirectCast(node, ImportsStatementSyntax).ImportsClauses.Count End Select Return 1 End Function Public Function SupportsNotPattern(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsNotPattern Return False End Function Public Function IsIsPatternExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsPatternExpression Return False End Function Public Function IsAnyPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnyPattern Return False End Function Public Function IsAndPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAndPattern Return False End Function Public Function IsBinaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryPattern Return False End Function Public Function IsConstantPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConstantPattern Return False End Function Public Function IsDeclarationPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationPattern Return False End Function Public Function IsNotPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNotPattern Return False End Function Public Function IsOrPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOrPattern Return False End Function Public Function IsParenthesizedPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParenthesizedPattern Return False End Function Public Function IsRecursivePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRecursivePattern Return False End Function Public Function IsUnaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnaryPattern Return False End Function Public Function IsTypePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypePattern Return False End Function Public Function IsVarPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVarPattern Return False End Function Public Sub GetPartsOfIsPatternExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef isToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfIsPatternExpression Throw ExceptionUtilities.Unreachable End Sub Public Function GetExpressionOfConstantPattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfConstantPattern Throw ExceptionUtilities.Unreachable End Function Public Sub GetPartsOfParenthesizedPattern(node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef pattern As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfBinaryPattern(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfUnaryPattern(node As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef pattern As SyntaxNode) Implements ISyntaxFacts.GetPartsOfUnaryPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfDeclarationPattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfDeclarationPattern Throw New NotImplementedException() End Sub Public Sub GetPartsOfRecursivePattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef positionalPart As SyntaxNode, ByRef propertyPart As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfRecursivePattern Throw New NotImplementedException() End Sub Public Function GetTypeOfTypePattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfTypePattern Throw New NotImplementedException() End Function Public Sub GetPartsOfInterpolationExpression(node As SyntaxNode, ByRef stringStartToken As SyntaxToken, ByRef contents As SyntaxList(Of SyntaxNode), ByRef stringEndToken As SyntaxToken) Implements ISyntaxFacts.GetPartsOfInterpolationExpression Dim interpolatedStringExpressionSyntax As InterpolatedStringExpressionSyntax = DirectCast(node, InterpolatedStringExpressionSyntax) stringStartToken = interpolatedStringExpressionSyntax.DollarSignDoubleQuoteToken contents = interpolatedStringExpressionSyntax.Contents stringEndToken = interpolatedStringExpressionSyntax.DoubleQuoteToken End Sub Public Function IsVerbatimInterpolatedStringExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVerbatimInterpolatedStringExpression Return False End Function #Region "IsXXX members" Public Function IsAnonymousFunctionExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnonymousFunctionExpression Return TypeOf node Is LambdaExpressionSyntax End Function Public Function IsBaseNamespaceDeclaration(<NotNullWhen(True)> node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBaseNamespaceDeclaration Return TypeOf node Is NamespaceBlockSyntax End Function Public Function IsBinaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryExpression Return TypeOf node Is BinaryExpressionSyntax End Function Public Function IsLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLiteralExpression Return TypeOf node Is LiteralExpressionSyntax End Function Public Function IsMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberAccessExpression Return TypeOf node Is MemberAccessExpressionSyntax End Function Public Function IsSimpleName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleName Return TypeOf node Is SimpleNameSyntax End Function #End Region #Region "GetPartsOfXXX members" Public Sub GetPartsOfBinaryExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryExpression Dim binaryExpression = DirectCast(node, BinaryExpressionSyntax) left = binaryExpression.Left operatorToken = binaryExpression.OperatorToken right = binaryExpression.Right End Sub Public Sub GetPartsOfCompilationUnit(node As SyntaxNode, ByRef [imports] As SyntaxList(Of SyntaxNode), ByRef attributeLists As SyntaxList(Of SyntaxNode), ByRef members As SyntaxList(Of SyntaxNode)) Implements ISyntaxFacts.GetPartsOfCompilationUnit Dim compilationUnit = DirectCast(node, CompilationUnitSyntax) [imports] = compilationUnit.Imports attributeLists = compilationUnit.Attributes members = compilationUnit.Members End Sub Public Sub GetPartsOfConditionalAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef whenNotNull As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalAccessExpression Dim conditionalAccess = DirectCast(node, ConditionalAccessExpressionSyntax) expression = conditionalAccess.Expression operatorToken = conditionalAccess.QuestionMarkToken whenNotNull = conditionalAccess.WhenNotNull End Sub Public Sub GetPartsOfConditionalExpression(node As SyntaxNode, ByRef condition As SyntaxNode, ByRef whenTrue As SyntaxNode, ByRef whenFalse As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalExpression Dim conditionalExpression = DirectCast(node, TernaryConditionalExpressionSyntax) condition = conditionalExpression.Condition whenTrue = conditionalExpression.WhenTrue whenFalse = conditionalExpression.WhenFalse End Sub Public Sub GetPartsOfInvocationExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfInvocationExpression Dim invocation = DirectCast(node, InvocationExpressionSyntax) expression = invocation.Expression argumentList = invocation.ArgumentList End Sub Public Sub GetPartsOfMemberAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef name As SyntaxNode) Implements ISyntaxFacts.GetPartsOfMemberAccessExpression Dim memberAccess = DirectCast(node, MemberAccessExpressionSyntax) expression = memberAccess.Expression operatorToken = memberAccess.OperatorToken name = memberAccess.Name End Sub Public Sub GetPartsOfBaseNamespaceDeclaration(node As SyntaxNode, ByRef name As SyntaxNode, ByRef [imports] As SyntaxList(Of SyntaxNode), ByRef members As SyntaxList(Of SyntaxNode)) Implements ISyntaxFacts.GetPartsOfBaseNamespaceDeclaration Dim namespaceBlock = DirectCast(node, NamespaceBlockSyntax) name = namespaceBlock.NamespaceStatement.Name [imports] = Nothing members = namespaceBlock.Members End Sub Public Sub GetPartsOfObjectCreationExpression(node As SyntaxNode, ByRef type As SyntaxNode, ByRef argumentList As SyntaxNode, ByRef initializer As SyntaxNode) Implements ISyntaxFacts.GetPartsOfObjectCreationExpression Dim objectCreationExpression = DirectCast(node, ObjectCreationExpressionSyntax) type = objectCreationExpression.Type argumentList = objectCreationExpression.ArgumentList initializer = objectCreationExpression.Initializer End Sub Public Sub GetPartsOfParenthesizedExpression(node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef expression As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedExpression Dim parenthesizedExpression = DirectCast(node, ParenthesizedExpressionSyntax) openParen = parenthesizedExpression.OpenParenToken expression = parenthesizedExpression.Expression closeParen = parenthesizedExpression.CloseParenToken End Sub Public Sub GetPartsOfPrefixUnaryExpression(node As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef operand As SyntaxNode) Implements ISyntaxFacts.GetPartsOfPrefixUnaryExpression Dim unaryExpression = DirectCast(node, UnaryExpressionSyntax) operatorToken = unaryExpression.OperatorToken operand = unaryExpression.Operand End Sub Public Sub GetPartsOfQualifiedName(node As SyntaxNode, ByRef left As SyntaxNode, ByRef dotToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfQualifiedName Dim qualifiedName = DirectCast(node, QualifiedNameSyntax) left = qualifiedName.Left dotToken = qualifiedName.DotToken right = qualifiedName.Right End Sub #End Region #Region "GetXXXOfYYY members" Public Function GetExpressionOfAwaitExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfAwaitExpression Return DirectCast(node, AwaitExpressionSyntax).Expression End Function Public Function GetExpressionOfThrowExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfThrowExpression ' ThrowExpression doesn't exist in VB Throw New NotImplementedException() End Function #End Region End Class End Namespace
1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Workspaces/VisualBasic/Portable/CodeCleanup/VisualBasicCodeCleanerService.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeCleanup Imports Microsoft.CodeAnalysis.CodeCleanup.Providers Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Namespace Microsoft.CodeAnalysis.VisualBasic.CodeCleanup Partial Friend Class VisualBasicCodeCleanerService Inherits AbstractCodeCleanerService Private Shared ReadOnly s_defaultProviders As ImmutableArray(Of ICodeCleanupProvider) = ImmutableArray.Create(Of ICodeCleanupProvider)( New AddMissingTokensCodeCleanupProvider(), New FixIncorrectTokensCodeCleanupProvider(), New ReduceTokensCodeCleanupProvider(), New NormalizeModifiersOrOperatorsCodeCleanupProvider(), New RemoveUnnecessaryLineContinuationCodeCleanupProvider(), New CaseCorrectionCodeCleanupProvider(), New SimplificationCodeCleanupProvider(), New FormatCodeCleanupProvider()) Public Overrides Function GetDefaultProviders() As ImmutableArray(Of ICodeCleanupProvider) Return s_defaultProviders End Function Protected Overrides Function GetSpansToAvoid(root As SyntaxNode) As ImmutableArray(Of TextSpan) ' We don't want to touch nodes in the document that have syntax errors on them and which ' contain multi-line string literals. It's quite possible that there is some string ' literal on a previous line that was intended to be terminated on that line, but which ' wasn't. The string may then have terminated on this line (because of the start of ' another literal) causing the literal contents to then be considered code. We don't ' want to cleanup 'code' that the user intends to be the content of a string literal. Dim result = ArrayBuilder(Of TextSpan).GetInstance() ProcessNode(root, result) Return result.ToImmutableAndFree() End Function Private Sub ProcessNode(node As SyntaxNode, result As ArrayBuilder(Of TextSpan)) If SkipProcessing(node, result) Then Return End If For Each child In node.ChildNodesAndTokens() If child.IsNode Then ProcessNode(child.AsNode(), result) Else ProcessToken(child.AsToken(), result) End If Next End Sub Private Sub ProcessToken(token As SyntaxToken, result As ArrayBuilder(Of TextSpan)) If SkipProcessing(token, result) Then Return End If Dim parentMultiLineNode = GetMultiLineContainer(token.Parent) If parentMultiLineNode IsNot Nothing Then If ContainsMultiLineStringLiteral(parentMultiLineNode) Then result.Add(parentMultiLineNode.FullSpan) End If End If End Sub Private Shared Function SkipProcessing(nodeOrToken As SyntaxNodeOrToken, result As ArrayBuilder(Of TextSpan)) As Boolean ' Don't bother looking at nodes or token that don't have any syntax errors in them. If Not nodeOrToken.ContainsDiagnostics Then Return True End If If result.Count > 0 AndAlso result.Last.Contains(nodeOrToken.Span) Then ' Don't bother looking at nodes or token that are contained within a span we've already ' marked as something to avoid. We would only ever produce mark the same (or smaller) ' span again. Return True End If Return False End Function Private Shared Function ContainsMultiLineStringLiteral(node As SyntaxNode) As Boolean Return node.DescendantTokens().Any( Function(t) If t.Kind() = SyntaxKind.StringLiteralToken OrElse t.Kind() = SyntaxKind.InterpolatedStringTextToken Then Return Not VisualBasicSyntaxFacts.Instance.IsOnSingleLine(t.Parent, fullSpan:=False) End If Return False End Function) End Function Private Function GetMultiLineContainer(node As SyntaxNode) As SyntaxNode If node Is Nothing Then Return Nothing End If If Not VisualBasicSyntaxFacts.Instance.IsOnSingleLine(node, fullSpan:=False) Then Return node End If Return GetMultiLineContainer(node.Parent) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeCleanup Imports Microsoft.CodeAnalysis.CodeCleanup.Providers Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Namespace Microsoft.CodeAnalysis.VisualBasic.CodeCleanup Partial Friend Class VisualBasicCodeCleanerService Inherits AbstractCodeCleanerService Private Shared ReadOnly s_defaultProviders As ImmutableArray(Of ICodeCleanupProvider) = ImmutableArray.Create(Of ICodeCleanupProvider)( New AddMissingTokensCodeCleanupProvider(), New FixIncorrectTokensCodeCleanupProvider(), New ReduceTokensCodeCleanupProvider(), New NormalizeModifiersOrOperatorsCodeCleanupProvider(), New RemoveUnnecessaryLineContinuationCodeCleanupProvider(), New CaseCorrectionCodeCleanupProvider(), New SimplificationCodeCleanupProvider(), New FormatCodeCleanupProvider()) Public Overrides Function GetDefaultProviders() As ImmutableArray(Of ICodeCleanupProvider) Return s_defaultProviders End Function Protected Overrides Function GetSpansToAvoid(root As SyntaxNode) As ImmutableArray(Of TextSpan) ' We don't want to touch nodes in the document that have syntax errors on them and which ' contain multi-line string literals. It's quite possible that there is some string ' literal on a previous line that was intended to be terminated on that line, but which ' wasn't. The string may then have terminated on this line (because of the start of ' another literal) causing the literal contents to then be considered code. We don't ' want to cleanup 'code' that the user intends to be the content of a string literal. Dim result = ArrayBuilder(Of TextSpan).GetInstance() ProcessNode(root, result) Return result.ToImmutableAndFree() End Function Private Sub ProcessNode(node As SyntaxNode, result As ArrayBuilder(Of TextSpan)) If SkipProcessing(node, result) Then Return End If For Each child In node.ChildNodesAndTokens() If child.IsNode Then ProcessNode(child.AsNode(), result) Else ProcessToken(child.AsToken(), result) End If Next End Sub Private Sub ProcessToken(token As SyntaxToken, result As ArrayBuilder(Of TextSpan)) If SkipProcessing(token, result) Then Return End If Dim parentMultiLineNode = GetMultiLineContainer(token.Parent) If parentMultiLineNode IsNot Nothing Then If ContainsMultiLineStringLiteral(parentMultiLineNode) Then result.Add(parentMultiLineNode.FullSpan) End If End If End Sub Private Shared Function SkipProcessing(nodeOrToken As SyntaxNodeOrToken, result As ArrayBuilder(Of TextSpan)) As Boolean ' Don't bother looking at nodes or token that don't have any syntax errors in them. If Not nodeOrToken.ContainsDiagnostics Then Return True End If If result.Count > 0 AndAlso result.Last.Contains(nodeOrToken.Span) Then ' Don't bother looking at nodes or token that are contained within a span we've already ' marked as something to avoid. We would only ever produce mark the same (or smaller) ' span again. Return True End If Return False End Function Private Shared Function ContainsMultiLineStringLiteral(node As SyntaxNode) As Boolean Return node.DescendantTokens().Any( Function(t) If t.Kind() = SyntaxKind.StringLiteralToken OrElse t.Kind() = SyntaxKind.InterpolatedStringTextToken Then Return Not VisualBasicSyntaxFacts.Instance.IsOnSingleLine(t.Parent, fullSpan:=False) End If Return False End Function) End Function Private Function GetMultiLineContainer(node As SyntaxNode) As SyntaxNode If node Is Nothing Then Return Nothing End If If Not VisualBasicSyntaxFacts.Instance.IsOnSingleLine(node, fullSpan:=False) Then Return node End If Return GetMultiLineContainer(node.Parent) End Function End Class End Namespace
1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Compilers/CSharp/Test/Semantic/Semantics/NameCollisionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; // The way the specification describes, and the way the native compiler reports name // collision errors is inconsistent and confusing. In Roslyn we will implement // the following more rational behaviors: // // ------------------ // // These two error messages are to be reworded: // // CS0135: (ERR_NameIllegallyOverrides) // // Original: 'X' conflicts with the declaration 'C.X' // // New: A local, parameter or range variable named 'X' cannot be declared in this scope // because that name is used in an enclosing local scope to refer to 'C.X'. // // CS0136: (ERR_LocalIllegallyOverrides) // // Original: A local variable named 'X' cannot be declared in this scope // because it would give a different meaning to 'X', which is // already used in a 'parent or current' / 'child' // scope to denote something else // // New: A local or parameter named 'X' cannot be declared in this scope // because that name is used in an enclosing local scope to define // a local or parameter. // // Note now the error messages are now nicely parallel, and much more clear about // precisely which rule has been violated. // // The rules for what error to report in each name collision scenario are as follows: // // --------------------------- // // Errors for simple names being used to refer to a member in one place and a declared // entity in another: // // CS0135: (ERR_NameIllegallyOverrides) // A local, parameter or range variable cannot be named 'X' because // that name is used in an enclosing local scope to refer to 'C.X'. // // Reported *only* when there is a local variable, local constant, lambda parameter or range variable // that would change the meaning of a *simple name* in an *expression* in an enclosing declaration // space to refer to a member, namespace, type, type parameter etc. Report it on the *inner* usage, // never the "outer" usage. eg: // // class C { int x; void M() { int y = x; { int x = y; } } } // // --------------------------- // // Errors for a local being used before it is defined: // // CS0841: (ERR_VariableUsedBeforeDeclaration) // Cannot use local variable 'X' before it is declared // // Reported when a local variable is used before it is declared, and the offending // usage was probably not intended to refer to a field. eg: // // class C { void M() { int y = x; int x; } } // // CS0844: (ERR_VariableUsedBeforeDeclarationAndHidesField) // Cannot use local variable 'X' before it is declared. The // declaration of the local variable hides the field 'C.X'. // // Reported if the offending usage might have been intended to refer to a field, eg: // // class C { int x; void M() { int y = x; int x; } } // // --------------------------- // // Errors for two of the same identifier being used to declare two different // things in overlapping or identical declaration spaces: // // CS0100: (ERR_DuplicateParamName) // The parameter name 'x' is a duplicate // // Reported when one parameter list contains two identically-named parameters. Eg: // // void M(int x, int x) {} or (x, x)=>{} // // CS0128: (ERR_LocalDuplicate) // A local variable named 'x' is already defined in this scope // // Reported *only* when there are two local variables or constants defined in the // *exact* same declaration space with the same name. eg: // // void M() { int x; int x; } // // CS0136: (ERR_LocalIllegallyOverrides) // New: A local or parameter named 'X' cannot be declared in this scope // because that name is used in an enclosing local scope to define // a local or parameter. // // Reported *only* when there is a local variable, local constant or lambda parameter // but NOT range variable that shadows a local variable, local constant, formal parameter, // range variable, or lambda parameter that was declared in an enclosing local declaration space. Again, // report it on the inner usage. eg: // // void M() { int y; { int y; } } // // CS0412: (ERR_LocalSameNameAsTypeParam) // 'X': a parameter or local variable cannot have the same name as a method type parameter // // Reported *only* when a local variable, local constant, formal parameter or lambda parameter // has the same name as a method type parameter. eg: // // void M<X>(){ int X; } // // CS1948: (ERR_QueryRangeVariableSameAsTypeParam) // The range variable 'X' cannot have the same name as a method type parameter // // Reported *only* when a range variable has the same name as a method type parameter. eg: // // void M<X>(){ var q = from X in z select X; } // // CS1930: (ERR_QueryDuplicateRangeVariable) // The range variable 'x' has already been declared // // Reported *only* if a range variable shadows another range variable that is in scope. eg: // // from x in y from x in z select q // // CS1931: (ERR_QueryRangeVariableOverrides) // The range variable 'x' conflicts with a previous declaration of 'x' // // Reported when there is a range variable that shadows a non-range variable from an // enclosing scope. eg: // // int x; var y = from x in q select m; // namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class NameCollisionTests : CompilingTestBase { [Fact] public void TestNamesFromTypeAndExpressionContextsDontCollide() { var source = @" using name1 = System.Exception; namespace Namespace { using name3 = System.Type; class Class { Class(name2 other1, name1 other2) { name3 other3 = typeof(name1); if (typeof(name1) != typeof(name2) || typeof(name2) is name3 || typeof(name1) is name3) { foreach (var name1 in ""string"") { for (var name2 = 1; name2 > --name2; name2++) { int name3 = name2; } } } else { name2 name1 = null, name2 = name1; name3 name3 = typeof(name2); } } } } class name2 { }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestLocalAndLabelDontCollide() { var source = @" using System; namespace Namespace { using name1 = System.Type; class Class { Class(name1 name1) { goto name2; name2: Console.WriteLine(); var name2 = new name2(); goto name1; name1: Console.WriteLine(); } } } class name2 { }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLabelWithLabel() { var source = @" using System; namespace Namespace { using name1 = System.Type; class Class { Class(name1 name1) { goto name1; name1: Console.WriteLine(); { goto name1; name1: Console.WriteLine(); var name2 = new name2(); goto name2; name2: Console.WriteLine(); } goto name2; name2: Console.WriteLine(); } internal int Property { set { goto name1; name1: Console.WriteLine(); Action lambda1 = () => { Action lambda2 = () => { goto name1; name1: Console.WriteLine(); var name2 = new name2(); goto name2; name2: Console.WriteLine(); }; goto name2; name2: Console.WriteLine(); }; } } } } class name2 { }"; CreateCompilation(source).VerifyDiagnostics( // (14,13): error CS0158: The label 'name1' shadows another label by the same name in a contained scope // name1: Console.WriteLine(); Diagnostic(ErrorCode.ERR_LabelShadow, "name1").WithArguments("name1"), // (17,13): error CS0158: The label 'name2' shadows another label by the same name in a contained scope // name2: Console.WriteLine(); Diagnostic(ErrorCode.ERR_LabelShadow, "name2").WithArguments("name2"), // (34,21): error CS0158: The label 'name1' shadows another label by the same name in a contained scope // name1: Console.WriteLine(); Diagnostic(ErrorCode.ERR_LabelShadow, "name1").WithArguments("name1"), // (37,21): error CS0158: The label 'name2' shadows another label by the same name in a contained scope // name2: Console.WriteLine(); Diagnostic(ErrorCode.ERR_LabelShadow, "name2").WithArguments("name2")); } [Fact] public void TestCollisionOfLocalWithTypeOrMethodOrProperty_LegalCases() { var source = @" using System; namespace name1 { class Class { void name1() { { name1(); } { int name1 = name1 = 1; } foreach(var name1 in ""string"") ; } } } class name2 { Action lambda = () => { { int name2 = name2 = 2; Console.WriteLine(name3); } { int name3 = name3 = 3; } }; static int name3 { get { return 4; } } }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithType() { var source = @" using name1 = System.Console; class Class { Class() { { name1.WriteLine(); // Legal name2.Equals(null, null); // Legal } { int name1 = (name1 = 1), name2 = name2 = 2; // Legal -- strange, but legal } { name1.WriteLine(); name2.Equals(null, null); { int name1 = 3, name2 = name1; // 0135 on name1, name2 // Native compiler reports 0136 here; Roslyn reports 0135. } } } } class name2 { }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithMethodOrProperty() { var source = @" using System; namespace name1 { class Class { void name1() { name1(); { name1(); } { int name1 = name1 = 1; // 0135: Roslyn reports 0135, native reports 0136. } foreach (var name1 in ""string"") ; // 0135: Roslyn reports 0135, native reports 0136. } Action lambda = () => { { int name2 = name2 = 2; // 0135: conflicts with usage of name2 as the static property below. // Roslyn reports this here; native compiler reports it below. Console.WriteLine(name2); } Console.WriteLine(name2); // Native compiler reports 0135 here; Roslyn reports it above. }; static int name2 { get { return 3; } } } }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(542039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542039")] [Fact] public void TestCollisionOfDelegateWithConst() { var source = @"class A { delegate void D(); static void Goo() { } class B { const int Goo = 123; static void Main() { Goo(); Bar(Goo); } static void Main2() { Bar(Goo); Goo(); } static void Bar(int x) { } static void Bar(D x) { } } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithTypeParameter() { var source = @" class Class<name1, name2> { void Method<name3, name4>(name1 other1, name4 name4) // 0412 on name4 { { int name3 = 10; // 0412 on name3 System.Console.WriteLine(name3); // Eliminate warning foreach (var name2 in ""string"") { for (var name1 = 1; name1 <= name1++; name1++) // legal; name1 conflicts with a class type parameter which is not in the local variable decl space name1 = name2.GetHashCode(); } } { name1 other2 = typeof(name1) is name1 ? other1 : other1; // no error; all the name1's refer to the type, not the local. int name1 = (name1 = 2), name2 = name2 = 3; // legal; name1 conflicts with a class type parameter which is not in the local variable decl space foreach (var name3 in ""string"") // 0412 on name3 { System.Console.WriteLine(name3); // Eliminate warning for (var name4 = 4; ; ) // 0412 on name4 { name1 = name2.GetHashCode(); System.Console.WriteLine(name4); // Eliminate warning } } try {} catch(System.Exception name3) // 0412 on name3 { System.Console.WriteLine(name3); } } } }"; CreateCompilation(source).VerifyDiagnostics( // (4,51): error CS0412: 'name4': a parameter or local variable cannot have the same name as a method type parameter // void Method<name3, name4>(name1 other1, name4 name4) // 0412 on name4 Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "name4").WithArguments("name4").WithLocation(4, 51), // (7,17): error CS0412: 'name3': a parameter or local variable cannot have the same name as a method type parameter // int name3 = 10; // 0412 on name3 Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "name3").WithArguments("name3").WithLocation(7, 17), // (18,26): error CS0412: 'name3': a parameter or local variable cannot have the same name as a method type parameter // foreach (var name3 in "string") // 0412 on name3 Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "name3").WithArguments("name3").WithLocation(18, 26), // (21,26): error CS0136: A local or parameter named 'name4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // for (var name4 = 4; ; ) // 0412 on name4 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name4").WithArguments("name4"), // (28,36): error CS0412: 'name3': a parameter or local variable cannot have the same name as a method type parameter // catch(System.Exception name3) // 0412 on name3 Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "name3").WithArguments("name3")); } [Fact] public void TestCollisionOfLocalWithField_LegalCases() { var source = @" partial class Derived : Base { private Derived() { this.name1 = 1; long name1 = this.name1; if (true) { name1 = this.name1 = name1; name2 = this.name2 = name2 + name1; } { while (name1 == 1) { long name2 = 2; name1 = name2; } do { long name2 = 3; name1 = name2; name1 = this.name1; } while (name1 != 1); } } } class Base { public long name2 = name1; private static int name1 = 4; } partial class Derived { internal long name1 = 5; }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithField1() { var source = @" class Derived : Base { static long name1 = 1; static Derived() { while(name1 == 2) { int name1 = 3, other = name1, name2 = other; // 0135 on name1 and name2 // Native reports 0136 on name1 here and 0135 on name2 below. } do { } while (name2 == 4); // Native reports 0135 on name2 here; Roslyn reports it above. } } class Base { protected static long name2 = 5; }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithField2() { var source = @" class Class { public static int M() { return 1; } internal int Property { set { for (int i = 0; i < int.MaxValue; ++i) { if (i == 0) { int other = M(), name = M(), name = other; // 0128, 0135 } else { { int name = M(); name = M(); // 0135 } } } for (int i = 0; i > int.MinValue; ++i) { { i += 1; } } name = M(); } } private const int x = 123; private void M1(int x = x) {} // UNDONE: Native and Roslyn compilers both allow this; should they? private void M2(int y = x) { int x = M(); // UNDONE: Native and Roslyn compilers both allow this; should they? } private long other = 0, name = 6; }"; CreateCompilation(source).VerifyDiagnostics( // (13,50): error CS0128: A local variable named 'name' is already defined in this scope // int other = M(), name = M(), name = other; // 0128, 0135 Diagnostic(ErrorCode.ERR_LocalDuplicate, "name").WithArguments("name"), // (37,18): warning CS0414: The field 'Class.other' is assigned but its value is never used // private long other = 0, name = 6; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "other").WithArguments("Class.other") ); } [Fact] public void TestCollisionInsideFieldDeclaration() { // A close reading of the spec would indicate that this is not an error because the // offending simple name 'x' does not appear in any local variable declaration space. // A field initializer is not a declaration space. However, it seems plausible // that we want to report the error here. The native compiler does so as well. var source = @" class Class { private static int M() { return 1; } private static int x = 123; private static int z = x + ((System.Func<int>)( ()=>{ int x = M(); return x; } ))(); }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithField_PartialType() { var source = @" partial struct PartialStruct { private void Method() { if (true) { { int name = 1, other = name; } } name = 2; // Native compiler reports 0135 here; Roslyn no longer reports 0135. } } partial struct PartialStruct { internal long name; }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithLocal_LegalCases1() { var source = @" partial class Derived : Base { private string Property { get { if (true) { int name = (name = 1); name += name; } { { int name = 2; name -= name; } } for(long name = 3; name <= 4; ++name) name += 5; foreach(var name in ""string"") { name.ToString(); } return this.name; } } } class Base { public string name = null; }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithLocal_LegalCases2() { var source = @" using System; using System.Linq; partial class Derived : Base { private string Property { get { // http://blogs.msdn.com/b/ericlippert/archive/2009/11/02/simple-names-are-not-so-simple.aspx foreach (var name in from name in ""string"" orderby name select name) Console.WriteLine(name); return this.name; } } } class Base { public string name = null; }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithLocal_LegalCases3() { var source = @" using System; using System.Linq; partial class Derived : Base { private string Property { get { // http://blogs.msdn.com/b/ericlippert/archive/2009/11/02/simple-names-are-not-so-simple.aspx foreach(var name in ""string"".OrderBy(name => name).Select(name => name)) { Console.WriteLine(name); } return this.name; } } } class Base { public string name = null; }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithLocal() { var source = @" class Class { public Class() { long name1 = 1; System.Console.WriteLine(name1); // Eliminate unused warning. name4 = name6; // 0841 on name4; used before declared. 0103 on name6; not defined in this context if (true) { { int other1 = 2, name1 = other1, name2 = name1; // 0136 on name1; already used in parent scope to mean something else. } // Native compiler reports 0136 on 'long name2' below; Roslyn reports it on 'int ... name2' here and 'var name2' below { if (true) { for (long name1 = this.name2; name1 >= --name1; name1++) // 0136 on name1; { name1.ToString(); name5.ToString(); // 0841: name5 is used before the declaration string name6 = ""string""; } } foreach (var name2 in ""string"") name2.ToString(); // 0136: Native reports this on 'long name2' below; Roslyn reports it here, and above. } string @name3 = ""string"", other2 = name3, name3 = other2; // 0128: name3 is defined twice. long @name2 = 3; System.Console.WriteLine(@name2); // eliminated unused warning. // Native compiler reports 0136 on 'long name2' here; Roslyn reports it on 'int ... name2' above. } string name4 = ""string"", name5 = name4; name6 = name3; // 0103 on both name6 and name3; not defined in this context. } public long name2 = 4; }"; CreateCompilation(source).VerifyDiagnostics( // (7,9): error CS0841: Cannot use local variable 'name4' before it is declared // name4 = name6; // 0841 on name4; used before declared. 0103 on name6; not defined in this context Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "name4").WithArguments("name4").WithLocation(7, 9), // (7,17): error CS0103: The name 'name6' does not exist in the current context // name4 = name6; // 0841 on name4; used before declared. 0103 on name6; not defined in this context Diagnostic(ErrorCode.ERR_NameNotInContext, "name6").WithArguments("name6").WithLocation(7, 17), // (11,33): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int other1 = 2, name1 = other1, name2 = name1; // 0136 on name1; already used in parent scope to mean something else. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(11, 33), // (11,49): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int other1 = 2, name1 = other1, name2 = name1; // 0136 on name1; already used in parent scope to mean something else. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(11, 49), // (16,31): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // for (long name1 = this.name2; name1 >= --name1; name1++) // 0136 on name1; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(16, 31), // (18,43): error CS0841: Cannot use local variable 'name5' before it is declared // name1.ToString(); name5.ToString(); // 0841: name5 is used before the declaration Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "name5").WithArguments("name5").WithLocation(18, 43), // (22,30): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name2 in "string") name2.ToString(); // 0136: Native reports this on 'long name2' below; Roslyn reports it here, and above. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(22, 30), // (24,55): error CS0128: A local variable named 'name3' is already defined in this scope // string @name3 = "string", other2 = name3, name3 = other2; // 0128: name3 is defined twice. Diagnostic(ErrorCode.ERR_LocalDuplicate, "name3").WithArguments("name3").WithLocation(24, 55), // (29,9): error CS0103: The name 'name6' does not exist in the current context // name6 = name3; // 0103 on both name6 and name3; not defined in this context. Diagnostic(ErrorCode.ERR_NameNotInContext, "name6").WithArguments("name6").WithLocation(29, 9), // (29,17): error CS0103: The name 'name3' does not exist in the current context // name6 = name3; // 0103 on both name6 and name3; not defined in this context. Diagnostic(ErrorCode.ERR_NameNotInContext, "name3").WithArguments("name3").WithLocation(29, 17), // (19,32): warning CS0219: The variable 'name6' is assigned but its value is never used // string name6 = "string"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "name6").WithArguments("name6").WithLocation(19, 32) ); } [Fact] public void TestCollisionOfLocalWithParam() { var source = @" using System; class Class { public Func<int, int, int> Method(int name1, int name2) { foreach (var name1 in ""string"") // 0136 { foreach (var name2 in ""string"") // 0136 { int name1 = name2.GetHashCode(); // 0136 } } Action<int> lambda = (name3) => { int name1 = 1; // 0136 if(name1 == 2) { name2 = name3 = name1; } else { int name2 = 3; // 0136 System.Console.WriteLine(name2); { int name3 = 2; // 0136 System.Console.WriteLine(name3); } } }; return (name1, name2) => name1; // 0136 on both name1 and name2 } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,22): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name1 in "string") // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(7, 22), // (9,26): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name2 in "string") // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(9, 26), // (11,21): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name1 = name2.GetHashCode(); // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(11, 21), // (17,17): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name1 = 1; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(17, 17), // (24,21): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name2 = 3; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(24, 21), // (27,25): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name3 = 2; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(27, 25), // (32,17): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // return (name1, name2) => name1; // 0136 on both name1 and name2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(32, 17), // (32,24): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // return (name1, name2) => name1; // 0136 on both name1 and name2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(32, 24) ); CreateCompilation(source).VerifyDiagnostics( // (7,22): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name1 in "string") // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(7, 22), // (9,26): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name2 in "string") // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(9, 26), // (11,21): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name1 = name2.GetHashCode(); // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(11, 21), // (27,25): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name3 = 2; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(27, 25) ); } [Fact] public void TestCollisionOfParamWithParam() { var source = @" using System; class Class { public static void Method(int name1, int name2, int name2) // 0100 on name2 { Action<int, int> lambda = (other, name3) => { Action<int, int, int, int> nestedLambda = (name1, name4, name4, name3) => // 0100 on name4, 0136 on name1 and name3 { }; }; } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (5,57): error CS0100: The parameter name 'name2' is a duplicate // public static void Method(int name1, int name2, int name2) // 0100 on name2 Diagnostic(ErrorCode.ERR_DuplicateParamName, "name2").WithArguments("name2").WithLocation(5, 57), // (9,56): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action<int, int, int, int> nestedLambda = (name1, name4, name4, name3) => // 0100 on name4, 0136 on name1 and name3 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(9, 56), // (9,70): error CS0100: The parameter name 'name4' is a duplicate // Action<int, int, int, int> nestedLambda = (name1, name4, name4, name3) => // 0100 on name4, 0136 on name1 and name3 Diagnostic(ErrorCode.ERR_DuplicateParamName, "name4").WithArguments("name4").WithLocation(9, 70), // (9,77): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action<int, int, int, int> nestedLambda = (name1, name4, name4, name3) => // 0100 on name4, 0136 on name1 and name3 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(9, 77) ); CreateCompilation(source).VerifyDiagnostics( // (5,57): error CS0100: The parameter name 'name2' is a duplicate // public static void Method(int name1, int name2, int name2) // 0100 on name2 Diagnostic(ErrorCode.ERR_DuplicateParamName, "name2").WithArguments("name2").WithLocation(5, 57), // (9,70): error CS0100: The parameter name 'name4' is a duplicate // Action<int, int, int, int> nestedLambda = (name1, name4, name4, name3) => // 0100 on name4, 0136 on name1 and name3 Diagnostic(ErrorCode.ERR_DuplicateParamName, "name4").WithArguments("name4").WithLocation(9, 70) ); } [WorkItem(930252, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930252")] [Fact] public void TestCollisionOfParamWithParam1() { var source = @" class Program { delegate int D(int x, int y); static void X() { D d1 = (int x, int x) => { return 1; }; D d2 = (x, x) => { return 1; }; } }"; CreateCompilation(source).VerifyDiagnostics( // (7,28): error CS0100: The parameter name 'x' is a duplicate // D d1 = (int x, int x) => { return 1; }; Diagnostic(ErrorCode.ERR_DuplicateParamName, "x").WithArguments("x").WithLocation(7, 28), // (8,20): error CS0100: The parameter name 'x' is a duplicate // D d2 = (x, x) => { return 1; }; Diagnostic(ErrorCode.ERR_DuplicateParamName, "x").WithArguments("x").WithLocation(8, 20) ); } [Fact] public void TestCollisionInsideLambda_LegalCases() { var source = @" using System; partial class Class { private string Property { set { this. Method((name1) => { name1 = string.Empty; for (int name2 = name2 = 1; ; ) ; }). Method((name1) => name1.ToString()). Method((name1) => { foreach (var name2 in string.Empty) ; return name1; }); } } Class Method(Action<string> name1) { return null; } Class Method(Func<string, string> name1) { return null; } }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionInsideLambda1() { var source = @" using System; class Derived : Base { static int M() { return 1; } static long name1 = 1; Action lambda = () => { name1 = 2; { int name1 = 3, other = name1, name2 = other; // 0135: on name1 and name2. // Native compiler reports 0136 here on name1 and 0135 on name2 below. // Roslyn reports them both as 0135 here. } name2 = 4; // Native compiler reports 0135 here; Roslyn reports above. int name3 = M(); { { name3 = 6; } if (true) { int name3 = M(); // 0136: Native compiler says 0135, Roslyn says 0136. The conflict is with the other local. } } }; Action anonMethod = delegate() { name1 = 8; if (true) { int name1 = 9, other = name1, name2 = other; // 0135: on name1, name2 // Native compiler reports 0136 on name1, Roslyn reports 0135. // Native compiler reports 0135 on name2 below, Roslyn reports it here. } { foreach (var name3 in ""string"") name3.ToString(); // 0136: Native compiler reports 0136 below, Roslyn reports it here. } name2 = 10; // Native compiler reports 0135 here; Roslyn reports it above. int name3 = M(); }; } class Base { protected static long name2 = 12; }"; CreateCompilation(source).VerifyDiagnostics( // (24,21): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name3 = M(); // 0136: Native compiler says 0135, Roslyn says 0136. The conflict is with the other local. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(24, 21), // (39,26): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name3 in "string") name3.ToString(); // 0136: Native compiler reports 0136 below, Roslyn reports it here. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(39, 26), // (6,17): warning CS0414: The field 'Derived.name1' is assigned but its value is never used // static long name1 = 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "name1").WithArguments("Derived.name1").WithLocation(6, 17) ); } [Fact] public void TestCollisionInsideLambda2() { var source = @" using System; class Class { void Method(Action lambda) { } void Method() { const long name1 = 1; System.Console.WriteLine(name1); // Eliminate warning. Method(() => { Console.WriteLine(name1); { const int name1 = 2; // 0136 int other = name1, name2 = other; // 0136: Native compiler reports this on 'const long name' below; Roslyn reports it here. } name2 = 3; // 0841: local used before declared const int name3 = 4; { { Console.WriteLine(name3); } if (true) { const int name3 = 5; // 0136 Console.WriteLine(name3); } } }); Method(delegate() { Console.WriteLine(name1); if (true) { const int name1 = 6, other = name1, name2 = other; // 0136 on name1 and name2 Console.WriteLine(name1 + other + name2); } // Roslyn reports 0136 on name2 above; native compiler reports it on 'const long name2' below. { foreach (var name3 in ""string"") name3.ToString(); // 0136: Roslyn reports this here, native reports it below. } Console.WriteLine(name2); // 0814: local used before declared const int name3 = 7; // Native compiler reports 0136 here, Roslyn reports it on 'var name3' above. Console.WriteLine(name3); // eliminate warning }); const long name2 = 8; // Native compiler reports 0136 here; Roslyn reports it on both offending nested decls above. Console.WriteLine(name2); } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (15,27): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // const int name1 = 2; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(15, 27), // (16,36): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int other = name1, name2 = other; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(16, 36), // (18,13): error CS0841: Cannot use local variable 'name2' before it is declared // name2 = 3; // 0841: local used before declared Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "name2").WithArguments("name2").WithLocation(18, 13), // (27,31): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // const int name3 = 5; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(27, 31), // (38,27): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // const int name1 = 6, other = name1, name2 = other; // 0136 on name1 and name2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(38, 27), // (38,53): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // const int name1 = 6, other = name1, name2 = other; // 0136 on name1 and name2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(38, 53), // (42,30): error CS0841: Cannot use local variable 'name3' before it is declared // foreach (var name3 in ""string"") name3.ToString(); // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(42, 30), // (44,31): error CS0841: Cannot use local variable 'name2' before it is declared // Console.WriteLine(name2); // 0814: local used before declared Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "name2").WithArguments("name2").WithLocation(44, 31)); CreateCompilation(source).VerifyDiagnostics( // (18,13): error CS0841: Cannot use local variable 'name2' before it is declared // name2 = 3; // 0841: local used before declared Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "name2").WithArguments("name2").WithLocation(18, 13), // (27,31): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // const int name3 = 5; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(27, 31), // (42,30): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name3 in "string") name3.ToString(); // 0136: Roslyn reports this here, native reports it below. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(42, 30), // (44,31): error CS0841: Cannot use local variable 'name2' before it is declared // Console.WriteLine(name2); // 0814: local used before declared Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "name2").WithArguments("name2").WithLocation(44, 31)); } [Fact] public void TestCollisionInsideOperator() { var source = @" using System; class Class { static long name1 = 1; public static Class operator +(Class name1, Class other) { var lambda = (Action)(() => { const int name1 = @name2; // 0136 on name1 because it conflicts with parameter if (true) { int name2 = name1; // 0135 because name2 conflicts with usage of name2 as Class.name2 above Console.WriteLine(name2); } }); return other; } const int name2 = 2; public static void Other() { Console.WriteLine(name1); } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (10,23): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // const int name1 = @name2; // 0136 on name1 because it conflicts with parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(10, 23)); CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionInsideIndexer() { var source = @" class Class { static long name1 = 1; public int this[int name1] { get { foreach (var name2 in ""string"") { foreach (var name2 in ""string"") // 0136 on name2 { int name1 = name2.GetHashCode(); // 0136 on name1 } } return name1; } } static long name2 = name1 + name2; }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (11,30): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name2 in "string") // 0136 on name2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2"), // (13,25): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name1 = name2.GetHashCode(); // 0136 on name1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1")); } [Fact] public void TestCollisionInsideFor1() { var source = @" class Class { void Method1(int name4 = 1, params int[] name5) { for (int name1 = 2; name1 <= name1++; ++name1) { foreach (var name2 in ""string"") { for (name1 = 3; ; ) { break; } for (int name2 = name1; name2 <= name2++; ++name2) // 0136 on name2 { int name3 = 4, name4 = 5, name5 = 6; // 0136 on name3, name4 and name5 // Native compiler reports 0136 on name3 below, Roslyn reports it above. System.Console.WriteLine(name3 + name4 + name5); // Eliminate warning } } foreach (var name1 in ""string"") ; // 0136 on name1 } int name3 = 7; // Native compiler reports 0136 on name3 here; Roslyn reports it above. System.Console.WriteLine(name3); // Eliminate warning } }"; CreateCompilation(source).VerifyDiagnostics( // (11,26): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // for (int name2 = name1; name2 <= name2++; ++name2) // 0136 on name2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(11, 26), // (13,25): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name3 = 4, name4 = 5, name5 = 6; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(13, 25), // (13,36): error CS0136: A local or parameter named 'name4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name3 = 4, name4 = 5, name5 = 6; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name4").WithArguments("name4").WithLocation(13, 36), // (13,47): error CS0136: A local or parameter named 'name5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name3 = 4, name4 = 5, name5 = 6; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name5").WithArguments("name5").WithLocation(13, 47), // (13,47): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name1 in ""string"") ; // 0136 on name1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(18, 26)); } [Fact] public void TestCollisionInsideFor2() { var source = @" using System.Linq; using System.Collections; partial class Class { private string Property { get { for (var name = from name in ""string"" orderby name select name; name != null; ) ; // 1931 for (IEnumerable name = null; name == from name in ""string"" orderby name select name; ) ; // 1931 for (IEnumerable name = null; name == null; name = from name in ""string"" orderby name select name ) ; // 1931 return string.Empty; } } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (11,51): warning CS8848: Operator 'from' cannot be used here due to precedence. Use parentheses to disambiguate. // for (IEnumerable name = null; name == from name in "string" orderby name select name; ) ; // 1931 Diagnostic(ErrorCode.WRN_PrecedenceInversion, @"from name in ""string""").WithArguments("from").WithLocation(11, 51), // (10,34): error CS1931: The range variable 'name' conflicts with a previous declaration of 'name' // for (var name = from name in "string" orderby name select name; name != null; ) ; // 1931 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "name").WithArguments("name").WithLocation(10, 34), // (11,56): error CS1931: The range variable 'name' conflicts with a previous declaration of 'name' // for (IEnumerable name = null; name == from name in "string" orderby name select name; ) ; // 1931 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "name").WithArguments("name").WithLocation(11, 56), // (12,69): error CS1931: The range variable 'name' conflicts with a previous declaration of 'name' // for (IEnumerable name = null; name == null; name = from name in "string" orderby name select name ) ; // 1931 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "name").WithArguments("name").WithLocation(12, 69)); } [WorkItem(792744, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792744")] [Fact] public void TestCollisionInsideForeach() { var source = @" class Class { static int y = 1; static void Main(string[] args) { foreach (var y in new[] {new { y = y }}){ } //End } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(); } [Fact] public void TestCollisionInsideUsing() { var source = @" class Class : System.IDisposable { public void Dispose() {} int[] name3 = {}; void Method1(Class name2 = null) { using (var name1 = new Class()) { int other = (name3[0]); } using (var name1 = new Class()) { var other = name3[0].ToString(); using (var name3 = new Class()) // 0135 because name3 above refers to this.name3 { int name1 = 2; // 0136 on name1 } } using (var name2 = new Class()) // 0136 on name2. { int name1 = 2; int other = (name3[0]); } using (name2 = new Class()) { int name1 = 2; int other = (name3[0]); } } }"; CreateCompilation(source).VerifyDiagnostics( // (17,21): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name1 = 2; // 0136 on name1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(17, 21), // (17,21): warning CS0219: The variable 'name1' is assigned but its value is never used // int name1 = 2; // 0136 on name1 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "name1").WithArguments("name1").WithLocation(17, 21), // (20,20): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (var name2 = new Class()) // 0136 on name2. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(20, 20), // (22,17): warning CS0219: The variable 'name1' is assigned but its value is never used // int name1 = 2; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "name1").WithArguments("name1").WithLocation(22, 17), // (27,17): warning CS0219: The variable 'name1' is assigned but its value is never used // int name1 = 2; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "name1").WithArguments("name1").WithLocation(27, 17) ); } [Fact] public void TestCollisionInsideLock() { var source = @" using System; class Class { const int[] name = null; void Method1() { lock (name) { } { lock (string.Empty) { const int name = 0; // 0135 because name above means 'this.name'. Console.WriteLine(name); } } } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionInsideSwitch() { var source = @" class Class { int M() { return 1; } int name1 = 1; void Method1() { switch (name1) { case name1: break; // 0844: use of 'int name1' below before it is declared -- surprising error, but correct. Also notes that local name1 hides field. case 2: int name1 = 2; // 0135: because 'name1' above means 'this.name1'. Native compiler reports 0136, Roslyn reports 0135. var name2 = 3; System.Console.WriteLine(name1 + name2); break; case 3: name2 = M(); // Not a use-before-declaration error; name2 is defined above var name2 = M(); // 0128 on name2; switch sections share the same declaration space for (int name3 = 5; ; ) { System.Console.WriteLine(name2 + name3); break; } int name4 = 6; System.Console.WriteLine(name4); break; case 4: name1 = 2; for (int name3 = 7; ; ) { System.Console.WriteLine(name3); break; } switch (name1) { case 1: int name4 = 8, name5 = 9; // 0136 on name4, name5 // Native compiler reports error 0136 on `name5 = 11` below; Roslyn reports it here. System.Console.WriteLine(name4 + name5); break; } for (int name6 = 10; ; ) // 0136 on name6; Native compiler reports 0136 on name6 below. { System.Console.WriteLine(name6);} default: int name5 = 11, name6 = 12; // Native compiler reports 0136 on name5 and name6. Roslyn reports them above. System.Console.WriteLine(name5 + name6); break; } } }"; CreateCompilation(source).VerifyDiagnostics( // (10,18): error CS0844: Cannot use local variable 'name1' before it is declared. The declaration of the local variable hides the field 'Class.name1'. // case name1: break; // 0844: use of 'int name1' below before it is declared -- surprising error, but correct. Also notes that local name1 hides field. Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclarationAndHidesField, "name1").WithArguments("name1", "Class.name1").WithLocation(10, 18), // (18,21): error CS0128: A local variable named 'name2' is already defined in this scope // var name2 = M(); // 0128 on name2; switch sections share the same declaration space Diagnostic(ErrorCode.ERR_LocalDuplicate, "name2").WithArguments("name2").WithLocation(18, 21), // (31,29): error CS0136: A local or parameter named 'name4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name4 = 8, name5 = 9; // 0136 on name4, name5 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name4").WithArguments("name4").WithLocation(31, 29), // (31,40): error CS0136: A local or parameter named 'name5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name4 = 8, name5 = 9; // 0136 on name4, name5 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name5").WithArguments("name5").WithLocation(31, 40), // (36,26): error CS0136: A local or parameter named 'name6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // for (int name6 = 10; ; ) // 0136 on name6; Native compiler reports 0136 on name6 below. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name6").WithArguments("name6").WithLocation(36, 26) ); } [Fact] public void TestCollisionInsideTryCatch_LegalCases() { var source = @" using System; class Derived : Base { static long name1 = 1; static Derived() { { try { Console.WriteLine(name1); } catch (ArgumentException name1) { Console.WriteLine(name1.Message); } catch (Exception name1) { Console.WriteLine(name1.Message); } } { Console.WriteLine(name1); try { var name4 = string.Empty; try { name2 = 3; string name5 = string.Empty; name5.ToString(); name4.ToString(); } catch (Exception name2) { Console.WriteLine(name2.Message); string name5 = string.Empty; name5.ToString(); name4.ToString(); } } catch (Exception other) { var name4 = string.Empty; Console.WriteLine(name4.ToString()); name2 = 4; Console.WriteLine(other.Message); } } } } class Base { protected static long name2 = 5; }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionInsideTryCatch() { var source = @" using System; class Derived : Base { static long name1 = 1; static Derived() { { Console.WriteLine(name1); try { Console.WriteLine(name1); } catch (ArgumentException name1) { Console.WriteLine(name1.Message); } catch (Exception name2) { Console.WriteLine(name2.Message); } Console.WriteLine(name2); } { try { var name4 = string.Empty; Console.WriteLine(name1); } catch (Exception name1) { System.Console.WriteLine(name1.Message); var name5 = string.Empty; try { } catch (Exception name1) // 0136 on name1 { var name5 = string.Empty; // 0136 on name5 System.Console.WriteLine(name1.Message); } } var name4 = string.Empty; // Native reports 0136 here; } } } class Base { protected static long name2 = 2; }"; CreateCompilation(source).VerifyDiagnostics( // (27,21): error CS0136: A local or parameter named 'name4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var name4 = string.Empty; // 0136: Roslyn reports this here; native reports it below. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name4").WithArguments("name4").WithLocation(27, 21), // (38,34): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch (Exception name1) // 0136 on name1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(38, 34), // (40,25): error CS0136: A local or parameter named 'name5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var name5 = string.Empty; // 0136 on name5 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name5").WithArguments("name5").WithLocation(40, 25) ); } [Fact] public void DifferentArities() { var source = @" public class C<T> { public static U G<U>(U x) { return x; } void M() { int G = 10; G<int>(G); int C = 5; C<string>.G(C); } }"; CompileAndVerify(source).VerifyDiagnostics(); } [WorkItem(10556, "DevDiv_Projects/Roslyn")] [Fact] public void TestCollisionInsideQuery_LegalCases() { var source = @" using System.Linq; using System.Collections.Generic; partial class Class { private string Property { set { var other1 = from int name1 in ""string"" select name1; { var query1 = from name1 in ""string"" select name1; var query2 = from name1 in ""string"" select name1; this.Method(from name1 in ""string"" select name1).Method(from name1 in ""string"" select name1); } other1 = from int name1 in ""string"" select name2; { var query1 = from name1 in ""string"" let name2 = 1 select name1; var query2 = from name2 in ""string"" select name2; this.Method(from other2 in ""string"" from name2 in ""string"" select other2).Method(from name1 in ""string"" group name1 by name1 into name2 select name2); Method(from name1 in ""string"" group name1 by name1.ToString() into name1 select name1); } } } int name2 = 2; Class Method(IEnumerable<char> name1) { return null; } Class Method(object name1) { return null; } }"; CompileAndVerify(source).VerifyDiagnostics(); } [WorkItem(543045, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543045")] [Fact] public void TestCollisionInsideQuery() { var source = @" using System; using System.Linq; using System.Collections.Generic; partial class Class { private string Property { set { Console.WriteLine(name1); { var query1 = from name1 in string.Empty // 1931 -- UNDONE change to 0135 because name1 above refers to Class.name1 select name1; var query2 = from other in string.Empty let name1 = 1 // 1931 -- UNDONE change to 0135 because name1 above refers to Class.name1 select other; this.Method(from other in string.Empty from name1 in string.Empty // 1931 -- UNDONE change to 0135 because name1 above refers to Class.name1 select other).Method(from other in string.Empty group other by other.ToString() into name1 // 1931 -- UNDONE change to 0135 because name1 above refers to Class.name1 select name1); } { var query1 = from name2 in string.Empty let name2 = 2 // 1930 select name2; this.Method(from name2 in string.Empty from name2 in name1.ToString() // 1930 select name2); } } } int name1 = 3; Class Method(IEnumerable<char> name1) { return null; } Class Method(object name1) { return null; } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (26,34): error CS1930: The range variable 'name2' has already been declared // let name2 = 2 // 1930 Diagnostic(ErrorCode.ERR_QueryDuplicateRangeVariable, "name2").WithArguments("name2").WithLocation(26, 34), // (29,34): error CS1930: The range variable 'name2' has already been declared // from name2 in name1.ToString() // 1930 Diagnostic(ErrorCode.ERR_QueryDuplicateRangeVariable, "name2").WithArguments("name2").WithLocation(29, 34) ); } [Fact] public void TestCollisionInsideQuery_TypeParameter() { var source = @" using System.Linq; public class Class { void Method<T, U>() { { var q = from T in """" let U = T select T; } } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (7,26): error CS1948: The range variable 'T' cannot have the same name as a method type parameter // var q = from T in "" Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "T").WithArguments("T"), // (8,25): error CS1948: The range variable 'U' cannot have the same name as a method type parameter // let U = T Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "U").WithArguments("U")); } [WorkItem(542088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542088")] [Fact] public void LocalCollidesWithGenericType() { var source = @" public class C { public static int G<T>(int x) { return x; } public static void Main() { int G = 10; G<int>(G); } }"; CompileAndVerify(source).VerifyDiagnostics(); } [WorkItem(542039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542039")] [Fact] public void BindingOrderCollisions01() { var source = @"using System; class A { static long M(Action<long> act) { return 0; } static void What1() { int x1; { int y1 = M(x1 => { }); } } static void What2() { { int y2 = M(x2 => { }); } int x2; } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (10,24): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int y1 = M(x1 => { }); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(10, 24), // (10,22): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // int y1 = M(x1 => { }); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "M(x1 => { })").WithArguments("long", "int").WithLocation(10, 22), // (8,13): warning CS0168: The variable 'x1' is declared but never used // int x1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(8, 13), // (16,24): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int y2 = M(x2 => { }); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(16, 24), // (16,22): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // int y2 = M(x2 => { }); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "M(x2 => { })").WithArguments("long", "int").WithLocation(16, 22), // (18,13): warning CS0168: The variable 'x2' is declared but never used // int x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(18, 13) ); CreateCompilation(source).VerifyDiagnostics( // (10,22): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // int y1 = M(x1 => { }); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "M(x1 => { })").WithArguments("long", "int").WithLocation(10, 22), // (8,13): warning CS0168: The variable 'x1' is declared but never used // int x1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(8, 13), // (16,22): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // int y2 = M(x2 => { }); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "M(x2 => { })").WithArguments("long", "int").WithLocation(16, 22), // (18,13): warning CS0168: The variable 'x2' is declared but never used // int x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(18, 13) ); } [WorkItem(542039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542039")] [Fact] public void BindingOrderCollisions02() { var source = @"using System; class A { static double M(Action<double> act) { return 0; } static long M(Action<long> act) { return 0; } static void What1() { int x1; { int y1 = M(x1 => { }); } } static void What2() { { int y2 = M(x2 => { }); } int x2; } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (11,24): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int y1 = M(x1 => { }); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(11, 24), // (11,22): error CS0121: The call is ambiguous between the following methods or properties: 'A.M(Action<double>)' and 'A.M(Action<long>)' // int y1 = M(x1 => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("A.M(System.Action<double>)", "A.M(System.Action<long>)").WithLocation(11, 22), // (9,13): warning CS0168: The variable 'x1' is declared but never used // int x1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(9, 13), // (17,24): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int y2 = M(x2 => { }); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(17, 24), // (17,22): error CS0121: The call is ambiguous between the following methods or properties: 'A.M(Action<double>)' and 'A.M(Action<long>)' // int y2 = M(x2 => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("A.M(System.Action<double>)", "A.M(System.Action<long>)").WithLocation(17, 22), // (19,13): warning CS0168: The variable 'x2' is declared but never used // int x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(19, 13) ); CreateCompilation(source).VerifyDiagnostics( // (11,22): error CS0121: The call is ambiguous between the following methods or properties: 'A.M(Action<double>)' and 'A.M(Action<long>)' // int y1 = M(x1 => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("A.M(System.Action<double>)", "A.M(System.Action<long>)").WithLocation(11, 22), // (9,13): warning CS0168: The variable 'x1' is declared but never used // int x1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(9, 13), // (17,22): error CS0121: The call is ambiguous between the following methods or properties: 'A.M(Action<double>)' and 'A.M(Action<long>)' // int y2 = M(x2 => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("A.M(System.Action<double>)", "A.M(System.Action<long>)").WithLocation(17, 22), // (19,13): warning CS0168: The variable 'x2' is declared but never used // int x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(19, 13) ); } [WorkItem(542039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542039")] [Fact] public void BindingOrderCollisions03() { var source = @"using System; class Outer { static void Main(string[] args) { } public static int M() { return 1; } class Inner { public static int M = 2; void F1() { int x1 = M; Action a = () => { int x2 = M(); }; } void F2() { Action a = () => { int x2 = M(); }; int x1 = M; } void F3() { int x1 = M(); Action a = () => { int x2 = M; }; } void F4() { Action a = () => { int x2 = M; }; int x1 = M(); } } }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(835569, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835569")] [Fact] public void CollisionWithSameWhenError() { var source = @" using System; using System.Reflection; class Program { static void Main() { Console.WriteLine(string.Join < Assembly(Environment.NewLine, Assembly.GetEntryAssembly().GetReferencedAssemblies())); } } "; CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "Assembly").WithArguments("System.Reflection.Assembly").WithLocation(9, 41) ); } [Fact(Skip = "https://roslyn.codeplex.com/workitem/450")] [WorkItem(879811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/879811")] public void Bug879811_1() { const string source = @" using static Static<string>; using static Static<int>; public static class Static<T> { public class Nested { public void M() { } } } class D { static void Main(string[] args) { var c = new Nested(); c.M(); } }"; CreateCompilation(source).VerifyDiagnostics( // (17,21): error CS0104: 'Nested' is an ambiguous reference between 'Static<int>.Nested' and 'Static<string>.Nested' // var c = new Nested(); Diagnostic(ErrorCode.ERR_AmbigContext, "Nested").WithArguments("Nested", "Static<int>.Nested", "Static<string>.Nested").WithLocation(17, 21)); } [Fact] [WorkItem(879811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/879811")] public void Bug879811_2() { const string source = @" using static Static<string>; using static Static<System.String>; public static class Static<T> { public class Nested { public void M() { } } } class D { static void Main() { var c = new Nested(); } }"; CreateCompilation(source).VerifyDiagnostics( // (3,7): warning CS0105: The using directive for 'Static<string>' appeared previously in this namespace // using Static<System.String>; Diagnostic(ErrorCode.WRN_DuplicateUsing, "Static<System.String>").WithArguments("Static<string>").WithLocation(3, 14), // (3,1): hidden CS8019: Unnecessary using directive. // using Static<System.String>; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static Static<System.String>;").WithLocation(3, 1)); } [Fact] [WorkItem(879811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/879811")] public void Bug879811_3() { const string source = @" using static Static<string>; public static class Static<T> { public class Nested { public void M() { } } } namespace N { using static Static<int>; class D { static void Main() { Static<int>.Nested c = new Nested(); } } }"; CreateCompilation(source).VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using Static<string>; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static Static<string>;").WithLocation(2, 1)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; // The way the specification describes, and the way the native compiler reports name // collision errors is inconsistent and confusing. In Roslyn we will implement // the following more rational behaviors: // // ------------------ // // These two error messages are to be reworded: // // CS0135: (ERR_NameIllegallyOverrides) // // Original: 'X' conflicts with the declaration 'C.X' // // New: A local, parameter or range variable named 'X' cannot be declared in this scope // because that name is used in an enclosing local scope to refer to 'C.X'. // // CS0136: (ERR_LocalIllegallyOverrides) // // Original: A local variable named 'X' cannot be declared in this scope // because it would give a different meaning to 'X', which is // already used in a 'parent or current' / 'child' // scope to denote something else // // New: A local or parameter named 'X' cannot be declared in this scope // because that name is used in an enclosing local scope to define // a local or parameter. // // Note now the error messages are now nicely parallel, and much more clear about // precisely which rule has been violated. // // The rules for what error to report in each name collision scenario are as follows: // // --------------------------- // // Errors for simple names being used to refer to a member in one place and a declared // entity in another: // // CS0135: (ERR_NameIllegallyOverrides) // A local, parameter or range variable cannot be named 'X' because // that name is used in an enclosing local scope to refer to 'C.X'. // // Reported *only* when there is a local variable, local constant, lambda parameter or range variable // that would change the meaning of a *simple name* in an *expression* in an enclosing declaration // space to refer to a member, namespace, type, type parameter etc. Report it on the *inner* usage, // never the "outer" usage. eg: // // class C { int x; void M() { int y = x; { int x = y; } } } // // --------------------------- // // Errors for a local being used before it is defined: // // CS0841: (ERR_VariableUsedBeforeDeclaration) // Cannot use local variable 'X' before it is declared // // Reported when a local variable is used before it is declared, and the offending // usage was probably not intended to refer to a field. eg: // // class C { void M() { int y = x; int x; } } // // CS0844: (ERR_VariableUsedBeforeDeclarationAndHidesField) // Cannot use local variable 'X' before it is declared. The // declaration of the local variable hides the field 'C.X'. // // Reported if the offending usage might have been intended to refer to a field, eg: // // class C { int x; void M() { int y = x; int x; } } // // --------------------------- // // Errors for two of the same identifier being used to declare two different // things in overlapping or identical declaration spaces: // // CS0100: (ERR_DuplicateParamName) // The parameter name 'x' is a duplicate // // Reported when one parameter list contains two identically-named parameters. Eg: // // void M(int x, int x) {} or (x, x)=>{} // // CS0128: (ERR_LocalDuplicate) // A local variable named 'x' is already defined in this scope // // Reported *only* when there are two local variables or constants defined in the // *exact* same declaration space with the same name. eg: // // void M() { int x; int x; } // // CS0136: (ERR_LocalIllegallyOverrides) // New: A local or parameter named 'X' cannot be declared in this scope // because that name is used in an enclosing local scope to define // a local or parameter. // // Reported *only* when there is a local variable, local constant or lambda parameter // but NOT range variable that shadows a local variable, local constant, formal parameter, // range variable, or lambda parameter that was declared in an enclosing local declaration space. Again, // report it on the inner usage. eg: // // void M() { int y; { int y; } } // // CS0412: (ERR_LocalSameNameAsTypeParam) // 'X': a parameter or local variable cannot have the same name as a method type parameter // // Reported *only* when a local variable, local constant, formal parameter or lambda parameter // has the same name as a method type parameter. eg: // // void M<X>(){ int X; } // // CS1948: (ERR_QueryRangeVariableSameAsTypeParam) // The range variable 'X' cannot have the same name as a method type parameter // // Reported *only* when a range variable has the same name as a method type parameter. eg: // // void M<X>(){ var q = from X in z select X; } // // CS1930: (ERR_QueryDuplicateRangeVariable) // The range variable 'x' has already been declared // // Reported *only* if a range variable shadows another range variable that is in scope. eg: // // from x in y from x in z select q // // CS1931: (ERR_QueryRangeVariableOverrides) // The range variable 'x' conflicts with a previous declaration of 'x' // // Reported when there is a range variable that shadows a non-range variable from an // enclosing scope. eg: // // int x; var y = from x in q select m; // namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class NameCollisionTests : CompilingTestBase { [Fact] public void TestNamesFromTypeAndExpressionContextsDontCollide() { var source = @" using name1 = System.Exception; namespace Namespace { using name3 = System.Type; class Class { Class(name2 other1, name1 other2) { name3 other3 = typeof(name1); if (typeof(name1) != typeof(name2) || typeof(name2) is name3 || typeof(name1) is name3) { foreach (var name1 in ""string"") { for (var name2 = 1; name2 > --name2; name2++) { int name3 = name2; } } } else { name2 name1 = null, name2 = name1; name3 name3 = typeof(name2); } } } } class name2 { }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestLocalAndLabelDontCollide() { var source = @" using System; namespace Namespace { using name1 = System.Type; class Class { Class(name1 name1) { goto name2; name2: Console.WriteLine(); var name2 = new name2(); goto name1; name1: Console.WriteLine(); } } } class name2 { }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLabelWithLabel() { var source = @" using System; namespace Namespace { using name1 = System.Type; class Class { Class(name1 name1) { goto name1; name1: Console.WriteLine(); { goto name1; name1: Console.WriteLine(); var name2 = new name2(); goto name2; name2: Console.WriteLine(); } goto name2; name2: Console.WriteLine(); } internal int Property { set { goto name1; name1: Console.WriteLine(); Action lambda1 = () => { Action lambda2 = () => { goto name1; name1: Console.WriteLine(); var name2 = new name2(); goto name2; name2: Console.WriteLine(); }; goto name2; name2: Console.WriteLine(); }; } } } } class name2 { }"; CreateCompilation(source).VerifyDiagnostics( // (14,13): error CS0158: The label 'name1' shadows another label by the same name in a contained scope // name1: Console.WriteLine(); Diagnostic(ErrorCode.ERR_LabelShadow, "name1").WithArguments("name1"), // (17,13): error CS0158: The label 'name2' shadows another label by the same name in a contained scope // name2: Console.WriteLine(); Diagnostic(ErrorCode.ERR_LabelShadow, "name2").WithArguments("name2"), // (34,21): error CS0158: The label 'name1' shadows another label by the same name in a contained scope // name1: Console.WriteLine(); Diagnostic(ErrorCode.ERR_LabelShadow, "name1").WithArguments("name1"), // (37,21): error CS0158: The label 'name2' shadows another label by the same name in a contained scope // name2: Console.WriteLine(); Diagnostic(ErrorCode.ERR_LabelShadow, "name2").WithArguments("name2")); } [Fact] public void TestCollisionOfLocalWithTypeOrMethodOrProperty_LegalCases() { var source = @" using System; namespace name1 { class Class { void name1() { { name1(); } { int name1 = name1 = 1; } foreach(var name1 in ""string"") ; } } } class name2 { Action lambda = () => { { int name2 = name2 = 2; Console.WriteLine(name3); } { int name3 = name3 = 3; } }; static int name3 { get { return 4; } } }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithType() { var source = @" using name1 = System.Console; class Class { Class() { { name1.WriteLine(); // Legal name2.Equals(null, null); // Legal } { int name1 = (name1 = 1), name2 = name2 = 2; // Legal -- strange, but legal } { name1.WriteLine(); name2.Equals(null, null); { int name1 = 3, name2 = name1; // 0135 on name1, name2 // Native compiler reports 0136 here; Roslyn reports 0135. } } } } class name2 { }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithMethodOrProperty() { var source = @" using System; namespace name1 { class Class { void name1() { name1(); { name1(); } { int name1 = name1 = 1; // 0135: Roslyn reports 0135, native reports 0136. } foreach (var name1 in ""string"") ; // 0135: Roslyn reports 0135, native reports 0136. } Action lambda = () => { { int name2 = name2 = 2; // 0135: conflicts with usage of name2 as the static property below. // Roslyn reports this here; native compiler reports it below. Console.WriteLine(name2); } Console.WriteLine(name2); // Native compiler reports 0135 here; Roslyn reports it above. }; static int name2 { get { return 3; } } } }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(542039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542039")] [Fact] public void TestCollisionOfDelegateWithConst() { var source = @"class A { delegate void D(); static void Goo() { } class B { const int Goo = 123; static void Main() { Goo(); Bar(Goo); } static void Main2() { Bar(Goo); Goo(); } static void Bar(int x) { } static void Bar(D x) { } } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithTypeParameter() { var source = @" class Class<name1, name2> { void Method<name3, name4>(name1 other1, name4 name4) // 0412 on name4 { { int name3 = 10; // 0412 on name3 System.Console.WriteLine(name3); // Eliminate warning foreach (var name2 in ""string"") { for (var name1 = 1; name1 <= name1++; name1++) // legal; name1 conflicts with a class type parameter which is not in the local variable decl space name1 = name2.GetHashCode(); } } { name1 other2 = typeof(name1) is name1 ? other1 : other1; // no error; all the name1's refer to the type, not the local. int name1 = (name1 = 2), name2 = name2 = 3; // legal; name1 conflicts with a class type parameter which is not in the local variable decl space foreach (var name3 in ""string"") // 0412 on name3 { System.Console.WriteLine(name3); // Eliminate warning for (var name4 = 4; ; ) // 0412 on name4 { name1 = name2.GetHashCode(); System.Console.WriteLine(name4); // Eliminate warning } } try {} catch(System.Exception name3) // 0412 on name3 { System.Console.WriteLine(name3); } } } }"; CreateCompilation(source).VerifyDiagnostics( // (4,51): error CS0412: 'name4': a parameter or local variable cannot have the same name as a method type parameter // void Method<name3, name4>(name1 other1, name4 name4) // 0412 on name4 Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "name4").WithArguments("name4").WithLocation(4, 51), // (7,17): error CS0412: 'name3': a parameter or local variable cannot have the same name as a method type parameter // int name3 = 10; // 0412 on name3 Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "name3").WithArguments("name3").WithLocation(7, 17), // (18,26): error CS0412: 'name3': a parameter or local variable cannot have the same name as a method type parameter // foreach (var name3 in "string") // 0412 on name3 Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "name3").WithArguments("name3").WithLocation(18, 26), // (21,26): error CS0136: A local or parameter named 'name4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // for (var name4 = 4; ; ) // 0412 on name4 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name4").WithArguments("name4"), // (28,36): error CS0412: 'name3': a parameter or local variable cannot have the same name as a method type parameter // catch(System.Exception name3) // 0412 on name3 Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "name3").WithArguments("name3")); } [Fact] public void TestCollisionOfLocalWithField_LegalCases() { var source = @" partial class Derived : Base { private Derived() { this.name1 = 1; long name1 = this.name1; if (true) { name1 = this.name1 = name1; name2 = this.name2 = name2 + name1; } { while (name1 == 1) { long name2 = 2; name1 = name2; } do { long name2 = 3; name1 = name2; name1 = this.name1; } while (name1 != 1); } } } class Base { public long name2 = name1; private static int name1 = 4; } partial class Derived { internal long name1 = 5; }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithField1() { var source = @" class Derived : Base { static long name1 = 1; static Derived() { while(name1 == 2) { int name1 = 3, other = name1, name2 = other; // 0135 on name1 and name2 // Native reports 0136 on name1 here and 0135 on name2 below. } do { } while (name2 == 4); // Native reports 0135 on name2 here; Roslyn reports it above. } } class Base { protected static long name2 = 5; }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithField2() { var source = @" class Class { public static int M() { return 1; } internal int Property { set { for (int i = 0; i < int.MaxValue; ++i) { if (i == 0) { int other = M(), name = M(), name = other; // 0128, 0135 } else { { int name = M(); name = M(); // 0135 } } } for (int i = 0; i > int.MinValue; ++i) { { i += 1; } } name = M(); } } private const int x = 123; private void M1(int x = x) {} // UNDONE: Native and Roslyn compilers both allow this; should they? private void M2(int y = x) { int x = M(); // UNDONE: Native and Roslyn compilers both allow this; should they? } private long other = 0, name = 6; }"; CreateCompilation(source).VerifyDiagnostics( // (13,50): error CS0128: A local variable named 'name' is already defined in this scope // int other = M(), name = M(), name = other; // 0128, 0135 Diagnostic(ErrorCode.ERR_LocalDuplicate, "name").WithArguments("name"), // (37,18): warning CS0414: The field 'Class.other' is assigned but its value is never used // private long other = 0, name = 6; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "other").WithArguments("Class.other") ); } [Fact] public void TestCollisionInsideFieldDeclaration() { // A close reading of the spec would indicate that this is not an error because the // offending simple name 'x' does not appear in any local variable declaration space. // A field initializer is not a declaration space. However, it seems plausible // that we want to report the error here. The native compiler does so as well. var source = @" class Class { private static int M() { return 1; } private static int x = 123; private static int z = x + ((System.Func<int>)( ()=>{ int x = M(); return x; } ))(); }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithField_PartialType() { var source = @" partial struct PartialStruct { private void Method() { if (true) { { int name = 1, other = name; } } name = 2; // Native compiler reports 0135 here; Roslyn no longer reports 0135. } } partial struct PartialStruct { internal long name; }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithLocal_LegalCases1() { var source = @" partial class Derived : Base { private string Property { get { if (true) { int name = (name = 1); name += name; } { { int name = 2; name -= name; } } for(long name = 3; name <= 4; ++name) name += 5; foreach(var name in ""string"") { name.ToString(); } return this.name; } } } class Base { public string name = null; }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithLocal_LegalCases2() { var source = @" using System; using System.Linq; partial class Derived : Base { private string Property { get { // http://blogs.msdn.com/b/ericlippert/archive/2009/11/02/simple-names-are-not-so-simple.aspx foreach (var name in from name in ""string"" orderby name select name) Console.WriteLine(name); return this.name; } } } class Base { public string name = null; }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithLocal_LegalCases3() { var source = @" using System; using System.Linq; partial class Derived : Base { private string Property { get { // http://blogs.msdn.com/b/ericlippert/archive/2009/11/02/simple-names-are-not-so-simple.aspx foreach(var name in ""string"".OrderBy(name => name).Select(name => name)) { Console.WriteLine(name); } return this.name; } } } class Base { public string name = null; }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithLocal() { var source = @" class Class { public Class() { long name1 = 1; System.Console.WriteLine(name1); // Eliminate unused warning. name4 = name6; // 0841 on name4; used before declared. 0103 on name6; not defined in this context if (true) { { int other1 = 2, name1 = other1, name2 = name1; // 0136 on name1; already used in parent scope to mean something else. } // Native compiler reports 0136 on 'long name2' below; Roslyn reports it on 'int ... name2' here and 'var name2' below { if (true) { for (long name1 = this.name2; name1 >= --name1; name1++) // 0136 on name1; { name1.ToString(); name5.ToString(); // 0841: name5 is used before the declaration string name6 = ""string""; } } foreach (var name2 in ""string"") name2.ToString(); // 0136: Native reports this on 'long name2' below; Roslyn reports it here, and above. } string @name3 = ""string"", other2 = name3, name3 = other2; // 0128: name3 is defined twice. long @name2 = 3; System.Console.WriteLine(@name2); // eliminated unused warning. // Native compiler reports 0136 on 'long name2' here; Roslyn reports it on 'int ... name2' above. } string name4 = ""string"", name5 = name4; name6 = name3; // 0103 on both name6 and name3; not defined in this context. } public long name2 = 4; }"; CreateCompilation(source).VerifyDiagnostics( // (7,9): error CS0841: Cannot use local variable 'name4' before it is declared // name4 = name6; // 0841 on name4; used before declared. 0103 on name6; not defined in this context Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "name4").WithArguments("name4").WithLocation(7, 9), // (7,17): error CS0103: The name 'name6' does not exist in the current context // name4 = name6; // 0841 on name4; used before declared. 0103 on name6; not defined in this context Diagnostic(ErrorCode.ERR_NameNotInContext, "name6").WithArguments("name6").WithLocation(7, 17), // (11,33): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int other1 = 2, name1 = other1, name2 = name1; // 0136 on name1; already used in parent scope to mean something else. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(11, 33), // (11,49): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int other1 = 2, name1 = other1, name2 = name1; // 0136 on name1; already used in parent scope to mean something else. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(11, 49), // (16,31): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // for (long name1 = this.name2; name1 >= --name1; name1++) // 0136 on name1; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(16, 31), // (18,43): error CS0841: Cannot use local variable 'name5' before it is declared // name1.ToString(); name5.ToString(); // 0841: name5 is used before the declaration Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "name5").WithArguments("name5").WithLocation(18, 43), // (22,30): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name2 in "string") name2.ToString(); // 0136: Native reports this on 'long name2' below; Roslyn reports it here, and above. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(22, 30), // (24,55): error CS0128: A local variable named 'name3' is already defined in this scope // string @name3 = "string", other2 = name3, name3 = other2; // 0128: name3 is defined twice. Diagnostic(ErrorCode.ERR_LocalDuplicate, "name3").WithArguments("name3").WithLocation(24, 55), // (29,9): error CS0103: The name 'name6' does not exist in the current context // name6 = name3; // 0103 on both name6 and name3; not defined in this context. Diagnostic(ErrorCode.ERR_NameNotInContext, "name6").WithArguments("name6").WithLocation(29, 9), // (29,17): error CS0103: The name 'name3' does not exist in the current context // name6 = name3; // 0103 on both name6 and name3; not defined in this context. Diagnostic(ErrorCode.ERR_NameNotInContext, "name3").WithArguments("name3").WithLocation(29, 17), // (19,32): warning CS0219: The variable 'name6' is assigned but its value is never used // string name6 = "string"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "name6").WithArguments("name6").WithLocation(19, 32) ); } [Fact] public void TestCollisionOfLocalWithParam() { var source = @" using System; class Class { public Func<int, int, int> Method(int name1, int name2) { foreach (var name1 in ""string"") // 0136 { foreach (var name2 in ""string"") // 0136 { int name1 = name2.GetHashCode(); // 0136 } } Action<int> lambda = (name3) => { int name1 = 1; // 0136 if(name1 == 2) { name2 = name3 = name1; } else { int name2 = 3; // 0136 System.Console.WriteLine(name2); { int name3 = 2; // 0136 System.Console.WriteLine(name3); } } }; return (name1, name2) => name1; // 0136 on both name1 and name2 } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,22): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name1 in "string") // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(7, 22), // (9,26): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name2 in "string") // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(9, 26), // (11,21): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name1 = name2.GetHashCode(); // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(11, 21), // (17,17): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name1 = 1; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(17, 17), // (24,21): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name2 = 3; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(24, 21), // (27,25): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name3 = 2; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(27, 25), // (32,17): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // return (name1, name2) => name1; // 0136 on both name1 and name2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(32, 17), // (32,24): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // return (name1, name2) => name1; // 0136 on both name1 and name2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(32, 24) ); CreateCompilation(source).VerifyDiagnostics( // (7,22): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name1 in "string") // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(7, 22), // (9,26): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name2 in "string") // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(9, 26), // (11,21): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name1 = name2.GetHashCode(); // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(11, 21), // (27,25): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name3 = 2; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(27, 25) ); } [Fact] public void TestCollisionOfParamWithParam() { var source = @" using System; class Class { public static void Method(int name1, int name2, int name2) // 0100 on name2 { Action<int, int> lambda = (other, name3) => { Action<int, int, int, int> nestedLambda = (name1, name4, name4, name3) => // 0100 on name4, 0136 on name1 and name3 { }; }; } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (5,57): error CS0100: The parameter name 'name2' is a duplicate // public static void Method(int name1, int name2, int name2) // 0100 on name2 Diagnostic(ErrorCode.ERR_DuplicateParamName, "name2").WithArguments("name2").WithLocation(5, 57), // (9,56): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action<int, int, int, int> nestedLambda = (name1, name4, name4, name3) => // 0100 on name4, 0136 on name1 and name3 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(9, 56), // (9,70): error CS0100: The parameter name 'name4' is a duplicate // Action<int, int, int, int> nestedLambda = (name1, name4, name4, name3) => // 0100 on name4, 0136 on name1 and name3 Diagnostic(ErrorCode.ERR_DuplicateParamName, "name4").WithArguments("name4").WithLocation(9, 70), // (9,77): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action<int, int, int, int> nestedLambda = (name1, name4, name4, name3) => // 0100 on name4, 0136 on name1 and name3 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(9, 77) ); CreateCompilation(source).VerifyDiagnostics( // (5,57): error CS0100: The parameter name 'name2' is a duplicate // public static void Method(int name1, int name2, int name2) // 0100 on name2 Diagnostic(ErrorCode.ERR_DuplicateParamName, "name2").WithArguments("name2").WithLocation(5, 57), // (9,70): error CS0100: The parameter name 'name4' is a duplicate // Action<int, int, int, int> nestedLambda = (name1, name4, name4, name3) => // 0100 on name4, 0136 on name1 and name3 Diagnostic(ErrorCode.ERR_DuplicateParamName, "name4").WithArguments("name4").WithLocation(9, 70) ); } [WorkItem(930252, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930252")] [Fact] public void TestCollisionOfParamWithParam1() { var source = @" class Program { delegate int D(int x, int y); static void X() { D d1 = (int x, int x) => { return 1; }; D d2 = (x, x) => { return 1; }; } }"; CreateCompilation(source).VerifyDiagnostics( // (7,28): error CS0100: The parameter name 'x' is a duplicate // D d1 = (int x, int x) => { return 1; }; Diagnostic(ErrorCode.ERR_DuplicateParamName, "x").WithArguments("x").WithLocation(7, 28), // (8,20): error CS0100: The parameter name 'x' is a duplicate // D d2 = (x, x) => { return 1; }; Diagnostic(ErrorCode.ERR_DuplicateParamName, "x").WithArguments("x").WithLocation(8, 20) ); } [Fact] public void TestCollisionInsideLambda_LegalCases() { var source = @" using System; partial class Class { private string Property { set { this. Method((name1) => { name1 = string.Empty; for (int name2 = name2 = 1; ; ) ; }). Method((name1) => name1.ToString()). Method((name1) => { foreach (var name2 in string.Empty) ; return name1; }); } } Class Method(Action<string> name1) { return null; } Class Method(Func<string, string> name1) { return null; } }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionInsideLambda1() { var source = @" using System; class Derived : Base { static int M() { return 1; } static long name1 = 1; Action lambda = () => { name1 = 2; { int name1 = 3, other = name1, name2 = other; // 0135: on name1 and name2. // Native compiler reports 0136 here on name1 and 0135 on name2 below. // Roslyn reports them both as 0135 here. } name2 = 4; // Native compiler reports 0135 here; Roslyn reports above. int name3 = M(); { { name3 = 6; } if (true) { int name3 = M(); // 0136: Native compiler says 0135, Roslyn says 0136. The conflict is with the other local. } } }; Action anonMethod = delegate() { name1 = 8; if (true) { int name1 = 9, other = name1, name2 = other; // 0135: on name1, name2 // Native compiler reports 0136 on name1, Roslyn reports 0135. // Native compiler reports 0135 on name2 below, Roslyn reports it here. } { foreach (var name3 in ""string"") name3.ToString(); // 0136: Native compiler reports 0136 below, Roslyn reports it here. } name2 = 10; // Native compiler reports 0135 here; Roslyn reports it above. int name3 = M(); }; } class Base { protected static long name2 = 12; }"; CreateCompilation(source).VerifyDiagnostics( // (24,21): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name3 = M(); // 0136: Native compiler says 0135, Roslyn says 0136. The conflict is with the other local. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(24, 21), // (39,26): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name3 in "string") name3.ToString(); // 0136: Native compiler reports 0136 below, Roslyn reports it here. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(39, 26), // (6,17): warning CS0414: The field 'Derived.name1' is assigned but its value is never used // static long name1 = 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "name1").WithArguments("Derived.name1").WithLocation(6, 17) ); } [Fact] public void TestCollisionInsideLambda2() { var source = @" using System; class Class { void Method(Action lambda) { } void Method() { const long name1 = 1; System.Console.WriteLine(name1); // Eliminate warning. Method(() => { Console.WriteLine(name1); { const int name1 = 2; // 0136 int other = name1, name2 = other; // 0136: Native compiler reports this on 'const long name' below; Roslyn reports it here. } name2 = 3; // 0841: local used before declared const int name3 = 4; { { Console.WriteLine(name3); } if (true) { const int name3 = 5; // 0136 Console.WriteLine(name3); } } }); Method(delegate() { Console.WriteLine(name1); if (true) { const int name1 = 6, other = name1, name2 = other; // 0136 on name1 and name2 Console.WriteLine(name1 + other + name2); } // Roslyn reports 0136 on name2 above; native compiler reports it on 'const long name2' below. { foreach (var name3 in ""string"") name3.ToString(); // 0136: Roslyn reports this here, native reports it below. } Console.WriteLine(name2); // 0814: local used before declared const int name3 = 7; // Native compiler reports 0136 here, Roslyn reports it on 'var name3' above. Console.WriteLine(name3); // eliminate warning }); const long name2 = 8; // Native compiler reports 0136 here; Roslyn reports it on both offending nested decls above. Console.WriteLine(name2); } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (15,27): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // const int name1 = 2; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(15, 27), // (16,36): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int other = name1, name2 = other; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(16, 36), // (18,13): error CS0841: Cannot use local variable 'name2' before it is declared // name2 = 3; // 0841: local used before declared Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "name2").WithArguments("name2").WithLocation(18, 13), // (27,31): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // const int name3 = 5; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(27, 31), // (38,27): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // const int name1 = 6, other = name1, name2 = other; // 0136 on name1 and name2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(38, 27), // (38,53): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // const int name1 = 6, other = name1, name2 = other; // 0136 on name1 and name2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(38, 53), // (42,30): error CS0841: Cannot use local variable 'name3' before it is declared // foreach (var name3 in ""string"") name3.ToString(); // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(42, 30), // (44,31): error CS0841: Cannot use local variable 'name2' before it is declared // Console.WriteLine(name2); // 0814: local used before declared Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "name2").WithArguments("name2").WithLocation(44, 31)); CreateCompilation(source).VerifyDiagnostics( // (18,13): error CS0841: Cannot use local variable 'name2' before it is declared // name2 = 3; // 0841: local used before declared Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "name2").WithArguments("name2").WithLocation(18, 13), // (27,31): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // const int name3 = 5; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(27, 31), // (42,30): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name3 in "string") name3.ToString(); // 0136: Roslyn reports this here, native reports it below. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(42, 30), // (44,31): error CS0841: Cannot use local variable 'name2' before it is declared // Console.WriteLine(name2); // 0814: local used before declared Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "name2").WithArguments("name2").WithLocation(44, 31)); } [Fact] public void TestCollisionInsideOperator() { var source = @" using System; class Class { static long name1 = 1; public static Class operator +(Class name1, Class other) { var lambda = (Action)(() => { const int name1 = @name2; // 0136 on name1 because it conflicts with parameter if (true) { int name2 = name1; // 0135 because name2 conflicts with usage of name2 as Class.name2 above Console.WriteLine(name2); } }); return other; } const int name2 = 2; public static void Other() { Console.WriteLine(name1); } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (10,23): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // const int name1 = @name2; // 0136 on name1 because it conflicts with parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(10, 23)); CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionInsideIndexer() { var source = @" class Class { static long name1 = 1; public int this[int name1] { get { foreach (var name2 in ""string"") { foreach (var name2 in ""string"") // 0136 on name2 { int name1 = name2.GetHashCode(); // 0136 on name1 } } return name1; } } static long name2 = name1 + name2; }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (11,30): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name2 in "string") // 0136 on name2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2"), // (13,25): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name1 = name2.GetHashCode(); // 0136 on name1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1")); } [Fact] public void TestCollisionInsideFor1() { var source = @" class Class { void Method1(int name4 = 1, params int[] name5) { for (int name1 = 2; name1 <= name1++; ++name1) { foreach (var name2 in ""string"") { for (name1 = 3; ; ) { break; } for (int name2 = name1; name2 <= name2++; ++name2) // 0136 on name2 { int name3 = 4, name4 = 5, name5 = 6; // 0136 on name3, name4 and name5 // Native compiler reports 0136 on name3 below, Roslyn reports it above. System.Console.WriteLine(name3 + name4 + name5); // Eliminate warning } } foreach (var name1 in ""string"") ; // 0136 on name1 } int name3 = 7; // Native compiler reports 0136 on name3 here; Roslyn reports it above. System.Console.WriteLine(name3); // Eliminate warning } }"; CreateCompilation(source).VerifyDiagnostics( // (11,26): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // for (int name2 = name1; name2 <= name2++; ++name2) // 0136 on name2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(11, 26), // (13,25): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name3 = 4, name4 = 5, name5 = 6; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(13, 25), // (13,36): error CS0136: A local or parameter named 'name4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name3 = 4, name4 = 5, name5 = 6; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name4").WithArguments("name4").WithLocation(13, 36), // (13,47): error CS0136: A local or parameter named 'name5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name3 = 4, name4 = 5, name5 = 6; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name5").WithArguments("name5").WithLocation(13, 47), // (13,47): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name1 in ""string"") ; // 0136 on name1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(18, 26)); } [Fact] public void TestCollisionInsideFor2() { var source = @" using System.Linq; using System.Collections; partial class Class { private string Property { get { for (var name = from name in ""string"" orderby name select name; name != null; ) ; // 1931 for (IEnumerable name = null; name == from name in ""string"" orderby name select name; ) ; // 1931 for (IEnumerable name = null; name == null; name = from name in ""string"" orderby name select name ) ; // 1931 return string.Empty; } } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (11,51): warning CS8848: Operator 'from' cannot be used here due to precedence. Use parentheses to disambiguate. // for (IEnumerable name = null; name == from name in "string" orderby name select name; ) ; // 1931 Diagnostic(ErrorCode.WRN_PrecedenceInversion, @"from name in ""string""").WithArguments("from").WithLocation(11, 51), // (10,34): error CS1931: The range variable 'name' conflicts with a previous declaration of 'name' // for (var name = from name in "string" orderby name select name; name != null; ) ; // 1931 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "name").WithArguments("name").WithLocation(10, 34), // (11,56): error CS1931: The range variable 'name' conflicts with a previous declaration of 'name' // for (IEnumerable name = null; name == from name in "string" orderby name select name; ) ; // 1931 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "name").WithArguments("name").WithLocation(11, 56), // (12,69): error CS1931: The range variable 'name' conflicts with a previous declaration of 'name' // for (IEnumerable name = null; name == null; name = from name in "string" orderby name select name ) ; // 1931 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "name").WithArguments("name").WithLocation(12, 69)); } [WorkItem(792744, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792744")] [Fact] public void TestCollisionInsideForeach() { var source = @" class Class { static int y = 1; static void Main(string[] args) { foreach (var y in new[] {new { y = y }}){ } //End } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(); } [Fact] public void TestCollisionInsideUsing() { var source = @" class Class : System.IDisposable { public void Dispose() {} int[] name3 = {}; void Method1(Class name2 = null) { using (var name1 = new Class()) { int other = (name3[0]); } using (var name1 = new Class()) { var other = name3[0].ToString(); using (var name3 = new Class()) // 0135 because name3 above refers to this.name3 { int name1 = 2; // 0136 on name1 } } using (var name2 = new Class()) // 0136 on name2. { int name1 = 2; int other = (name3[0]); } using (name2 = new Class()) { int name1 = 2; int other = (name3[0]); } } }"; CreateCompilation(source).VerifyDiagnostics( // (17,21): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name1 = 2; // 0136 on name1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(17, 21), // (17,21): warning CS0219: The variable 'name1' is assigned but its value is never used // int name1 = 2; // 0136 on name1 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "name1").WithArguments("name1").WithLocation(17, 21), // (20,20): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (var name2 = new Class()) // 0136 on name2. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(20, 20), // (22,17): warning CS0219: The variable 'name1' is assigned but its value is never used // int name1 = 2; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "name1").WithArguments("name1").WithLocation(22, 17), // (27,17): warning CS0219: The variable 'name1' is assigned but its value is never used // int name1 = 2; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "name1").WithArguments("name1").WithLocation(27, 17) ); } [Fact] public void TestCollisionInsideLock() { var source = @" using System; class Class { const int[] name = null; void Method1() { lock (name) { } { lock (string.Empty) { const int name = 0; // 0135 because name above means 'this.name'. Console.WriteLine(name); } } } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionInsideSwitch() { var source = @" class Class { int M() { return 1; } int name1 = 1; void Method1() { switch (name1) { case name1: break; // 0844: use of 'int name1' below before it is declared -- surprising error, but correct. Also notes that local name1 hides field. case 2: int name1 = 2; // 0135: because 'name1' above means 'this.name1'. Native compiler reports 0136, Roslyn reports 0135. var name2 = 3; System.Console.WriteLine(name1 + name2); break; case 3: name2 = M(); // Not a use-before-declaration error; name2 is defined above var name2 = M(); // 0128 on name2; switch sections share the same declaration space for (int name3 = 5; ; ) { System.Console.WriteLine(name2 + name3); break; } int name4 = 6; System.Console.WriteLine(name4); break; case 4: name1 = 2; for (int name3 = 7; ; ) { System.Console.WriteLine(name3); break; } switch (name1) { case 1: int name4 = 8, name5 = 9; // 0136 on name4, name5 // Native compiler reports error 0136 on `name5 = 11` below; Roslyn reports it here. System.Console.WriteLine(name4 + name5); break; } for (int name6 = 10; ; ) // 0136 on name6; Native compiler reports 0136 on name6 below. { System.Console.WriteLine(name6);} default: int name5 = 11, name6 = 12; // Native compiler reports 0136 on name5 and name6. Roslyn reports them above. System.Console.WriteLine(name5 + name6); break; } } }"; CreateCompilation(source).VerifyDiagnostics( // (10,18): error CS0844: Cannot use local variable 'name1' before it is declared. The declaration of the local variable hides the field 'Class.name1'. // case name1: break; // 0844: use of 'int name1' below before it is declared -- surprising error, but correct. Also notes that local name1 hides field. Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclarationAndHidesField, "name1").WithArguments("name1", "Class.name1").WithLocation(10, 18), // (18,21): error CS0128: A local variable named 'name2' is already defined in this scope // var name2 = M(); // 0128 on name2; switch sections share the same declaration space Diagnostic(ErrorCode.ERR_LocalDuplicate, "name2").WithArguments("name2").WithLocation(18, 21), // (31,29): error CS0136: A local or parameter named 'name4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name4 = 8, name5 = 9; // 0136 on name4, name5 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name4").WithArguments("name4").WithLocation(31, 29), // (31,40): error CS0136: A local or parameter named 'name5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name4 = 8, name5 = 9; // 0136 on name4, name5 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name5").WithArguments("name5").WithLocation(31, 40), // (36,26): error CS0136: A local or parameter named 'name6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // for (int name6 = 10; ; ) // 0136 on name6; Native compiler reports 0136 on name6 below. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name6").WithArguments("name6").WithLocation(36, 26) ); } [Fact] public void TestCollisionInsideTryCatch_LegalCases() { var source = @" using System; class Derived : Base { static long name1 = 1; static Derived() { { try { Console.WriteLine(name1); } catch (ArgumentException name1) { Console.WriteLine(name1.Message); } catch (Exception name1) { Console.WriteLine(name1.Message); } } { Console.WriteLine(name1); try { var name4 = string.Empty; try { name2 = 3; string name5 = string.Empty; name5.ToString(); name4.ToString(); } catch (Exception name2) { Console.WriteLine(name2.Message); string name5 = string.Empty; name5.ToString(); name4.ToString(); } } catch (Exception other) { var name4 = string.Empty; Console.WriteLine(name4.ToString()); name2 = 4; Console.WriteLine(other.Message); } } } } class Base { protected static long name2 = 5; }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionInsideTryCatch() { var source = @" using System; class Derived : Base { static long name1 = 1; static Derived() { { Console.WriteLine(name1); try { Console.WriteLine(name1); } catch (ArgumentException name1) { Console.WriteLine(name1.Message); } catch (Exception name2) { Console.WriteLine(name2.Message); } Console.WriteLine(name2); } { try { var name4 = string.Empty; Console.WriteLine(name1); } catch (Exception name1) { System.Console.WriteLine(name1.Message); var name5 = string.Empty; try { } catch (Exception name1) // 0136 on name1 { var name5 = string.Empty; // 0136 on name5 System.Console.WriteLine(name1.Message); } } var name4 = string.Empty; // Native reports 0136 here; } } } class Base { protected static long name2 = 2; }"; CreateCompilation(source).VerifyDiagnostics( // (27,21): error CS0136: A local or parameter named 'name4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var name4 = string.Empty; // 0136: Roslyn reports this here; native reports it below. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name4").WithArguments("name4").WithLocation(27, 21), // (38,34): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch (Exception name1) // 0136 on name1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(38, 34), // (40,25): error CS0136: A local or parameter named 'name5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var name5 = string.Empty; // 0136 on name5 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name5").WithArguments("name5").WithLocation(40, 25) ); } [Fact] public void DifferentArities() { var source = @" public class C<T> { public static U G<U>(U x) { return x; } void M() { int G = 10; G<int>(G); int C = 5; C<string>.G(C); } }"; CompileAndVerify(source).VerifyDiagnostics(); } [WorkItem(10556, "DevDiv_Projects/Roslyn")] [Fact] public void TestCollisionInsideQuery_LegalCases() { var source = @" using System.Linq; using System.Collections.Generic; partial class Class { private string Property { set { var other1 = from int name1 in ""string"" select name1; { var query1 = from name1 in ""string"" select name1; var query2 = from name1 in ""string"" select name1; this.Method(from name1 in ""string"" select name1).Method(from name1 in ""string"" select name1); } other1 = from int name1 in ""string"" select name2; { var query1 = from name1 in ""string"" let name2 = 1 select name1; var query2 = from name2 in ""string"" select name2; this.Method(from other2 in ""string"" from name2 in ""string"" select other2).Method(from name1 in ""string"" group name1 by name1 into name2 select name2); Method(from name1 in ""string"" group name1 by name1.ToString() into name1 select name1); } } } int name2 = 2; Class Method(IEnumerable<char> name1) { return null; } Class Method(object name1) { return null; } }"; CompileAndVerify(source).VerifyDiagnostics(); } [WorkItem(543045, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543045")] [Fact] public void TestCollisionInsideQuery() { var source = @" using System; using System.Linq; using System.Collections.Generic; partial class Class { private string Property { set { Console.WriteLine(name1); { var query1 = from name1 in string.Empty // 1931 -- UNDONE change to 0135 because name1 above refers to Class.name1 select name1; var query2 = from other in string.Empty let name1 = 1 // 1931 -- UNDONE change to 0135 because name1 above refers to Class.name1 select other; this.Method(from other in string.Empty from name1 in string.Empty // 1931 -- UNDONE change to 0135 because name1 above refers to Class.name1 select other).Method(from other in string.Empty group other by other.ToString() into name1 // 1931 -- UNDONE change to 0135 because name1 above refers to Class.name1 select name1); } { var query1 = from name2 in string.Empty let name2 = 2 // 1930 select name2; this.Method(from name2 in string.Empty from name2 in name1.ToString() // 1930 select name2); } } } int name1 = 3; Class Method(IEnumerable<char> name1) { return null; } Class Method(object name1) { return null; } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (26,34): error CS1930: The range variable 'name2' has already been declared // let name2 = 2 // 1930 Diagnostic(ErrorCode.ERR_QueryDuplicateRangeVariable, "name2").WithArguments("name2").WithLocation(26, 34), // (29,34): error CS1930: The range variable 'name2' has already been declared // from name2 in name1.ToString() // 1930 Diagnostic(ErrorCode.ERR_QueryDuplicateRangeVariable, "name2").WithArguments("name2").WithLocation(29, 34) ); } [Fact] public void TestCollisionInsideQuery_TypeParameter() { var source = @" using System.Linq; public class Class { void Method<T, U>() { { var q = from T in """" let U = T select T; } } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (7,26): error CS1948: The range variable 'T' cannot have the same name as a method type parameter // var q = from T in "" Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "T").WithArguments("T"), // (8,25): error CS1948: The range variable 'U' cannot have the same name as a method type parameter // let U = T Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "U").WithArguments("U")); } [WorkItem(542088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542088")] [Fact] public void LocalCollidesWithGenericType() { var source = @" public class C { public static int G<T>(int x) { return x; } public static void Main() { int G = 10; G<int>(G); } }"; CompileAndVerify(source).VerifyDiagnostics(); } [WorkItem(542039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542039")] [Fact] public void BindingOrderCollisions01() { var source = @"using System; class A { static long M(Action<long> act) { return 0; } static void What1() { int x1; { int y1 = M(x1 => { }); } } static void What2() { { int y2 = M(x2 => { }); } int x2; } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (10,24): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int y1 = M(x1 => { }); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(10, 24), // (10,22): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // int y1 = M(x1 => { }); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "M(x1 => { })").WithArguments("long", "int").WithLocation(10, 22), // (8,13): warning CS0168: The variable 'x1' is declared but never used // int x1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(8, 13), // (16,24): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int y2 = M(x2 => { }); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(16, 24), // (16,22): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // int y2 = M(x2 => { }); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "M(x2 => { })").WithArguments("long", "int").WithLocation(16, 22), // (18,13): warning CS0168: The variable 'x2' is declared but never used // int x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(18, 13) ); CreateCompilation(source).VerifyDiagnostics( // (10,22): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // int y1 = M(x1 => { }); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "M(x1 => { })").WithArguments("long", "int").WithLocation(10, 22), // (8,13): warning CS0168: The variable 'x1' is declared but never used // int x1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(8, 13), // (16,22): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // int y2 = M(x2 => { }); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "M(x2 => { })").WithArguments("long", "int").WithLocation(16, 22), // (18,13): warning CS0168: The variable 'x2' is declared but never used // int x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(18, 13) ); } [WorkItem(542039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542039")] [Fact] public void BindingOrderCollisions02() { var source = @"using System; class A { static double M(Action<double> act) { return 0; } static long M(Action<long> act) { return 0; } static void What1() { int x1; { int y1 = M(x1 => { }); } } static void What2() { { int y2 = M(x2 => { }); } int x2; } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (11,24): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int y1 = M(x1 => { }); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(11, 24), // (11,22): error CS0121: The call is ambiguous between the following methods or properties: 'A.M(Action<double>)' and 'A.M(Action<long>)' // int y1 = M(x1 => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("A.M(System.Action<double>)", "A.M(System.Action<long>)").WithLocation(11, 22), // (9,13): warning CS0168: The variable 'x1' is declared but never used // int x1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(9, 13), // (17,24): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int y2 = M(x2 => { }); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(17, 24), // (17,22): error CS0121: The call is ambiguous between the following methods or properties: 'A.M(Action<double>)' and 'A.M(Action<long>)' // int y2 = M(x2 => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("A.M(System.Action<double>)", "A.M(System.Action<long>)").WithLocation(17, 22), // (19,13): warning CS0168: The variable 'x2' is declared but never used // int x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(19, 13) ); CreateCompilation(source).VerifyDiagnostics( // (11,22): error CS0121: The call is ambiguous between the following methods or properties: 'A.M(Action<double>)' and 'A.M(Action<long>)' // int y1 = M(x1 => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("A.M(System.Action<double>)", "A.M(System.Action<long>)").WithLocation(11, 22), // (9,13): warning CS0168: The variable 'x1' is declared but never used // int x1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(9, 13), // (17,22): error CS0121: The call is ambiguous between the following methods or properties: 'A.M(Action<double>)' and 'A.M(Action<long>)' // int y2 = M(x2 => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("A.M(System.Action<double>)", "A.M(System.Action<long>)").WithLocation(17, 22), // (19,13): warning CS0168: The variable 'x2' is declared but never used // int x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(19, 13) ); } [WorkItem(542039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542039")] [Fact] public void BindingOrderCollisions03() { var source = @"using System; class Outer { static void Main(string[] args) { } public static int M() { return 1; } class Inner { public static int M = 2; void F1() { int x1 = M; Action a = () => { int x2 = M(); }; } void F2() { Action a = () => { int x2 = M(); }; int x1 = M; } void F3() { int x1 = M(); Action a = () => { int x2 = M; }; } void F4() { Action a = () => { int x2 = M; }; int x1 = M(); } } }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(835569, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835569")] [Fact] public void CollisionWithSameWhenError() { var source = @" using System; using System.Reflection; class Program { static void Main() { Console.WriteLine(string.Join < Assembly(Environment.NewLine, Assembly.GetEntryAssembly().GetReferencedAssemblies())); } } "; CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "Assembly").WithArguments("System.Reflection.Assembly").WithLocation(9, 41) ); } [Fact(Skip = "https://roslyn.codeplex.com/workitem/450")] [WorkItem(879811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/879811")] public void Bug879811_1() { const string source = @" using static Static<string>; using static Static<int>; public static class Static<T> { public class Nested { public void M() { } } } class D { static void Main(string[] args) { var c = new Nested(); c.M(); } }"; CreateCompilation(source).VerifyDiagnostics( // (17,21): error CS0104: 'Nested' is an ambiguous reference between 'Static<int>.Nested' and 'Static<string>.Nested' // var c = new Nested(); Diagnostic(ErrorCode.ERR_AmbigContext, "Nested").WithArguments("Nested", "Static<int>.Nested", "Static<string>.Nested").WithLocation(17, 21)); } [Fact] [WorkItem(879811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/879811")] public void Bug879811_2() { const string source = @" using static Static<string>; using static Static<System.String>; public static class Static<T> { public class Nested { public void M() { } } } class D { static void Main() { var c = new Nested(); } }"; CreateCompilation(source).VerifyDiagnostics( // (3,7): warning CS0105: The using directive for 'Static<string>' appeared previously in this namespace // using Static<System.String>; Diagnostic(ErrorCode.WRN_DuplicateUsing, "Static<System.String>").WithArguments("Static<string>").WithLocation(3, 14), // (3,1): hidden CS8019: Unnecessary using directive. // using Static<System.String>; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static Static<System.String>;").WithLocation(3, 1)); } [Fact] [WorkItem(879811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/879811")] public void Bug879811_3() { const string source = @" using static Static<string>; public static class Static<T> { public class Nested { public void M() { } } } namespace N { using static Static<int>; class D { static void Main() { Static<int>.Nested c = new Nested(); } } }"; CreateCompilation(source).VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using Static<string>; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static Static<string>;").WithLocation(2, 1)); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/EditorFeatures/VisualBasicTest/Recommendations/Expressions/BinaryOperatorKeywordRecommenderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Expressions Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Expressions Public Class BinaryOperatorKeywordRecommenderTests Inherits RecommenderTests Private Shared ReadOnly s_expectedKeywords As String() = BinaryOperatorKeywordRecommender.KeywordList.Select(Function(k) k.Keyword).ToArray() <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInClassDeclarationTest() VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInMethodDeclarationTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterLocalDeclarationNumericLiteralInitializerTest() VerifyRecommendationsContain(<MethodBody>Dim i As Integer = 1 |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterNumberInAssignmentTest() VerifyRecommendationsContain(<MethodBody>x = 1 |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterStringInAssignmentTest() VerifyRecommendationsContain(<MethodBody>x = "asdf" |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterObjectCreationInAssignmentTest() VerifyRecommendationsContain(<MethodBody>x = New Object() |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterObjectCreationInDeclarationTest() VerifyRecommendationsMissing(<MethodBody>Dim x = New Object |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterObjectCreationWithParensInDeclarationTest() VerifyRecommendationsMissing(<MethodBody>Dim x = New Object() |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterAsNewInDeclarationTest() VerifyRecommendationsMissing(<MethodBody>Dim x As New Object |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterAsNewWithParensInDeclarationTest() VerifyRecommendationsMissing(<MethodBody>Dim x As New Object() |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterMethodCallInAsNewClauseTest() VerifyRecommendationsContain(<MethodBody>Dim x As New Object(Goo() |)</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterPropertyAccessInAssignmentTest() VerifyRecommendationsContain(<MethodBody>x = Goo.Bar |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterMethodCallInAssignmentTest() VerifyRecommendationsContain(<MethodBody>x = Goo.Bar() |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterDotInImportsTest() VerifyRecommendationsMissing(<File>Imports System.|</File>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInSubLambdaParameterListTest() VerifyRecommendationsMissing(<MethodBody>Dim x = Sub(x |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInFunctionLambdaParameterListTest() VerifyRecommendationsMissing(<MethodBody>Dim x = Function(x |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInQueryVariableListTest() VerifyRecommendationsMissing(<MethodBody>Dim x = From y |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInQueryVariableList2Test() VerifyRecommendationsMissing(<MethodBody>Dim x = From y In {1, 2, 3} Let z |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllInSubLambdaBodyTest() VerifyRecommendationsContain(<MethodBody>Dim x = Sub(x As Integer) x |</MethodBody>, s_expectedKeywords) End Sub <WorkItem(541354, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541354")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterStringLiteralTest() VerifyRecommendationsContain(<MethodBody>test = "F" |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllInFunctionLambdaBodyTest() VerifyRecommendationsContain(<MethodBody>Dim x = Function(x As Integer) x |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInObjectMemberInitializer1Test() VerifyRecommendationsMissing(<MethodBody>Dim y = New goo() With {|</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInObjectMemberInitializer2Test() VerifyRecommendationsMissing(<MethodBody>Dim y = New goo() With {.|</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInObjectMemberInitializer3Test() VerifyRecommendationsMissing(<MethodBody>Dim y = New goo() With {.x|</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInObjectMemberInitializer4Test() VerifyRecommendationsMissing(<MethodBody>Dim y = New goo() With {.x |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInCatchStatement1Test() VerifyRecommendationsMissing(<MethodBody> Try Catch ex | </MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInCatchStatement2Test() VerifyRecommendationsMissing(<MethodBody> Try Catch ex As Exception | </MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInDimArrayBounds1Test() VerifyRecommendationsMissing(<MethodBody>Dim i(0 |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllInDimArrayBounds2Test() VerifyRecommendationsContain(<MethodBody>Dim i(0 To 4 |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInReDimArrayBounds1Test() VerifyRecommendationsMissing(<MethodBody>ReDim i(0 |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllInReDimArrayBounds2Test() VerifyRecommendationsContain(<MethodBody>ReDim i(0 To 4 |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterQueryFromTest() VerifyRecommendationsMissing(<MethodBody>Dim query = From |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterQueryAggregateTest() VerifyRecommendationsMissing(<MethodBody>Dim query = Aggregate |</MethodBody>, s_expectedKeywords) End Sub <WorkItem(543637, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543637")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInTypeArgumentListTest() Dim code = <File> Module M Sub Goo(Of T As Class)() Goo(Of T | End Sub End Module </File> VerifyRecommendationsMissing(code, s_expectedKeywords) End Sub <WorkItem(544106, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544106")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterAddHandlerEventNameTest() VerifyRecommendationsMissing(<MethodBody>AddHandler System.Console.CancelKeyPress |</MethodBody>, s_expectedKeywords) End Sub <WorkItem(544106, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544106")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterAddHandlerIdentifierTest() VerifyRecommendationsContain(<MethodBody>AddHandler System.Console.CancelKeyPress, Goo |</MethodBody>, s_expectedKeywords) End Sub <WorkItem(544106, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544106")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterAddHandlerAddressOfIdentifierTest() VerifyRecommendationsMissing(<MethodBody>AddHandler System.Console.CancelKeyPress, AddressOf Goo |</MethodBody>, s_expectedKeywords) End Sub <WorkItem(544106, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544106")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterRemoveHandlerEventNameTest() VerifyRecommendationsMissing(<MethodBody>RemoveHandler System.Console.CancelKeyPress |</MethodBody>, s_expectedKeywords) End Sub <WorkItem(544106, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544106")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterRemoveHandlerIdentifierTest() VerifyRecommendationsContain(<MethodBody>RemoveHandler System.Console.CancelKeyPress, Goo |</MethodBody>, s_expectedKeywords) End Sub <WorkItem(544106, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544106")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterRemoveHandlerAddressOfIdentifierTest() VerifyRecommendationsMissing(<MethodBody>RemoveHandler System.Console.CancelKeyPress, AddressOf Goo |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterNamespaceAliasInImportsTest() Dim code = <File> Imports S | </File> VerifyRecommendationsMissing(code, s_expectedKeywords) End Sub <WorkItem(546505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546505")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoCrashInVariableDeclarationTest() VerifyRecommendationsMissing(<MethodBody>Dim x As New TypeInfo(New |)</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending), WorkItem(544278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544278")> Public Sub NoneAfterMidStatementTest() VerifyRecommendationsMissing(<MethodBody>Mid(s, 1, 1) |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending), WorkItem(544576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544576")> Public Sub NoneAfterExternalMethodDeclarationTest() VerifyRecommendationsMissing(<ClassDeclaration>Declare Sub S Lib "L" Alias "A" |</ClassDeclaration>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending), WorkItem(545988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545988")> Public Sub NoneAfterNamedArgumentTest() VerifyRecommendationsMissing(<MethodBody>Goo(f:=|</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending), WorkItem(546659, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546659")> Public Sub NoneInUsingStatementTest() VerifyRecommendationsMissing(<MethodBody>Using Goo |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending), WorkItem(531329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531329")> Public Sub NoneInForStatementTest() VerifyRecommendationsMissing(<MethodBody>For i = 1 |</MethodBody>, s_expectedKeywords) End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterEolTest() VerifyRecommendationsMissing( <MethodBody>test = "F" |</MethodBody>, s_expectedKeywords) End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTest() VerifyRecommendationsContain( <MethodBody>test = "F" _ |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTestCommentsAfterLineContinuation() VerifyRecommendationsContain( <MethodBody>test = "F" _ ' Test |</MethodBody>, s_expectedKeywords) End Sub <WorkItem(975804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/975804")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterIncompleteObjectCreationTest() VerifyRecommendationsMissing( <MethodBody>Dim x = new Goo.| </MethodBody>, s_expectedKeywords) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Expressions Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Expressions Public Class BinaryOperatorKeywordRecommenderTests Inherits RecommenderTests Private Shared ReadOnly s_expectedKeywords As String() = BinaryOperatorKeywordRecommender.KeywordList.Select(Function(k) k.Keyword).ToArray() <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInClassDeclarationTest() VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInMethodDeclarationTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterLocalDeclarationNumericLiteralInitializerTest() VerifyRecommendationsContain(<MethodBody>Dim i As Integer = 1 |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterNumberInAssignmentTest() VerifyRecommendationsContain(<MethodBody>x = 1 |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterStringInAssignmentTest() VerifyRecommendationsContain(<MethodBody>x = "asdf" |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterObjectCreationInAssignmentTest() VerifyRecommendationsContain(<MethodBody>x = New Object() |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterObjectCreationInDeclarationTest() VerifyRecommendationsMissing(<MethodBody>Dim x = New Object |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterObjectCreationWithParensInDeclarationTest() VerifyRecommendationsMissing(<MethodBody>Dim x = New Object() |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterAsNewInDeclarationTest() VerifyRecommendationsMissing(<MethodBody>Dim x As New Object |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterAsNewWithParensInDeclarationTest() VerifyRecommendationsMissing(<MethodBody>Dim x As New Object() |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterMethodCallInAsNewClauseTest() VerifyRecommendationsContain(<MethodBody>Dim x As New Object(Goo() |)</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterPropertyAccessInAssignmentTest() VerifyRecommendationsContain(<MethodBody>x = Goo.Bar |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterMethodCallInAssignmentTest() VerifyRecommendationsContain(<MethodBody>x = Goo.Bar() |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterDotInImportsTest() VerifyRecommendationsMissing(<File>Imports System.|</File>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInSubLambdaParameterListTest() VerifyRecommendationsMissing(<MethodBody>Dim x = Sub(x |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInFunctionLambdaParameterListTest() VerifyRecommendationsMissing(<MethodBody>Dim x = Function(x |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInQueryVariableListTest() VerifyRecommendationsMissing(<MethodBody>Dim x = From y |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInQueryVariableList2Test() VerifyRecommendationsMissing(<MethodBody>Dim x = From y In {1, 2, 3} Let z |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllInSubLambdaBodyTest() VerifyRecommendationsContain(<MethodBody>Dim x = Sub(x As Integer) x |</MethodBody>, s_expectedKeywords) End Sub <WorkItem(541354, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541354")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterStringLiteralTest() VerifyRecommendationsContain(<MethodBody>test = "F" |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllInFunctionLambdaBodyTest() VerifyRecommendationsContain(<MethodBody>Dim x = Function(x As Integer) x |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInObjectMemberInitializer1Test() VerifyRecommendationsMissing(<MethodBody>Dim y = New goo() With {|</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInObjectMemberInitializer2Test() VerifyRecommendationsMissing(<MethodBody>Dim y = New goo() With {.|</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInObjectMemberInitializer3Test() VerifyRecommendationsMissing(<MethodBody>Dim y = New goo() With {.x|</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInObjectMemberInitializer4Test() VerifyRecommendationsMissing(<MethodBody>Dim y = New goo() With {.x |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInCatchStatement1Test() VerifyRecommendationsMissing(<MethodBody> Try Catch ex | </MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInCatchStatement2Test() VerifyRecommendationsMissing(<MethodBody> Try Catch ex As Exception | </MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInDimArrayBounds1Test() VerifyRecommendationsMissing(<MethodBody>Dim i(0 |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllInDimArrayBounds2Test() VerifyRecommendationsContain(<MethodBody>Dim i(0 To 4 |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInReDimArrayBounds1Test() VerifyRecommendationsMissing(<MethodBody>ReDim i(0 |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllInReDimArrayBounds2Test() VerifyRecommendationsContain(<MethodBody>ReDim i(0 To 4 |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterQueryFromTest() VerifyRecommendationsMissing(<MethodBody>Dim query = From |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterQueryAggregateTest() VerifyRecommendationsMissing(<MethodBody>Dim query = Aggregate |</MethodBody>, s_expectedKeywords) End Sub <WorkItem(543637, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543637")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInTypeArgumentListTest() Dim code = <File> Module M Sub Goo(Of T As Class)() Goo(Of T | End Sub End Module </File> VerifyRecommendationsMissing(code, s_expectedKeywords) End Sub <WorkItem(544106, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544106")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterAddHandlerEventNameTest() VerifyRecommendationsMissing(<MethodBody>AddHandler System.Console.CancelKeyPress |</MethodBody>, s_expectedKeywords) End Sub <WorkItem(544106, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544106")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterAddHandlerIdentifierTest() VerifyRecommendationsContain(<MethodBody>AddHandler System.Console.CancelKeyPress, Goo |</MethodBody>, s_expectedKeywords) End Sub <WorkItem(544106, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544106")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterAddHandlerAddressOfIdentifierTest() VerifyRecommendationsMissing(<MethodBody>AddHandler System.Console.CancelKeyPress, AddressOf Goo |</MethodBody>, s_expectedKeywords) End Sub <WorkItem(544106, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544106")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterRemoveHandlerEventNameTest() VerifyRecommendationsMissing(<MethodBody>RemoveHandler System.Console.CancelKeyPress |</MethodBody>, s_expectedKeywords) End Sub <WorkItem(544106, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544106")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterRemoveHandlerIdentifierTest() VerifyRecommendationsContain(<MethodBody>RemoveHandler System.Console.CancelKeyPress, Goo |</MethodBody>, s_expectedKeywords) End Sub <WorkItem(544106, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544106")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterRemoveHandlerAddressOfIdentifierTest() VerifyRecommendationsMissing(<MethodBody>RemoveHandler System.Console.CancelKeyPress, AddressOf Goo |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterNamespaceAliasInImportsTest() Dim code = <File> Imports S | </File> VerifyRecommendationsMissing(code, s_expectedKeywords) End Sub <WorkItem(546505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546505")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoCrashInVariableDeclarationTest() VerifyRecommendationsMissing(<MethodBody>Dim x As New TypeInfo(New |)</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending), WorkItem(544278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544278")> Public Sub NoneAfterMidStatementTest() VerifyRecommendationsMissing(<MethodBody>Mid(s, 1, 1) |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending), WorkItem(544576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544576")> Public Sub NoneAfterExternalMethodDeclarationTest() VerifyRecommendationsMissing(<ClassDeclaration>Declare Sub S Lib "L" Alias "A" |</ClassDeclaration>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending), WorkItem(545988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545988")> Public Sub NoneAfterNamedArgumentTest() VerifyRecommendationsMissing(<MethodBody>Goo(f:=|</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending), WorkItem(546659, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546659")> Public Sub NoneInUsingStatementTest() VerifyRecommendationsMissing(<MethodBody>Using Goo |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending), WorkItem(531329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531329")> Public Sub NoneInForStatementTest() VerifyRecommendationsMissing(<MethodBody>For i = 1 |</MethodBody>, s_expectedKeywords) End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterEolTest() VerifyRecommendationsMissing( <MethodBody>test = "F" |</MethodBody>, s_expectedKeywords) End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTest() VerifyRecommendationsContain( <MethodBody>test = "F" _ |</MethodBody>, s_expectedKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTestCommentsAfterLineContinuation() VerifyRecommendationsContain( <MethodBody>test = "F" _ ' Test |</MethodBody>, s_expectedKeywords) End Sub <WorkItem(975804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/975804")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterIncompleteObjectCreationTest() VerifyRecommendationsMissing( <MethodBody>Dim x = new Goo.| </MethodBody>, s_expectedKeywords) End Sub End Class End Namespace
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpFormattingOptions2.Parsers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Roslyn.Utilities; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #else using Microsoft.CodeAnalysis.Options; #endif namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal static partial class CSharpFormattingOptions2 { internal static bool DetermineIfSpaceOptionIsSet(string value, SpacingWithinParenthesesOption parenthesesSpacingOption) => (from v in value.Split(',').Select(v => v.Trim()) let option = ConvertToSpacingOption(v) where option.HasValue && option.Value == parenthesesSpacingOption select option) .Any(); private static SpacingWithinParenthesesOption? ConvertToSpacingOption(string value) => s_spacingWithinParenthesisOptionsEditorConfigMap.TryGetValue(value, out var option) ? option : (SpacingWithinParenthesesOption?)null; private static string GetSpacingWithParenthesesEditorConfigString(OptionSet optionSet) { var editorConfigStringBuilder = new List<string>(); foreach (var kvp in SpacingWithinParenthesisOptionsMap) { var value = optionSet.GetOption(kvp.Key); if (value) { Debug.Assert(s_spacingWithinParenthesisOptionsEditorConfigMap.ContainsValue(kvp.Value)); editorConfigStringBuilder.Add(s_spacingWithinParenthesisOptionsEditorConfigMap.GetKeyOrDefault(kvp.Value)!); } } if (editorConfigStringBuilder.Count == 0) { // No spacing within parenthesis option set. return "false"; } else { return string.Join(",", editorConfigStringBuilder.Order()); } } internal static BinaryOperatorSpacingOptions ParseEditorConfigSpacingAroundBinaryOperator(string binaryOperatorSpacingValue) => s_binaryOperatorSpacingOptionsEditorConfigMap.TryGetValue(binaryOperatorSpacingValue.Trim(), out var value) ? value : BinaryOperatorSpacingOptions.Single; private static string GetSpacingAroundBinaryOperatorEditorConfigString(BinaryOperatorSpacingOptions value) => s_binaryOperatorSpacingOptionsEditorConfigMap.TryGetKey(value, out var key) ? key : ""; internal static LabelPositionOptions ParseEditorConfigLabelPositioning(string labelIndentationValue) => s_labelPositionOptionsEditorConfigMap.TryGetValue(labelIndentationValue.Trim(), out var value) ? value : LabelPositionOptions.NoIndent; private static string GetLabelPositionOptionEditorConfigString(LabelPositionOptions value) => s_labelPositionOptionsEditorConfigMap.TryGetKey(value, out var key) ? key : ""; internal static bool DetermineIfNewLineOptionIsSet(string value, NewLineOption optionName) { var values = value.Split(',').Select(v => v.Trim()); if (values.Any(s => s == "all")) { return true; } if (values.Any(s => s == "none")) { return false; } return (from v in values let option = ConvertToNewLineOption(v) where option.HasValue && option.Value == optionName select option) .Any(); } private static NewLineOption? ConvertToNewLineOption(string value) { if (s_newLineOptionsEditorConfigMap.TryGetValue(value, out var option)) { return option; } if (s_legacyNewLineOptionsEditorConfigMap.TryGetValue(value, out var legacyOption)) { return legacyOption; } return null; } private static string GetNewLineOptionEditorConfigString(OptionSet optionSet) { var editorConfigStringBuilder = new List<string>(NewLineOptionsMap.Count); foreach (var kvp in NewLineOptionsMap) { var value = optionSet.GetOption(kvp.Key); if (value) { Debug.Assert(s_newLineOptionsEditorConfigMap.ContainsValue(kvp.Value)); editorConfigStringBuilder.Add(s_newLineOptionsEditorConfigMap.GetKeyOrDefault(kvp.Value)!); } } if (editorConfigStringBuilder.Count == 0) { // No NewLine option set. return "none"; } else if (editorConfigStringBuilder.Count == s_newLineOptionsMapBuilder.Count) { // All NewLine options set. return "all"; } else { return string.Join(",", editorConfigStringBuilder.Order()); } } internal static bool DetermineIfIgnoreSpacesAroundVariableDeclarationIsSet(string value) => value.Trim() == "ignore"; internal enum SpacingWithinParenthesesOption { Expressions, TypeCasts, ControlFlowStatements } internal enum NewLineOption { Types, Methods, Properties, Indexers, Events, AnonymousMethods, ControlBlocks, AnonymousTypes, ObjectCollectionsArrayInitializers, Lambdas, LocalFunction, Accessors } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Roslyn.Utilities; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #else using Microsoft.CodeAnalysis.Options; #endif namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal static partial class CSharpFormattingOptions2 { internal static bool DetermineIfSpaceOptionIsSet(string value, SpacingWithinParenthesesOption parenthesesSpacingOption) => (from v in value.Split(',').Select(v => v.Trim()) let option = ConvertToSpacingOption(v) where option.HasValue && option.Value == parenthesesSpacingOption select option) .Any(); private static SpacingWithinParenthesesOption? ConvertToSpacingOption(string value) => s_spacingWithinParenthesisOptionsEditorConfigMap.TryGetValue(value, out var option) ? option : (SpacingWithinParenthesesOption?)null; private static string GetSpacingWithParenthesesEditorConfigString(OptionSet optionSet) { var editorConfigStringBuilder = new List<string>(); foreach (var kvp in SpacingWithinParenthesisOptionsMap) { var value = optionSet.GetOption(kvp.Key); if (value) { Debug.Assert(s_spacingWithinParenthesisOptionsEditorConfigMap.ContainsValue(kvp.Value)); editorConfigStringBuilder.Add(s_spacingWithinParenthesisOptionsEditorConfigMap.GetKeyOrDefault(kvp.Value)!); } } if (editorConfigStringBuilder.Count == 0) { // No spacing within parenthesis option set. return "false"; } else { return string.Join(",", editorConfigStringBuilder.Order()); } } internal static BinaryOperatorSpacingOptions ParseEditorConfigSpacingAroundBinaryOperator(string binaryOperatorSpacingValue) => s_binaryOperatorSpacingOptionsEditorConfigMap.TryGetValue(binaryOperatorSpacingValue.Trim(), out var value) ? value : BinaryOperatorSpacingOptions.Single; private static string GetSpacingAroundBinaryOperatorEditorConfigString(BinaryOperatorSpacingOptions value) => s_binaryOperatorSpacingOptionsEditorConfigMap.TryGetKey(value, out var key) ? key : ""; internal static LabelPositionOptions ParseEditorConfigLabelPositioning(string labelIndentationValue) => s_labelPositionOptionsEditorConfigMap.TryGetValue(labelIndentationValue.Trim(), out var value) ? value : LabelPositionOptions.NoIndent; private static string GetLabelPositionOptionEditorConfigString(LabelPositionOptions value) => s_labelPositionOptionsEditorConfigMap.TryGetKey(value, out var key) ? key : ""; internal static bool DetermineIfNewLineOptionIsSet(string value, NewLineOption optionName) { var values = value.Split(',').Select(v => v.Trim()); if (values.Any(s => s == "all")) { return true; } if (values.Any(s => s == "none")) { return false; } return (from v in values let option = ConvertToNewLineOption(v) where option.HasValue && option.Value == optionName select option) .Any(); } private static NewLineOption? ConvertToNewLineOption(string value) { if (s_newLineOptionsEditorConfigMap.TryGetValue(value, out var option)) { return option; } if (s_legacyNewLineOptionsEditorConfigMap.TryGetValue(value, out var legacyOption)) { return legacyOption; } return null; } private static string GetNewLineOptionEditorConfigString(OptionSet optionSet) { var editorConfigStringBuilder = new List<string>(NewLineOptionsMap.Count); foreach (var kvp in NewLineOptionsMap) { var value = optionSet.GetOption(kvp.Key); if (value) { Debug.Assert(s_newLineOptionsEditorConfigMap.ContainsValue(kvp.Value)); editorConfigStringBuilder.Add(s_newLineOptionsEditorConfigMap.GetKeyOrDefault(kvp.Value)!); } } if (editorConfigStringBuilder.Count == 0) { // No NewLine option set. return "none"; } else if (editorConfigStringBuilder.Count == s_newLineOptionsMapBuilder.Count) { // All NewLine options set. return "all"; } else { return string.Join(",", editorConfigStringBuilder.Order()); } } internal static bool DetermineIfIgnoreSpacesAroundVariableDeclarationIsSet(string value) => value.Trim() == "ignore"; internal enum SpacingWithinParenthesesOption { Expressions, TypeCasts, ControlFlowStatements } internal enum NewLineOption { Types, Methods, Properties, Indexers, Events, AnonymousMethods, ControlBlocks, AnonymousTypes, ObjectCollectionsArrayInitializers, Lambdas, LocalFunction, Accessors } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Compilers/Core/Portable/InternalUtilities/SpanUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis { internal static class SpanUtilities { public static bool All<TElement, TParam>(this ReadOnlySpan<TElement> span, TParam param, Func<TElement, TParam, bool> predicate) { foreach (var e in span) { if (!predicate(e, param)) { return false; } } return true; } public static bool All<TElement>(this ReadOnlySpan<TElement> span, Func<TElement, bool> predicate) { foreach (var e in span) { if (!predicate(e)) { return false; } } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis { internal static class SpanUtilities { public static bool All<TElement, TParam>(this ReadOnlySpan<TElement> span, TParam param, Func<TElement, TParam, bool> predicate) { foreach (var e in span) { if (!predicate(e, param)) { return false; } } return true; } public static bool All<TElement>(this ReadOnlySpan<TElement> span, Func<TElement, bool> predicate) { foreach (var e in span) { if (!predicate(e)) { return false; } } return true; } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Features/CSharp/Portable/UseAutoProperty/CSharpUseAutoPropertyCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.UseAutoProperty; namespace Microsoft.CodeAnalysis.CSharp.UseAutoProperty { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseAutoProperty), Shared] internal class CSharpUseAutoPropertyCodeFixProvider : AbstractUseAutoPropertyCodeFixProvider<TypeDeclarationSyntax, PropertyDeclarationSyntax, VariableDeclaratorSyntax, ConstructorDeclarationSyntax, ExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUseAutoPropertyCodeFixProvider() { } protected override PropertyDeclarationSyntax GetPropertyDeclaration(SyntaxNode node) => (PropertyDeclarationSyntax)node; protected override SyntaxNode GetNodeToRemove(VariableDeclaratorSyntax declarator) { var fieldDeclaration = (FieldDeclarationSyntax)declarator.Parent.Parent; var nodeToRemove = fieldDeclaration.Declaration.Variables.Count > 1 ? declarator : (SyntaxNode)fieldDeclaration; return nodeToRemove; } protected override async Task<SyntaxNode> UpdatePropertyAsync( Document propertyDocument, Compilation compilation, IFieldSymbol fieldSymbol, IPropertySymbol propertySymbol, PropertyDeclarationSyntax propertyDeclaration, bool isWrittenOutsideOfConstructor, CancellationToken cancellationToken) { var project = propertyDocument.Project; var trailingTrivia = propertyDeclaration.GetTrailingTrivia(); var updatedProperty = propertyDeclaration.WithAccessorList(UpdateAccessorList(propertyDeclaration.AccessorList)) .WithExpressionBody(null) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)); // We may need to add a setter if the field is written to outside of the constructor // of it's class. if (NeedsSetter(compilation, propertyDeclaration, isWrittenOutsideOfConstructor)) { var accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); var generator = SyntaxGenerator.GetGenerator(project); if (fieldSymbol.DeclaredAccessibility != propertySymbol.DeclaredAccessibility) { accessor = (AccessorDeclarationSyntax)generator.WithAccessibility(accessor, fieldSymbol.DeclaredAccessibility); } var modifiers = SyntaxFactory.TokenList( updatedProperty.Modifiers.Where(token => !token.IsKind(SyntaxKind.ReadOnlyKeyword))); updatedProperty = updatedProperty.WithModifiers(modifiers) .AddAccessorListAccessors(accessor); } var fieldInitializer = await GetFieldInitializerAsync(fieldSymbol, cancellationToken).ConfigureAwait(false); if (fieldInitializer != null) { updatedProperty = updatedProperty.WithInitializer(SyntaxFactory.EqualsValueClause(fieldInitializer)) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } return updatedProperty.WithTrailingTrivia(trailingTrivia).WithAdditionalAnnotations(SpecializedFormattingAnnotation); } protected override IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document) { var rules = new List<AbstractFormattingRule> { new SingleLinePropertyFormattingRule() }; rules.AddRange(Formatter.GetDefaultFormattingRules(document)); return rules; } private class SingleLinePropertyFormattingRule : AbstractFormattingRule { private static bool ForceSingleSpace(SyntaxToken previousToken, SyntaxToken currentToken) { if (currentToken.IsKind(SyntaxKind.OpenBraceToken) && currentToken.Parent.IsKind(SyntaxKind.AccessorList)) { return true; } if (previousToken.IsKind(SyntaxKind.OpenBraceToken) && previousToken.Parent.IsKind(SyntaxKind.AccessorList)) { return true; } if (currentToken.IsKind(SyntaxKind.CloseBraceToken) && currentToken.Parent.IsKind(SyntaxKind.AccessorList)) { return true; } return false; } public override AdjustNewLinesOperation GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) { if (ForceSingleSpace(previousToken, currentToken)) { return null; } return base.GetAdjustNewLinesOperation(in previousToken, in currentToken, in nextOperation); } public override AdjustSpacesOperation GetAdjustSpacesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustSpacesOperation nextOperation) { if (ForceSingleSpace(previousToken, currentToken)) { return new AdjustSpacesOperation(1, AdjustSpacesOption.ForceSpaces); } return base.GetAdjustSpacesOperation(in previousToken, in currentToken, in nextOperation); } } private static async Task<ExpressionSyntax> GetFieldInitializerAsync(IFieldSymbol fieldSymbol, CancellationToken cancellationToken) { var variableDeclarator = (VariableDeclaratorSyntax)await fieldSymbol.DeclaringSyntaxReferences[0].GetSyntaxAsync(cancellationToken).ConfigureAwait(false); return variableDeclarator.Initializer?.Value; } private static bool NeedsSetter(Compilation compilation, PropertyDeclarationSyntax propertyDeclaration, bool isWrittenOutsideOfConstructor) { if (propertyDeclaration.AccessorList?.Accessors.Any(SyntaxKind.SetAccessorDeclaration) == true) { // Already has a setter. return false; } if (!SupportsReadOnlyProperties(compilation)) { // If the language doesn't have readonly properties, then we'll need a // setter here. return true; } // If we're written outside a constructor we need a setter. return isWrittenOutsideOfConstructor; } private static bool SupportsReadOnlyProperties(Compilation compilation) => ((CSharpCompilation)compilation).LanguageVersion >= LanguageVersion.CSharp6; private static AccessorListSyntax UpdateAccessorList(AccessorListSyntax accessorList) { if (accessorList == null) { var getter = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); return SyntaxFactory.AccessorList(SyntaxFactory.List(Enumerable.Repeat(getter, 1))); } return accessorList.WithAccessors(SyntaxFactory.List(GetAccessors(accessorList.Accessors))); } private static IEnumerable<AccessorDeclarationSyntax> GetAccessors(SyntaxList<AccessorDeclarationSyntax> accessors) { foreach (var accessor in accessors) { yield return accessor.WithBody(null) .WithExpressionBody(null) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.UseAutoProperty; namespace Microsoft.CodeAnalysis.CSharp.UseAutoProperty { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseAutoProperty), Shared] internal class CSharpUseAutoPropertyCodeFixProvider : AbstractUseAutoPropertyCodeFixProvider<TypeDeclarationSyntax, PropertyDeclarationSyntax, VariableDeclaratorSyntax, ConstructorDeclarationSyntax, ExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUseAutoPropertyCodeFixProvider() { } protected override PropertyDeclarationSyntax GetPropertyDeclaration(SyntaxNode node) => (PropertyDeclarationSyntax)node; protected override SyntaxNode GetNodeToRemove(VariableDeclaratorSyntax declarator) { var fieldDeclaration = (FieldDeclarationSyntax)declarator.Parent.Parent; var nodeToRemove = fieldDeclaration.Declaration.Variables.Count > 1 ? declarator : (SyntaxNode)fieldDeclaration; return nodeToRemove; } protected override async Task<SyntaxNode> UpdatePropertyAsync( Document propertyDocument, Compilation compilation, IFieldSymbol fieldSymbol, IPropertySymbol propertySymbol, PropertyDeclarationSyntax propertyDeclaration, bool isWrittenOutsideOfConstructor, CancellationToken cancellationToken) { var project = propertyDocument.Project; var trailingTrivia = propertyDeclaration.GetTrailingTrivia(); var updatedProperty = propertyDeclaration.WithAccessorList(UpdateAccessorList(propertyDeclaration.AccessorList)) .WithExpressionBody(null) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)); // We may need to add a setter if the field is written to outside of the constructor // of it's class. if (NeedsSetter(compilation, propertyDeclaration, isWrittenOutsideOfConstructor)) { var accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); var generator = SyntaxGenerator.GetGenerator(project); if (fieldSymbol.DeclaredAccessibility != propertySymbol.DeclaredAccessibility) { accessor = (AccessorDeclarationSyntax)generator.WithAccessibility(accessor, fieldSymbol.DeclaredAccessibility); } var modifiers = SyntaxFactory.TokenList( updatedProperty.Modifiers.Where(token => !token.IsKind(SyntaxKind.ReadOnlyKeyword))); updatedProperty = updatedProperty.WithModifiers(modifiers) .AddAccessorListAccessors(accessor); } var fieldInitializer = await GetFieldInitializerAsync(fieldSymbol, cancellationToken).ConfigureAwait(false); if (fieldInitializer != null) { updatedProperty = updatedProperty.WithInitializer(SyntaxFactory.EqualsValueClause(fieldInitializer)) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } return updatedProperty.WithTrailingTrivia(trailingTrivia).WithAdditionalAnnotations(SpecializedFormattingAnnotation); } protected override IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document) { var rules = new List<AbstractFormattingRule> { new SingleLinePropertyFormattingRule() }; rules.AddRange(Formatter.GetDefaultFormattingRules(document)); return rules; } private class SingleLinePropertyFormattingRule : AbstractFormattingRule { private static bool ForceSingleSpace(SyntaxToken previousToken, SyntaxToken currentToken) { if (currentToken.IsKind(SyntaxKind.OpenBraceToken) && currentToken.Parent.IsKind(SyntaxKind.AccessorList)) { return true; } if (previousToken.IsKind(SyntaxKind.OpenBraceToken) && previousToken.Parent.IsKind(SyntaxKind.AccessorList)) { return true; } if (currentToken.IsKind(SyntaxKind.CloseBraceToken) && currentToken.Parent.IsKind(SyntaxKind.AccessorList)) { return true; } return false; } public override AdjustNewLinesOperation GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) { if (ForceSingleSpace(previousToken, currentToken)) { return null; } return base.GetAdjustNewLinesOperation(in previousToken, in currentToken, in nextOperation); } public override AdjustSpacesOperation GetAdjustSpacesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustSpacesOperation nextOperation) { if (ForceSingleSpace(previousToken, currentToken)) { return new AdjustSpacesOperation(1, AdjustSpacesOption.ForceSpaces); } return base.GetAdjustSpacesOperation(in previousToken, in currentToken, in nextOperation); } } private static async Task<ExpressionSyntax> GetFieldInitializerAsync(IFieldSymbol fieldSymbol, CancellationToken cancellationToken) { var variableDeclarator = (VariableDeclaratorSyntax)await fieldSymbol.DeclaringSyntaxReferences[0].GetSyntaxAsync(cancellationToken).ConfigureAwait(false); return variableDeclarator.Initializer?.Value; } private static bool NeedsSetter(Compilation compilation, PropertyDeclarationSyntax propertyDeclaration, bool isWrittenOutsideOfConstructor) { if (propertyDeclaration.AccessorList?.Accessors.Any(SyntaxKind.SetAccessorDeclaration) == true) { // Already has a setter. return false; } if (!SupportsReadOnlyProperties(compilation)) { // If the language doesn't have readonly properties, then we'll need a // setter here. return true; } // If we're written outside a constructor we need a setter. return isWrittenOutsideOfConstructor; } private static bool SupportsReadOnlyProperties(Compilation compilation) => ((CSharpCompilation)compilation).LanguageVersion >= LanguageVersion.CSharp6; private static AccessorListSyntax UpdateAccessorList(AccessorListSyntax accessorList) { if (accessorList == null) { var getter = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); return SyntaxFactory.AccessorList(SyntaxFactory.List(Enumerable.Repeat(getter, 1))); } return accessorList.WithAccessors(SyntaxFactory.List(GetAccessors(accessorList.Accessors))); } private static IEnumerable<AccessorDeclarationSyntax> GetAccessors(SyntaxList<AccessorDeclarationSyntax> accessors) { foreach (var accessor in accessors) { yield return accessor.WithBody(null) .WithExpressionBody(null) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Workspaces/CSharp/Portable/CodeGeneration/ParameterGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.PooledObjects; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class ParameterGenerator { public static ParameterListSyntax GenerateParameterList( ImmutableArray<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { return GenerateParameterList((IEnumerable<IParameterSymbol>)parameterDefinitions, isExplicit, options); } public static ParameterListSyntax GenerateParameterList( IEnumerable<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { var parameters = GetParameters(parameterDefinitions, isExplicit, options); return SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters)); } public static BracketedParameterListSyntax GenerateBracketedParameterList( ImmutableArray<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { return GenerateBracketedParameterList((IList<IParameterSymbol>)parameterDefinitions, isExplicit, options); } public static BracketedParameterListSyntax GenerateBracketedParameterList( IEnumerable<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { // Bracketed parameter lists come from indexers. Those don't have type parameters, so we // could never have a typeParameterMapping. var parameters = GetParameters(parameterDefinitions, isExplicit, options); return SyntaxFactory.BracketedParameterList( parameters: SyntaxFactory.SeparatedList(parameters)); } internal static ImmutableArray<ParameterSyntax> GetParameters( IEnumerable<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { var result = ArrayBuilder<ParameterSyntax>.GetInstance(); var seenOptional = false; var isFirstParam = true; foreach (var p in parameterDefinitions) { var parameter = GetParameter(p, options, isExplicit, isFirstParam, seenOptional); result.Add(parameter); seenOptional = seenOptional || parameter.Default != null; isFirstParam = false; } return result.ToImmutableAndFree(); } internal static ParameterSyntax GetParameter(IParameterSymbol p, CodeGenerationOptions options, bool isExplicit, bool isFirstParam, bool seenOptional) { var reusableSyntax = GetReuseableSyntaxNodeForSymbol<ParameterSyntax>(p, options); if (reusableSyntax != null) { return reusableSyntax; } return SyntaxFactory.Parameter(p.Name.ToIdentifierToken()) .WithAttributeLists(GenerateAttributes(p, isExplicit, options)) .WithModifiers(GenerateModifiers(p, isFirstParam)) .WithType(p.Type.GenerateTypeSyntax()) .WithDefault(GenerateEqualsValueClause(p, isExplicit, seenOptional)); } private static SyntaxTokenList GenerateModifiers( IParameterSymbol parameter, bool isFirstParam) { var list = CSharpSyntaxGeneratorInternal.GetParameterModifiers(parameter.RefKind); if (isFirstParam && parameter.ContainingSymbol is IMethodSymbol methodSymbol && methodSymbol.IsExtensionMethod) { list = list.Add(SyntaxFactory.Token(SyntaxKind.ThisKeyword)); } if (parameter.IsParams) { list = list.Add(SyntaxFactory.Token(SyntaxKind.ParamsKeyword)); } return list; } private static EqualsValueClauseSyntax GenerateEqualsValueClause( IParameterSymbol parameter, bool isExplicit, bool seenOptional) { if (!parameter.IsParams && !isExplicit && !parameter.IsRefOrOut()) { if (parameter.HasExplicitDefaultValue || seenOptional) { var defaultValue = parameter.HasExplicitDefaultValue ? parameter.ExplicitDefaultValue : null; if (defaultValue is DateTime) { return null; } return SyntaxFactory.EqualsValueClause( GenerateEqualsValueClauseWorker(parameter, defaultValue)); } } return null; } private static ExpressionSyntax GenerateEqualsValueClauseWorker( IParameterSymbol parameter, object value) { return ExpressionGenerator.GenerateExpression(parameter.Type, value, canUseFieldReference: true); } private static SyntaxList<AttributeListSyntax> GenerateAttributes( IParameterSymbol parameter, bool isExplicit, CodeGenerationOptions options) { if (isExplicit) { return default; } var attributes = parameter.GetAttributes(); if (attributes.Length == 0) { return default; } return AttributeGenerator.GenerateAttributeLists(attributes, options); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.PooledObjects; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class ParameterGenerator { public static ParameterListSyntax GenerateParameterList( ImmutableArray<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { return GenerateParameterList((IEnumerable<IParameterSymbol>)parameterDefinitions, isExplicit, options); } public static ParameterListSyntax GenerateParameterList( IEnumerable<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { var parameters = GetParameters(parameterDefinitions, isExplicit, options); return SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters)); } public static BracketedParameterListSyntax GenerateBracketedParameterList( ImmutableArray<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { return GenerateBracketedParameterList((IList<IParameterSymbol>)parameterDefinitions, isExplicit, options); } public static BracketedParameterListSyntax GenerateBracketedParameterList( IEnumerable<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { // Bracketed parameter lists come from indexers. Those don't have type parameters, so we // could never have a typeParameterMapping. var parameters = GetParameters(parameterDefinitions, isExplicit, options); return SyntaxFactory.BracketedParameterList( parameters: SyntaxFactory.SeparatedList(parameters)); } internal static ImmutableArray<ParameterSyntax> GetParameters( IEnumerable<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { var result = ArrayBuilder<ParameterSyntax>.GetInstance(); var seenOptional = false; var isFirstParam = true; foreach (var p in parameterDefinitions) { var parameter = GetParameter(p, options, isExplicit, isFirstParam, seenOptional); result.Add(parameter); seenOptional = seenOptional || parameter.Default != null; isFirstParam = false; } return result.ToImmutableAndFree(); } internal static ParameterSyntax GetParameter(IParameterSymbol p, CodeGenerationOptions options, bool isExplicit, bool isFirstParam, bool seenOptional) { var reusableSyntax = GetReuseableSyntaxNodeForSymbol<ParameterSyntax>(p, options); if (reusableSyntax != null) { return reusableSyntax; } return SyntaxFactory.Parameter(p.Name.ToIdentifierToken()) .WithAttributeLists(GenerateAttributes(p, isExplicit, options)) .WithModifiers(GenerateModifiers(p, isFirstParam)) .WithType(p.Type.GenerateTypeSyntax()) .WithDefault(GenerateEqualsValueClause(p, isExplicit, seenOptional)); } private static SyntaxTokenList GenerateModifiers( IParameterSymbol parameter, bool isFirstParam) { var list = CSharpSyntaxGeneratorInternal.GetParameterModifiers(parameter.RefKind); if (isFirstParam && parameter.ContainingSymbol is IMethodSymbol methodSymbol && methodSymbol.IsExtensionMethod) { list = list.Add(SyntaxFactory.Token(SyntaxKind.ThisKeyword)); } if (parameter.IsParams) { list = list.Add(SyntaxFactory.Token(SyntaxKind.ParamsKeyword)); } return list; } private static EqualsValueClauseSyntax GenerateEqualsValueClause( IParameterSymbol parameter, bool isExplicit, bool seenOptional) { if (!parameter.IsParams && !isExplicit && !parameter.IsRefOrOut()) { if (parameter.HasExplicitDefaultValue || seenOptional) { var defaultValue = parameter.HasExplicitDefaultValue ? parameter.ExplicitDefaultValue : null; if (defaultValue is DateTime) { return null; } return SyntaxFactory.EqualsValueClause( GenerateEqualsValueClauseWorker(parameter, defaultValue)); } } return null; } private static ExpressionSyntax GenerateEqualsValueClauseWorker( IParameterSymbol parameter, object value) { return ExpressionGenerator.GenerateExpression(parameter.Type, value, canUseFieldReference: true); } private static SyntaxList<AttributeListSyntax> GenerateAttributes( IParameterSymbol parameter, bool isExplicit, CodeGenerationOptions options) { if (isExplicit) { return default; } var attributes = parameter.GetAttributes(); if (attributes.Length == 0) { return default; } return AttributeGenerator.GenerateAttributeLists(attributes, options); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/EditorFeatures/Test/Completion/FileSystemCompletionHelperTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Completion; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Completion { public class FileSystemCompletionHelperTests { private static void AssertItemsEqual(ImmutableArray<CompletionItem> actual, params string[] expected) { AssertEx.Equal( expected, actual.Select(c => $"'{c.DisplayText}', {string.Join(", ", c.Tags)}, '{c.Properties["Description"]}'"), itemInspector: c => $"@\"{c}\""); Assert.True(actual.All(i => i.Rules == TestFileSystemCompletionHelper.CompletionRules)); } [ConditionalFact(typeof(WindowsOnly))] public void GetItems_Windows1() { var fsc = new TestFileSystemCompletionHelper( searchPaths: ImmutableArray.Create(@"X:\A", @"X:\B"), baseDirectoryOpt: @"Z:\C", allowableExtensions: ImmutableArray.Create(".abc", ".def"), drives: new[] { @"X:\", @"Z:\" }, directories: new[] { @"X:", @"X:\A", @"X:\A\1", @"X:\A\2", @"X:\A\3", @"X:\B", @"Z:", @"Z:\C", @"Z:\D", }, files: new[] { @"X:\A\1\file1.abc", @"X:\A\2\file2.abc", @"X:\B\file4.x", @"X:\B\file5.abc", @"X:\B\hidden.def", @"Z:\C\file6.def", @"Z:\C\file.7.def", }); // Note backslashes in description are escaped AssertItemsEqual(fsc.GetTestAccessor().GetItems("", CancellationToken.None), @"'file6.def', File, C#, 'Text|Z:\5CC\5Cfile6.def'", @"'file.7.def', File, C#, 'Text|Z:\5CC\5Cfile.7.def'", @"'X:', Folder, 'Text|X:'", @"'Z:', Folder, 'Text|Z:'", @"'\\', , 'Text|\5C\5C'", @"'1', Folder, 'Text|X:\5CA\5C1'", @"'2', Folder, 'Text|X:\5CA\5C2'", @"'3', Folder, 'Text|X:\5CA\5C3'", @"'file5.abc', File, C#, 'Text|X:\5CB\5Cfile5.abc'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"X:\A\", CancellationToken.None), @"'1', Folder, 'Text|X:\5CA\5C1'", @"'2', Folder, 'Text|X:\5CA\5C2'", @"'3', Folder, 'Text|X:\5CA\5C3'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"X:\B\", CancellationToken.None), @"'file5.abc', File, C#, 'Text|X:\5CB\5Cfile5.abc'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"Z:\", CancellationToken.None), @"'C', Folder, 'Text|Z:\5CC'", @"'D', Folder, 'Text|Z:\5CD'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"Z:", CancellationToken.None), @"'Z:', Folder, 'Text|Z:'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"\", CancellationToken.None), @"'\\', , 'Text|\5C\5C'"); } [ConditionalFact(typeof(WindowsOnly))] public void GetItems_Windows_NoBaseDirectory() { var fsc = new TestFileSystemCompletionHelper( searchPaths: ImmutableArray.Create(@"X:\A", @"X:\B"), baseDirectoryOpt: null, allowableExtensions: ImmutableArray.Create(".abc", ".def"), drives: new[] { @"X:\" }, directories: new[] { @"X:", @"X:\A", @"X:\A\1", @"X:\A\2", @"X:\A\3", @"X:\B", }, files: new[] { @"X:\A\1\file1.abc", @"X:\A\2\file2.abc", @"X:\B\file4.x", @"X:\B\file5.abc", @"X:\B\hidden.def", }); // Note backslashes in description are escaped AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"", CancellationToken.None), @"'X:', Folder, 'Text|X:'", @"'\\', , 'Text|\5C\5C'", @"'1', Folder, 'Text|X:\5CA\5C1'", @"'2', Folder, 'Text|X:\5CA\5C2'", @"'3', Folder, 'Text|X:\5CA\5C3'", @"'file5.abc', File, C#, 'Text|X:\5CB\5Cfile5.abc'"); } [ConditionalFact(typeof(WindowsOnly))] public void GetItems_Windows_NoSearchPaths() { var fsc = new TestFileSystemCompletionHelper( searchPaths: ImmutableArray<string>.Empty, baseDirectoryOpt: null, allowableExtensions: ImmutableArray.Create(".abc", ".def"), drives: new[] { @"X:\" }, directories: new[] { @"X:", @"X:\A", @"X:\A\1", @"X:\A\2", @"X:\A\3", @"X:\B", }, files: new[] { @"X:\A\1\file1.abc", @"X:\A\2\file2.abc", @"X:\B\file4.x", @"X:\B\file5.abc", @"X:\B\hidden.def", }); // Note backslashes in description are escaped AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"", CancellationToken.None), @"'X:', Folder, 'Text|X:'", @"'\\', , 'Text|\5C\5C'"); } [ConditionalFact(typeof(WindowsOnly))] public void GetItems_Windows_Network() { var fsc = new TestFileSystemCompletionHelper( searchPaths: ImmutableArray<string>.Empty, baseDirectoryOpt: null, allowableExtensions: ImmutableArray.Create(".cs"), drives: Array.Empty<string>(), directories: new[] { @"\\server\share", @"\\server\share\C", @"\\server\share\D", }, files: new[] { @"\\server\share\C\b.cs", @"\\server\share\C\c.cs", @"\\server\share\D\e.cs", }); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"\\server\share\", CancellationToken.None), @"'C', Folder, 'Text|\5C\5Cserver\5Cshare\5CC'", @"'D', Folder, 'Text|\5C\5Cserver\5Cshare\5CD'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"\\server\share\C\", CancellationToken.None), @"'b.cs', File, C#, 'Text|\5C\5Cserver\5Cshare\5CC\5Cb.cs'", @"'c.cs', File, C#, 'Text|\5C\5Cserver\5Cshare\5CC\5Cc.cs'"); } [ConditionalFact(typeof(UnixLikeOnly))] public void GetItems_Unix1() { var fsc = new TestFileSystemCompletionHelper( searchPaths: ImmutableArray.Create(@"/A", @"/B"), baseDirectoryOpt: @"/C", allowableExtensions: ImmutableArray.Create(".abc", ".def"), drives: Array.Empty<string>(), directories: new[] { @"/A", @"/A/1", @"/A/2", @"/A/3", @"/B", @"/C", @"/D", }, files: new[] { @"/A/1/file1.abc", @"/A/2/file2.abc", @"/B/file4.x", @"/B/file5.abc", @"/B/hidden.def", @"/C/file6.def", @"/C/file.7.def", }); // Note backslashes in description are escaped AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"", CancellationToken.None), @"'file6.def', File, C#, 'Text|/C/file6.def'", @"'file.7.def', File, C#, 'Text|/C/file.7.def'", @"'/', Folder, 'Text|/'", @"'1', Folder, 'Text|/A/1'", @"'2', Folder, 'Text|/A/2'", @"'3', Folder, 'Text|/A/3'", @"'file5.abc', File, C#, 'Text|/B/file5.abc'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"/", CancellationToken.None), @"'A', Folder, 'Text|/A'", @"'B', Folder, 'Text|/B'", @"'C', Folder, 'Text|/C'", @"'D', Folder, 'Text|/D'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"/B/", CancellationToken.None), @"'file5.abc', File, C#, 'Text|/B/file5.abc'"); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Completion; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Completion { public class FileSystemCompletionHelperTests { private static void AssertItemsEqual(ImmutableArray<CompletionItem> actual, params string[] expected) { AssertEx.Equal( expected, actual.Select(c => $"'{c.DisplayText}', {string.Join(", ", c.Tags)}, '{c.Properties["Description"]}'"), itemInspector: c => $"@\"{c}\""); Assert.True(actual.All(i => i.Rules == TestFileSystemCompletionHelper.CompletionRules)); } [ConditionalFact(typeof(WindowsOnly))] public void GetItems_Windows1() { var fsc = new TestFileSystemCompletionHelper( searchPaths: ImmutableArray.Create(@"X:\A", @"X:\B"), baseDirectoryOpt: @"Z:\C", allowableExtensions: ImmutableArray.Create(".abc", ".def"), drives: new[] { @"X:\", @"Z:\" }, directories: new[] { @"X:", @"X:\A", @"X:\A\1", @"X:\A\2", @"X:\A\3", @"X:\B", @"Z:", @"Z:\C", @"Z:\D", }, files: new[] { @"X:\A\1\file1.abc", @"X:\A\2\file2.abc", @"X:\B\file4.x", @"X:\B\file5.abc", @"X:\B\hidden.def", @"Z:\C\file6.def", @"Z:\C\file.7.def", }); // Note backslashes in description are escaped AssertItemsEqual(fsc.GetTestAccessor().GetItems("", CancellationToken.None), @"'file6.def', File, C#, 'Text|Z:\5CC\5Cfile6.def'", @"'file.7.def', File, C#, 'Text|Z:\5CC\5Cfile.7.def'", @"'X:', Folder, 'Text|X:'", @"'Z:', Folder, 'Text|Z:'", @"'\\', , 'Text|\5C\5C'", @"'1', Folder, 'Text|X:\5CA\5C1'", @"'2', Folder, 'Text|X:\5CA\5C2'", @"'3', Folder, 'Text|X:\5CA\5C3'", @"'file5.abc', File, C#, 'Text|X:\5CB\5Cfile5.abc'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"X:\A\", CancellationToken.None), @"'1', Folder, 'Text|X:\5CA\5C1'", @"'2', Folder, 'Text|X:\5CA\5C2'", @"'3', Folder, 'Text|X:\5CA\5C3'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"X:\B\", CancellationToken.None), @"'file5.abc', File, C#, 'Text|X:\5CB\5Cfile5.abc'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"Z:\", CancellationToken.None), @"'C', Folder, 'Text|Z:\5CC'", @"'D', Folder, 'Text|Z:\5CD'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"Z:", CancellationToken.None), @"'Z:', Folder, 'Text|Z:'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"\", CancellationToken.None), @"'\\', , 'Text|\5C\5C'"); } [ConditionalFact(typeof(WindowsOnly))] public void GetItems_Windows_NoBaseDirectory() { var fsc = new TestFileSystemCompletionHelper( searchPaths: ImmutableArray.Create(@"X:\A", @"X:\B"), baseDirectoryOpt: null, allowableExtensions: ImmutableArray.Create(".abc", ".def"), drives: new[] { @"X:\" }, directories: new[] { @"X:", @"X:\A", @"X:\A\1", @"X:\A\2", @"X:\A\3", @"X:\B", }, files: new[] { @"X:\A\1\file1.abc", @"X:\A\2\file2.abc", @"X:\B\file4.x", @"X:\B\file5.abc", @"X:\B\hidden.def", }); // Note backslashes in description are escaped AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"", CancellationToken.None), @"'X:', Folder, 'Text|X:'", @"'\\', , 'Text|\5C\5C'", @"'1', Folder, 'Text|X:\5CA\5C1'", @"'2', Folder, 'Text|X:\5CA\5C2'", @"'3', Folder, 'Text|X:\5CA\5C3'", @"'file5.abc', File, C#, 'Text|X:\5CB\5Cfile5.abc'"); } [ConditionalFact(typeof(WindowsOnly))] public void GetItems_Windows_NoSearchPaths() { var fsc = new TestFileSystemCompletionHelper( searchPaths: ImmutableArray<string>.Empty, baseDirectoryOpt: null, allowableExtensions: ImmutableArray.Create(".abc", ".def"), drives: new[] { @"X:\" }, directories: new[] { @"X:", @"X:\A", @"X:\A\1", @"X:\A\2", @"X:\A\3", @"X:\B", }, files: new[] { @"X:\A\1\file1.abc", @"X:\A\2\file2.abc", @"X:\B\file4.x", @"X:\B\file5.abc", @"X:\B\hidden.def", }); // Note backslashes in description are escaped AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"", CancellationToken.None), @"'X:', Folder, 'Text|X:'", @"'\\', , 'Text|\5C\5C'"); } [ConditionalFact(typeof(WindowsOnly))] public void GetItems_Windows_Network() { var fsc = new TestFileSystemCompletionHelper( searchPaths: ImmutableArray<string>.Empty, baseDirectoryOpt: null, allowableExtensions: ImmutableArray.Create(".cs"), drives: Array.Empty<string>(), directories: new[] { @"\\server\share", @"\\server\share\C", @"\\server\share\D", }, files: new[] { @"\\server\share\C\b.cs", @"\\server\share\C\c.cs", @"\\server\share\D\e.cs", }); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"\\server\share\", CancellationToken.None), @"'C', Folder, 'Text|\5C\5Cserver\5Cshare\5CC'", @"'D', Folder, 'Text|\5C\5Cserver\5Cshare\5CD'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"\\server\share\C\", CancellationToken.None), @"'b.cs', File, C#, 'Text|\5C\5Cserver\5Cshare\5CC\5Cb.cs'", @"'c.cs', File, C#, 'Text|\5C\5Cserver\5Cshare\5CC\5Cc.cs'"); } [ConditionalFact(typeof(UnixLikeOnly))] public void GetItems_Unix1() { var fsc = new TestFileSystemCompletionHelper( searchPaths: ImmutableArray.Create(@"/A", @"/B"), baseDirectoryOpt: @"/C", allowableExtensions: ImmutableArray.Create(".abc", ".def"), drives: Array.Empty<string>(), directories: new[] { @"/A", @"/A/1", @"/A/2", @"/A/3", @"/B", @"/C", @"/D", }, files: new[] { @"/A/1/file1.abc", @"/A/2/file2.abc", @"/B/file4.x", @"/B/file5.abc", @"/B/hidden.def", @"/C/file6.def", @"/C/file.7.def", }); // Note backslashes in description are escaped AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"", CancellationToken.None), @"'file6.def', File, C#, 'Text|/C/file6.def'", @"'file.7.def', File, C#, 'Text|/C/file.7.def'", @"'/', Folder, 'Text|/'", @"'1', Folder, 'Text|/A/1'", @"'2', Folder, 'Text|/A/2'", @"'3', Folder, 'Text|/A/3'", @"'file5.abc', File, C#, 'Text|/B/file5.abc'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"/", CancellationToken.None), @"'A', Folder, 'Text|/A'", @"'B', Folder, 'Text|/B'", @"'C', Folder, 'Text|/C'", @"'D', Folder, 'Text|/D'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"/B/", CancellationToken.None), @"'file5.abc', File, C#, 'Text|/B/file5.abc'"); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Workspaces/MSBuildTest/TestFiles/Resources.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Reflection; namespace Microsoft.CodeAnalysis.UnitTests.TestFiles { public static class Resources { private static Stream GetResourceStream(string name) { var resourceName = $"Microsoft.CodeAnalysis.MSBuild.UnitTests.Resources.{name}"; var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName); if (resourceStream != null) { return resourceStream; } throw new InvalidOperationException($"Cannot find resource named: '{resourceName}'"); } private static byte[] LoadBytes(string name) { using (var resourceStream = GetResourceStream(name)) { var bytes = new byte[resourceStream.Length]; resourceStream.Read(bytes, 0, (int)resourceStream.Length); return bytes; } } private static string LoadText(string name) { using (var streamReader = new StreamReader(GetResourceStream(name))) { return streamReader.ReadToEnd(); } } private static readonly Func<string, byte[]> s_bytesLoader = LoadBytes; private static readonly Func<string, string> s_textLoader = LoadText; private static Dictionary<string, byte[]> s_bytesCache; private static Dictionary<string, string> s_textCache; private static TResult GetOrLoadValue<TResult>(string name, Func<string, TResult> loader, ref Dictionary<string, TResult> cache) { if (cache != null && cache.TryGetValue(name, out var result)) { return result; } result = loader(name); if (cache == null) { cache = new Dictionary<string, TResult>(); } cache[name] = result; return result; } public static byte[] GetBytes(string name) => GetOrLoadValue(name, s_bytesLoader, ref s_bytesCache); public static string GetText(string name) => GetOrLoadValue(name, s_textLoader, ref s_textCache); public static string Directory_Build_props => GetText("Directory.Build.props"); public static string Directory_Build_targets => GetText("Directory.Build.targets"); public static byte[] Key_snk => GetBytes("key.snk"); public static string NuGet_Config => GetText("NuGet.Config"); public static class SolutionFilters { public static string Invalid => GetText("SolutionFilters.InvalidSolutionFilter.slnf"); public static string CSharp => GetText("SolutionFilters.CSharpSolutionFilter.slnf"); } public static class SolutionFiles { public static string AnalyzerReference => GetText("SolutionFiles.AnalyzerReference.sln"); public static string CircularSolution => GetText("CircularProjectReferences.CircularSolution.sln"); public static string CSharp => GetText("SolutionFiles.CSharp.sln"); public static string CSharp_EmptyLines => GetText("SolutionFiles.CSharp_EmptyLines.sln"); public static string CSharp_ProjectReference => GetText("SolutionFiles.CSharp_ProjectReference.sln"); public static string CSharp_UnknownProjectExtension => GetText("SolutionFiles.CSharp_UnknownProjectExtension.sln"); public static string CSharp_UnknownProjectTypeGuid => GetText("SolutionFiles.CSharp_UnknownProjectTypeGuid.sln"); public static string CSharp_UnknownProjectTypeGuidAndUnknownExtension => GetText("SolutionFiles.CSharp_UnknownProjectTypeGuidAndUnknownExtension.sln"); public static string DuplicatedGuids => GetText("SolutionFiles.DuplicatedGuids.sln"); public static string DuplicatedGuidsBecomeSelfReferential => GetText("SolutionFiles.DuplicatedGuidsBecomeSelfReferential.sln"); public static string DuplicatedGuidsBecomeCircularReferential => GetText("SolutionFiles.DuplicatedGuidsBecomeCircularReferential.sln"); public static string EmptyLineBetweenProjectBlock => GetText("SolutionFiles.EmptyLineBetweenProjectBlock.sln"); public static string Issue29122_Solution => GetText("Issue29122.TestVB2.sln"); public static string Issue30174_Solution => GetText("Issue30174.Solution.sln"); public static string InvalidProjectPath => GetText("SolutionFiles.InvalidProjectPath.sln"); public static string MissingEndProject1 => GetText("SolutionFiles.MissingEndProject1.sln"); public static string MissingEndProject2 => GetText("SolutionFiles.MissingEndProject2.sln"); public static string MissingEndProject3 => GetText("SolutionFiles.MissingEndProject3.sln"); public static string NetCoreMultiTFM_ProjectReferenceToFSharp = GetText("NetCoreMultiTFM_ProjectReferenceToFSharp.Solution.sln"); public static string NonExistentProject => GetText("SolutionFiles.NonExistentProject.sln"); public static string ProjectLoadErrorOnMissingDebugType => GetText("SolutionFiles.ProjectLoadErrorOnMissingDebugType.sln"); public static string SolutionFolder => GetText("SolutionFiles.SolutionFolder.sln"); public static string VB_and_CSharp => GetText("SolutionFiles.VB_and_CSharp.sln"); } public static class ProjectFiles { public static class CSharp { public static string AnalyzerReference => GetText("ProjectFiles.CSharp.AnalyzerReference.csproj"); public static string AllOptions => GetText("ProjectFiles.CSharp.AllOptions.csproj"); public static string AssemblyNameIsPath => GetText("ProjectFiles.CSharp.AssemblyNameIsPath.csproj"); public static string AssemblyNameIsPath2 => GetText("ProjectFiles.CSharp.AssemblyNameIsPath2.csproj"); public static string BadHintPath => GetText("ProjectFiles.CSharp.BadHintPath.csproj"); public static string BadLink => GetText("ProjectFiles.CSharp.BadLink.csproj"); public static string BadElement => GetText("ProjectFiles.CSharp.BadElement.csproj"); public static string BadTasks => GetText("ProjectFiles.CSharp.BadTasks.csproj"); public static string CircularProjectReferences_CircularCSharpProject1 => GetText("CircularProjectReferences.CircularCSharpProject1.csproj"); public static string CircularProjectReferences_CircularCSharpProject2 => GetText("CircularProjectReferences.CircularCSharpProject2.csproj"); public static string CSharpProject => GetText("ProjectFiles.CSharp.CSharpProject.csproj"); public static string AdditionalFile => GetText("ProjectFiles.CSharp.AdditionalFile.csproj"); public static string DuplicateFile => GetText("ProjectFiles.CSharp.DuplicateFile.csproj"); public static string DuplicateReferences => GetText("ProjectFiles.CSharp.DuplicateReferences.csproj"); public static string DuplicatedGuidLibrary1 => GetText("ProjectFiles.CSharp.DuplicatedGuidLibrary1.csproj"); public static string DuplicatedGuidLibrary2 => GetText("ProjectFiles.CSharp.DuplicatedGuidLibrary2.csproj"); public static string DuplicatedGuidLibrary3 => GetText("ProjectFiles.CSharp.DuplicatedGuidLibrary3.csproj"); public static string DuplicatedGuidLibrary4 => GetText("ProjectFiles.CSharp.DuplicatedGuidLibrary4.csproj"); public static string DuplicatedGuidReferenceTest => GetText("ProjectFiles.CSharp.DuplicatedGuidReferenceTest.csproj"); public static string DuplicatedGuidsBecomeSelfReferential => GetText("ProjectFiles.CSharp.DuplicatedGuidsBecomeSelfReferential.csproj"); public static string DuplicatedGuidsBecomeCircularReferential => GetText("ProjectFiles.CSharp.DuplicatedGuidsBecomeCircularReferential.csproj"); public static string Encoding => GetText("ProjectFiles.CSharp.Encoding.csproj"); public static string ExternAlias => GetText("ProjectFiles.CSharp.ExternAlias.csproj"); public static string ExternAlias2 => GetText("ProjectFiles.CSharp.ExternAlias2.csproj"); public static string ForEmittedOutput => GetText("ProjectFiles.CSharp.ForEmittedOutput.csproj"); public static string Issue30174_InspectedLibrary => GetText("Issue30174.InspectedLibrary.InspectedLibrary.csproj"); public static string Issue30174_ReferencedLibrary => GetText("Issue30174.ReferencedLibrary.ReferencedLibrary.csproj"); public static string MsbuildError => GetText("ProjectFiles.CSharp.MsbuildError.csproj"); public static string MallformedAdditionalFilePath => GetText("ProjectFiles.CSharp.MallformedAdditionalFilePath.csproj"); public static string NetCoreApp2_Project => GetText("NetCoreApp2.Project.csproj"); public static string NetCoreApp2AndLibrary_Project => GetText("NetCoreApp2AndLibrary.Project.csproj"); public static string NetCoreApp2AndLibrary_Library => GetText("NetCoreApp2AndLibrary.Library.csproj"); public static string NetCoreApp2AndTwoLibraries_Project => GetText("NetCoreApp2AndTwoLibraries.Project.csproj"); public static string NetCoreApp2AndTwoLibraries_Library1 => GetText("NetCoreApp2AndTwoLibraries.Library1.csproj"); public static string NetCoreApp2AndTwoLibraries_Library2 => GetText("NetCoreApp2AndTwoLibraries.Library2.csproj"); public static string NetCoreMultiTFM_Project => GetText("NetCoreMultiTFM.Project.csproj"); public static string NetCoreMultiTFM_ExtensionWithConditionOnTFM_Project => GetText("NetCoreMultiTFM_ExtensionWithConditionOnTFM.Project.csproj"); public static string NetCoreMultiTFM_ExtensionWithConditionOnTFM_ProjectTestProps => GetText("NetCoreMultiTFM_ExtensionWithConditionOnTFM.Project.csproj.test.props"); public static string NetCoreMultiTFM_ProjectReference_Library => GetText("NetCoreMultiTFM_ProjectReference.Library.csproj"); public static string NetCoreMultiTFM_ProjectReference_Project => GetText("NetCoreMultiTFM_ProjectReference.Project.csproj"); public static string NetCoreMultiTFM_ProjectReferenceToFSharp_CSharpLib = GetText("NetCoreMultiTFM_ProjectReferenceToFSharp.csharplib.csharplib.csproj"); public static string PortableProject => GetText("ProjectFiles.CSharp.PortableProject.csproj"); public static string ProjectLoadErrorOnMissingDebugType => GetText("ProjectFiles.CSharp.ProjectLoadErrorOnMissingDebugType.csproj"); public static string ProjectReference => GetText("ProjectFiles.CSharp.ProjectReference.csproj"); public static string ReferencesPortableProject => GetText("ProjectFiles.CSharp.ReferencesPortableProject.csproj"); public static string ShouldUnsetParentConfigurationAndPlatform => GetText("ProjectFiles.CSharp.ShouldUnsetParentConfigurationAndPlatform.csproj"); public static string Wildcards => GetText("ProjectFiles.CSharp.Wildcards.csproj"); public static string WithoutCSharpTargetsImported => GetText("ProjectFiles.CSharp.WithoutCSharpTargetsImported.csproj"); public static string WithDiscoverEditorConfigFiles => GetText("ProjectFiles.CSharp.WithDiscoverEditorConfigFiles.csproj"); public static string WithPrefer32Bit => GetText("ProjectFiles.CSharp.WithPrefer32Bit.csproj"); public static string WithLink => GetText("ProjectFiles.CSharp.WithLink.csproj"); public static string WithSystemNumerics => GetText("ProjectFiles.CSharp.WithSystemNumerics.csproj"); public static string WithXaml => GetText("ProjectFiles.CSharp.WithXaml.csproj"); public static string WithoutPrefer32Bit => GetText("ProjectFiles.CSharp.WithoutPrefer32Bit.csproj"); } public static class FSharp { public static string NetCoreMultiTFM_ProjectReferenceToFSharp_FSharpLib = GetText("NetCoreMultiTFM_ProjectReferenceToFSharp.fsharplib.fsharplib.fsproj"); } public static class VisualBasic { public static string AnalyzerReference => GetText("ProjectFiles.VisualBasic.AnalyzerReference.vbproj"); public static string Circular_Target => GetText("ProjectFiles.VisualBasic.Circular_Target.vbproj"); public static string Circular_Top => GetText("ProjectFiles.VisualBasic.Circular_Top.vbproj"); public static string Embed => GetText("ProjectFiles.VisualBasic.Embed.vbproj"); public static string Issue29122_ClassLibrary1 => GetText("Issue29122.Proj1.ClassLibrary1.vbproj"); public static string Issue29122_ClassLibrary2 => GetText("Issue29122.Proj2.ClassLibrary2.vbproj"); public static string InvalidProjectReference => GetText("ProjectFiles.VisualBasic.InvalidProjectReference.vbproj"); public static string NonExistentProjectReference => GetText("ProjectFiles.VisualBasic.NonExistentProjectReference.vbproj"); public static string UnknownProjectExtension => GetText("ProjectFiles.VisualBasic.UnknownProjectExtension.vbproj"); public static string VisualBasicProject => GetText("ProjectFiles.VisualBasic.VisualBasicProject.vbproj"); public static string VisualBasicProject_3_5 => GetText("ProjectFiles.VisualBasic.VisualBasicProject_3_5.vbproj"); public static string WithPrefer32Bit => GetText("ProjectFiles.VisualBasic.WithPrefer32Bit.vbproj"); public static string WithoutPrefer32Bit => GetText("ProjectFiles.VisualBasic.WithoutPrefer32Bit.vbproj"); public static string WithoutVBTargetsImported => GetText("ProjectFiles.VisualBasic.WithoutVBTargetsImported.vbproj"); } } public static class SourceFiles { public static class CSharp { public static string App => GetText("SourceFiles.CSharp.App.xaml.cs"); public static string AssemblyInfo => GetText("SourceFiles.CSharp.AssemblyInfo.cs"); public static string CSharpClass => GetText("SourceFiles.CSharp.CSharpClass.cs"); public static string CSharpClass_WithConditionalAttributes => GetText("SourceFiles.CSharp.CSharpClass_WithConditionalAttributes.cs"); public static string CSharpConsole => GetText("SourceFiles.CSharp.CSharpConsole.cs"); public static string CSharpExternAlias => GetText("SourceFiles.CSharp.CSharpExternAlias.cs"); public static string Issue30174_InspectedClass => GetText("Issue30174.InspectedLibrary.InspectedClass.cs"); public static string Issue30174_SomeMetadataAttribute => GetText("Issue30174.ReferencedLibrary.SomeMetadataAttribute.cs"); public static string NetCoreApp2_Program => GetText("NetCoreApp2.Program.cs"); public static string NetCoreApp2AndLibrary_Class1 => GetText("NetCoreApp2AndLibrary.Class1.cs"); public static string NetCoreApp2AndLibrary_Program => GetText("NetCoreApp2AndLibrary.Program.cs"); public static string NetCoreApp2AndTwoLibraries_Class1 => GetText("NetCoreApp2AndTwoLibraries.Class1.cs"); public static string NetCoreApp2AndTwoLibraries_Class2 => GetText("NetCoreApp2AndTwoLibraries.Class1.cs"); public static string NetCoreApp2AndTwoLibraries_Program => GetText("NetCoreApp2AndTwoLibraries.Program.cs"); public static string NetCoreMultiTFM_Program => GetText("NetCoreMultiTFM.Program.cs"); public static string NetCoreMultiTFM_ProjectReference_Class1 => GetText("NetCoreMultiTFM_ProjectReference.Class1.cs"); public static string NetCoreMultiTFM_ProjectReference_Program => GetText("NetCoreMultiTFM_ProjectReference.Program.cs"); public static string NetCoreMultiTFM_ProjectReferenceToFSharp_CSharpLib_Class1 = GetText("NetCoreMultiTFM_ProjectReferenceToFSharp.csharplib.Class1.cs"); public static string MainWindow => GetText("SourceFiles.CSharp.MainWindow.xaml.cs"); public static string OtherStuff_Foo => GetText("SourceFiles.CSharp.OtherStuff_Foo.cs"); } public static class FSharp { public static string NetCoreMultiTFM_ProjectReferenceToFSharp_FSharpLib_Library = GetText("NetCoreMultiTFM_ProjectReferenceToFSharp.fsharplib.Library.fs"); } public static class Text { public static string ValidAdditionalFile => GetText("SourceFiles.Text.ValidAdditionalFile.txt"); } public static class VisualBasic { public static string Application => GetText("SourceFiles.VisualBasic.Application.myapp"); public static string Application_Designer => GetText("SourceFiles.VisualBasic.Application.Designer.vb"); public static string AssemblyInfo => GetText("SourceFiles.VisualBasic.AssemblyInfo.vb"); public static string Resources => GetText("SourceFiles.VisualBasic.Resources.resx_"); public static string Resources_Designer => GetText("SourceFiles.VisualBasic.Resources.Designer.vb"); public static string Settings => GetText("SourceFiles.VisualBasic.Settings.settings"); public static string Settings_Designer => GetText("SourceFiles.VisualBasic.Settings.Designer.vb"); public static string VisualBasicClass => GetText("SourceFiles.VisualBasic.VisualBasicClass.vb"); public static string VisualBasicClass_WithConditionalAttributes => GetText("SourceFiles.VisualBasic.VisualBasicClass_WithConditionalAttributes.vb"); } public static class Xaml { public static string App => GetText("SourceFiles.Xaml.App.xaml"); public static string MainWindow => GetText("SourceFiles.Xaml.MainWindow.xaml"); } } public static class Dlls { public static byte[] CSharpProject => GetBytes("Dlls.CSharpProject.dll"); public static byte[] EmptyLibrary => GetBytes("Dlls.EmptyLibrary.dll"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Reflection; namespace Microsoft.CodeAnalysis.UnitTests.TestFiles { public static class Resources { private static Stream GetResourceStream(string name) { var resourceName = $"Microsoft.CodeAnalysis.MSBuild.UnitTests.Resources.{name}"; var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName); if (resourceStream != null) { return resourceStream; } throw new InvalidOperationException($"Cannot find resource named: '{resourceName}'"); } private static byte[] LoadBytes(string name) { using (var resourceStream = GetResourceStream(name)) { var bytes = new byte[resourceStream.Length]; resourceStream.Read(bytes, 0, (int)resourceStream.Length); return bytes; } } private static string LoadText(string name) { using (var streamReader = new StreamReader(GetResourceStream(name))) { return streamReader.ReadToEnd(); } } private static readonly Func<string, byte[]> s_bytesLoader = LoadBytes; private static readonly Func<string, string> s_textLoader = LoadText; private static Dictionary<string, byte[]> s_bytesCache; private static Dictionary<string, string> s_textCache; private static TResult GetOrLoadValue<TResult>(string name, Func<string, TResult> loader, ref Dictionary<string, TResult> cache) { if (cache != null && cache.TryGetValue(name, out var result)) { return result; } result = loader(name); if (cache == null) { cache = new Dictionary<string, TResult>(); } cache[name] = result; return result; } public static byte[] GetBytes(string name) => GetOrLoadValue(name, s_bytesLoader, ref s_bytesCache); public static string GetText(string name) => GetOrLoadValue(name, s_textLoader, ref s_textCache); public static string Directory_Build_props => GetText("Directory.Build.props"); public static string Directory_Build_targets => GetText("Directory.Build.targets"); public static byte[] Key_snk => GetBytes("key.snk"); public static string NuGet_Config => GetText("NuGet.Config"); public static class SolutionFilters { public static string Invalid => GetText("SolutionFilters.InvalidSolutionFilter.slnf"); public static string CSharp => GetText("SolutionFilters.CSharpSolutionFilter.slnf"); } public static class SolutionFiles { public static string AnalyzerReference => GetText("SolutionFiles.AnalyzerReference.sln"); public static string CircularSolution => GetText("CircularProjectReferences.CircularSolution.sln"); public static string CSharp => GetText("SolutionFiles.CSharp.sln"); public static string CSharp_EmptyLines => GetText("SolutionFiles.CSharp_EmptyLines.sln"); public static string CSharp_ProjectReference => GetText("SolutionFiles.CSharp_ProjectReference.sln"); public static string CSharp_UnknownProjectExtension => GetText("SolutionFiles.CSharp_UnknownProjectExtension.sln"); public static string CSharp_UnknownProjectTypeGuid => GetText("SolutionFiles.CSharp_UnknownProjectTypeGuid.sln"); public static string CSharp_UnknownProjectTypeGuidAndUnknownExtension => GetText("SolutionFiles.CSharp_UnknownProjectTypeGuidAndUnknownExtension.sln"); public static string DuplicatedGuids => GetText("SolutionFiles.DuplicatedGuids.sln"); public static string DuplicatedGuidsBecomeSelfReferential => GetText("SolutionFiles.DuplicatedGuidsBecomeSelfReferential.sln"); public static string DuplicatedGuidsBecomeCircularReferential => GetText("SolutionFiles.DuplicatedGuidsBecomeCircularReferential.sln"); public static string EmptyLineBetweenProjectBlock => GetText("SolutionFiles.EmptyLineBetweenProjectBlock.sln"); public static string Issue29122_Solution => GetText("Issue29122.TestVB2.sln"); public static string Issue30174_Solution => GetText("Issue30174.Solution.sln"); public static string InvalidProjectPath => GetText("SolutionFiles.InvalidProjectPath.sln"); public static string MissingEndProject1 => GetText("SolutionFiles.MissingEndProject1.sln"); public static string MissingEndProject2 => GetText("SolutionFiles.MissingEndProject2.sln"); public static string MissingEndProject3 => GetText("SolutionFiles.MissingEndProject3.sln"); public static string NetCoreMultiTFM_ProjectReferenceToFSharp = GetText("NetCoreMultiTFM_ProjectReferenceToFSharp.Solution.sln"); public static string NonExistentProject => GetText("SolutionFiles.NonExistentProject.sln"); public static string ProjectLoadErrorOnMissingDebugType => GetText("SolutionFiles.ProjectLoadErrorOnMissingDebugType.sln"); public static string SolutionFolder => GetText("SolutionFiles.SolutionFolder.sln"); public static string VB_and_CSharp => GetText("SolutionFiles.VB_and_CSharp.sln"); } public static class ProjectFiles { public static class CSharp { public static string AnalyzerReference => GetText("ProjectFiles.CSharp.AnalyzerReference.csproj"); public static string AllOptions => GetText("ProjectFiles.CSharp.AllOptions.csproj"); public static string AssemblyNameIsPath => GetText("ProjectFiles.CSharp.AssemblyNameIsPath.csproj"); public static string AssemblyNameIsPath2 => GetText("ProjectFiles.CSharp.AssemblyNameIsPath2.csproj"); public static string BadHintPath => GetText("ProjectFiles.CSharp.BadHintPath.csproj"); public static string BadLink => GetText("ProjectFiles.CSharp.BadLink.csproj"); public static string BadElement => GetText("ProjectFiles.CSharp.BadElement.csproj"); public static string BadTasks => GetText("ProjectFiles.CSharp.BadTasks.csproj"); public static string CircularProjectReferences_CircularCSharpProject1 => GetText("CircularProjectReferences.CircularCSharpProject1.csproj"); public static string CircularProjectReferences_CircularCSharpProject2 => GetText("CircularProjectReferences.CircularCSharpProject2.csproj"); public static string CSharpProject => GetText("ProjectFiles.CSharp.CSharpProject.csproj"); public static string AdditionalFile => GetText("ProjectFiles.CSharp.AdditionalFile.csproj"); public static string DuplicateFile => GetText("ProjectFiles.CSharp.DuplicateFile.csproj"); public static string DuplicateReferences => GetText("ProjectFiles.CSharp.DuplicateReferences.csproj"); public static string DuplicatedGuidLibrary1 => GetText("ProjectFiles.CSharp.DuplicatedGuidLibrary1.csproj"); public static string DuplicatedGuidLibrary2 => GetText("ProjectFiles.CSharp.DuplicatedGuidLibrary2.csproj"); public static string DuplicatedGuidLibrary3 => GetText("ProjectFiles.CSharp.DuplicatedGuidLibrary3.csproj"); public static string DuplicatedGuidLibrary4 => GetText("ProjectFiles.CSharp.DuplicatedGuidLibrary4.csproj"); public static string DuplicatedGuidReferenceTest => GetText("ProjectFiles.CSharp.DuplicatedGuidReferenceTest.csproj"); public static string DuplicatedGuidsBecomeSelfReferential => GetText("ProjectFiles.CSharp.DuplicatedGuidsBecomeSelfReferential.csproj"); public static string DuplicatedGuidsBecomeCircularReferential => GetText("ProjectFiles.CSharp.DuplicatedGuidsBecomeCircularReferential.csproj"); public static string Encoding => GetText("ProjectFiles.CSharp.Encoding.csproj"); public static string ExternAlias => GetText("ProjectFiles.CSharp.ExternAlias.csproj"); public static string ExternAlias2 => GetText("ProjectFiles.CSharp.ExternAlias2.csproj"); public static string ForEmittedOutput => GetText("ProjectFiles.CSharp.ForEmittedOutput.csproj"); public static string Issue30174_InspectedLibrary => GetText("Issue30174.InspectedLibrary.InspectedLibrary.csproj"); public static string Issue30174_ReferencedLibrary => GetText("Issue30174.ReferencedLibrary.ReferencedLibrary.csproj"); public static string MsbuildError => GetText("ProjectFiles.CSharp.MsbuildError.csproj"); public static string MallformedAdditionalFilePath => GetText("ProjectFiles.CSharp.MallformedAdditionalFilePath.csproj"); public static string NetCoreApp2_Project => GetText("NetCoreApp2.Project.csproj"); public static string NetCoreApp2AndLibrary_Project => GetText("NetCoreApp2AndLibrary.Project.csproj"); public static string NetCoreApp2AndLibrary_Library => GetText("NetCoreApp2AndLibrary.Library.csproj"); public static string NetCoreApp2AndTwoLibraries_Project => GetText("NetCoreApp2AndTwoLibraries.Project.csproj"); public static string NetCoreApp2AndTwoLibraries_Library1 => GetText("NetCoreApp2AndTwoLibraries.Library1.csproj"); public static string NetCoreApp2AndTwoLibraries_Library2 => GetText("NetCoreApp2AndTwoLibraries.Library2.csproj"); public static string NetCoreMultiTFM_Project => GetText("NetCoreMultiTFM.Project.csproj"); public static string NetCoreMultiTFM_ExtensionWithConditionOnTFM_Project => GetText("NetCoreMultiTFM_ExtensionWithConditionOnTFM.Project.csproj"); public static string NetCoreMultiTFM_ExtensionWithConditionOnTFM_ProjectTestProps => GetText("NetCoreMultiTFM_ExtensionWithConditionOnTFM.Project.csproj.test.props"); public static string NetCoreMultiTFM_ProjectReference_Library => GetText("NetCoreMultiTFM_ProjectReference.Library.csproj"); public static string NetCoreMultiTFM_ProjectReference_Project => GetText("NetCoreMultiTFM_ProjectReference.Project.csproj"); public static string NetCoreMultiTFM_ProjectReferenceToFSharp_CSharpLib = GetText("NetCoreMultiTFM_ProjectReferenceToFSharp.csharplib.csharplib.csproj"); public static string PortableProject => GetText("ProjectFiles.CSharp.PortableProject.csproj"); public static string ProjectLoadErrorOnMissingDebugType => GetText("ProjectFiles.CSharp.ProjectLoadErrorOnMissingDebugType.csproj"); public static string ProjectReference => GetText("ProjectFiles.CSharp.ProjectReference.csproj"); public static string ReferencesPortableProject => GetText("ProjectFiles.CSharp.ReferencesPortableProject.csproj"); public static string ShouldUnsetParentConfigurationAndPlatform => GetText("ProjectFiles.CSharp.ShouldUnsetParentConfigurationAndPlatform.csproj"); public static string Wildcards => GetText("ProjectFiles.CSharp.Wildcards.csproj"); public static string WithoutCSharpTargetsImported => GetText("ProjectFiles.CSharp.WithoutCSharpTargetsImported.csproj"); public static string WithDiscoverEditorConfigFiles => GetText("ProjectFiles.CSharp.WithDiscoverEditorConfigFiles.csproj"); public static string WithPrefer32Bit => GetText("ProjectFiles.CSharp.WithPrefer32Bit.csproj"); public static string WithLink => GetText("ProjectFiles.CSharp.WithLink.csproj"); public static string WithSystemNumerics => GetText("ProjectFiles.CSharp.WithSystemNumerics.csproj"); public static string WithXaml => GetText("ProjectFiles.CSharp.WithXaml.csproj"); public static string WithoutPrefer32Bit => GetText("ProjectFiles.CSharp.WithoutPrefer32Bit.csproj"); } public static class FSharp { public static string NetCoreMultiTFM_ProjectReferenceToFSharp_FSharpLib = GetText("NetCoreMultiTFM_ProjectReferenceToFSharp.fsharplib.fsharplib.fsproj"); } public static class VisualBasic { public static string AnalyzerReference => GetText("ProjectFiles.VisualBasic.AnalyzerReference.vbproj"); public static string Circular_Target => GetText("ProjectFiles.VisualBasic.Circular_Target.vbproj"); public static string Circular_Top => GetText("ProjectFiles.VisualBasic.Circular_Top.vbproj"); public static string Embed => GetText("ProjectFiles.VisualBasic.Embed.vbproj"); public static string Issue29122_ClassLibrary1 => GetText("Issue29122.Proj1.ClassLibrary1.vbproj"); public static string Issue29122_ClassLibrary2 => GetText("Issue29122.Proj2.ClassLibrary2.vbproj"); public static string InvalidProjectReference => GetText("ProjectFiles.VisualBasic.InvalidProjectReference.vbproj"); public static string NonExistentProjectReference => GetText("ProjectFiles.VisualBasic.NonExistentProjectReference.vbproj"); public static string UnknownProjectExtension => GetText("ProjectFiles.VisualBasic.UnknownProjectExtension.vbproj"); public static string VisualBasicProject => GetText("ProjectFiles.VisualBasic.VisualBasicProject.vbproj"); public static string VisualBasicProject_3_5 => GetText("ProjectFiles.VisualBasic.VisualBasicProject_3_5.vbproj"); public static string WithPrefer32Bit => GetText("ProjectFiles.VisualBasic.WithPrefer32Bit.vbproj"); public static string WithoutPrefer32Bit => GetText("ProjectFiles.VisualBasic.WithoutPrefer32Bit.vbproj"); public static string WithoutVBTargetsImported => GetText("ProjectFiles.VisualBasic.WithoutVBTargetsImported.vbproj"); } } public static class SourceFiles { public static class CSharp { public static string App => GetText("SourceFiles.CSharp.App.xaml.cs"); public static string AssemblyInfo => GetText("SourceFiles.CSharp.AssemblyInfo.cs"); public static string CSharpClass => GetText("SourceFiles.CSharp.CSharpClass.cs"); public static string CSharpClass_WithConditionalAttributes => GetText("SourceFiles.CSharp.CSharpClass_WithConditionalAttributes.cs"); public static string CSharpConsole => GetText("SourceFiles.CSharp.CSharpConsole.cs"); public static string CSharpExternAlias => GetText("SourceFiles.CSharp.CSharpExternAlias.cs"); public static string Issue30174_InspectedClass => GetText("Issue30174.InspectedLibrary.InspectedClass.cs"); public static string Issue30174_SomeMetadataAttribute => GetText("Issue30174.ReferencedLibrary.SomeMetadataAttribute.cs"); public static string NetCoreApp2_Program => GetText("NetCoreApp2.Program.cs"); public static string NetCoreApp2AndLibrary_Class1 => GetText("NetCoreApp2AndLibrary.Class1.cs"); public static string NetCoreApp2AndLibrary_Program => GetText("NetCoreApp2AndLibrary.Program.cs"); public static string NetCoreApp2AndTwoLibraries_Class1 => GetText("NetCoreApp2AndTwoLibraries.Class1.cs"); public static string NetCoreApp2AndTwoLibraries_Class2 => GetText("NetCoreApp2AndTwoLibraries.Class1.cs"); public static string NetCoreApp2AndTwoLibraries_Program => GetText("NetCoreApp2AndTwoLibraries.Program.cs"); public static string NetCoreMultiTFM_Program => GetText("NetCoreMultiTFM.Program.cs"); public static string NetCoreMultiTFM_ProjectReference_Class1 => GetText("NetCoreMultiTFM_ProjectReference.Class1.cs"); public static string NetCoreMultiTFM_ProjectReference_Program => GetText("NetCoreMultiTFM_ProjectReference.Program.cs"); public static string NetCoreMultiTFM_ProjectReferenceToFSharp_CSharpLib_Class1 = GetText("NetCoreMultiTFM_ProjectReferenceToFSharp.csharplib.Class1.cs"); public static string MainWindow => GetText("SourceFiles.CSharp.MainWindow.xaml.cs"); public static string OtherStuff_Foo => GetText("SourceFiles.CSharp.OtherStuff_Foo.cs"); } public static class FSharp { public static string NetCoreMultiTFM_ProjectReferenceToFSharp_FSharpLib_Library = GetText("NetCoreMultiTFM_ProjectReferenceToFSharp.fsharplib.Library.fs"); } public static class Text { public static string ValidAdditionalFile => GetText("SourceFiles.Text.ValidAdditionalFile.txt"); } public static class VisualBasic { public static string Application => GetText("SourceFiles.VisualBasic.Application.myapp"); public static string Application_Designer => GetText("SourceFiles.VisualBasic.Application.Designer.vb"); public static string AssemblyInfo => GetText("SourceFiles.VisualBasic.AssemblyInfo.vb"); public static string Resources => GetText("SourceFiles.VisualBasic.Resources.resx_"); public static string Resources_Designer => GetText("SourceFiles.VisualBasic.Resources.Designer.vb"); public static string Settings => GetText("SourceFiles.VisualBasic.Settings.settings"); public static string Settings_Designer => GetText("SourceFiles.VisualBasic.Settings.Designer.vb"); public static string VisualBasicClass => GetText("SourceFiles.VisualBasic.VisualBasicClass.vb"); public static string VisualBasicClass_WithConditionalAttributes => GetText("SourceFiles.VisualBasic.VisualBasicClass_WithConditionalAttributes.vb"); } public static class Xaml { public static string App => GetText("SourceFiles.Xaml.App.xaml"); public static string MainWindow => GetText("SourceFiles.Xaml.MainWindow.xaml"); } } public static class Dlls { public static byte[] CSharpProject => GetBytes("Dlls.CSharpProject.dll"); public static byte[] EmptyLibrary => GetBytes("Dlls.EmptyLibrary.dll"); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/VisualStudio/CSharp/Impl/LanguageService/CSharpCreateServicesOnTextViewConnection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets { [Export(typeof(IWpfTextViewConnectionListener))] [ContentType(ContentTypeNames.CSharpContentType)] [TextViewRole(PredefinedTextViewRoles.Interactive)] internal class CSharpCreateServicesOnTextViewConnection : AbstractCreateServicesOnTextViewConnection { private readonly object _gate = new(); private readonly HashSet<ProjectId> _processedProjects = new(); private Task _typeTask = Task.CompletedTask; private Task _extensionMethodTask = Task.CompletedTask; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpCreateServicesOnTextViewConnection( VisualStudioWorkspace workspace, IAsynchronousOperationListenerProvider listenerProvider, IThreadingContext threadingContext) : base(workspace, listenerProvider, threadingContext, LanguageNames.CSharp) { } protected override void OnSolutionRemoved() { lock (_gate) { _processedProjects.Clear(); } } protected override Task InitializeServiceForOpenedDocumentAsync(Document document) { // Only pre-populate cache if import completion is enabled if (this.Workspace.Options.GetOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp) != true) return Task.CompletedTask; lock (_gate) { if (!_processedProjects.Contains(document.Project.Id)) { // Make sure we don't capture the entire snapshot var documentId = document.Id; _typeTask = _typeTask.ContinueWith(_ => PopulateTypeImportCompletionCacheAsync(this.Workspace, documentId), TaskScheduler.Default); _extensionMethodTask = _extensionMethodTask.ContinueWith(_ => PopulateExtensionMethodImportCompletionCacheAsync(this.Workspace, documentId), TaskScheduler.Default); } return Task.WhenAll(_typeTask, _extensionMethodTask); } static async Task PopulateTypeImportCompletionCacheAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken = default) { var document = workspace.CurrentSolution.GetDocument(documentId); if (document is null) return; var service = document.GetRequiredLanguageService<ITypeImportCompletionService>(); // First use partial semantic to build mostly correct cache fast var partialDocument = document.WithFrozenPartialSemantics(cancellationToken); await service.WarmUpCacheAsync(partialDocument.Project, CancellationToken.None).ConfigureAwait(false); // Then try to update the cache with full semantic await service.WarmUpCacheAsync(document.Project, CancellationToken.None).ConfigureAwait(false); } static async Task PopulateExtensionMethodImportCompletionCacheAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken = default) { var document = workspace.CurrentSolution.GetDocument(documentId); if (document is null) return; // First use partial semantic to build mostly correct cache fast var partialDocument = document.WithFrozenPartialSemantics(cancellationToken); await ExtensionMethodImportCompletionHelper.WarmUpCacheAsync(partialDocument, cancellationToken).ConfigureAwait(false); // Then try to update the cache with full semantic await ExtensionMethodImportCompletionHelper.WarmUpCacheAsync(document, cancellationToken).ConfigureAwait(false); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets { [Export(typeof(IWpfTextViewConnectionListener))] [ContentType(ContentTypeNames.CSharpContentType)] [TextViewRole(PredefinedTextViewRoles.Interactive)] internal class CSharpCreateServicesOnTextViewConnection : AbstractCreateServicesOnTextViewConnection { private readonly object _gate = new(); private readonly HashSet<ProjectId> _processedProjects = new(); private Task _typeTask = Task.CompletedTask; private Task _extensionMethodTask = Task.CompletedTask; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpCreateServicesOnTextViewConnection( VisualStudioWorkspace workspace, IAsynchronousOperationListenerProvider listenerProvider, IThreadingContext threadingContext) : base(workspace, listenerProvider, threadingContext, LanguageNames.CSharp) { } protected override void OnSolutionRemoved() { lock (_gate) { _processedProjects.Clear(); } } protected override Task InitializeServiceForOpenedDocumentAsync(Document document) { // Only pre-populate cache if import completion is enabled if (this.Workspace.Options.GetOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp) != true) return Task.CompletedTask; lock (_gate) { if (!_processedProjects.Contains(document.Project.Id)) { // Make sure we don't capture the entire snapshot var documentId = document.Id; _typeTask = _typeTask.ContinueWith(_ => PopulateTypeImportCompletionCacheAsync(this.Workspace, documentId), TaskScheduler.Default); _extensionMethodTask = _extensionMethodTask.ContinueWith(_ => PopulateExtensionMethodImportCompletionCacheAsync(this.Workspace, documentId), TaskScheduler.Default); } return Task.WhenAll(_typeTask, _extensionMethodTask); } static async Task PopulateTypeImportCompletionCacheAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken = default) { var document = workspace.CurrentSolution.GetDocument(documentId); if (document is null) return; var service = document.GetRequiredLanguageService<ITypeImportCompletionService>(); // First use partial semantic to build mostly correct cache fast var partialDocument = document.WithFrozenPartialSemantics(cancellationToken); await service.WarmUpCacheAsync(partialDocument.Project, CancellationToken.None).ConfigureAwait(false); // Then try to update the cache with full semantic await service.WarmUpCacheAsync(document.Project, CancellationToken.None).ConfigureAwait(false); } static async Task PopulateExtensionMethodImportCompletionCacheAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken = default) { var document = workspace.CurrentSolution.GetDocument(documentId); if (document is null) return; // First use partial semantic to build mostly correct cache fast var partialDocument = document.WithFrozenPartialSemantics(cancellationToken); await ExtensionMethodImportCompletionHelper.WarmUpCacheAsync(partialDocument, cancellationToken).ConfigureAwait(false); // Then try to update the cache with full semantic await ExtensionMethodImportCompletionHelper.WarmUpCacheAsync(document, cancellationToken).ConfigureAwait(false); } } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicFindReferences.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Common; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicFindReferences : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicFindReferences(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicFindReferences)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)] public void FindReferencesToLocals() { SetUpEditor(@" Class Program Sub Main() Dim local = 1 Console.WriteLine(loca$$l) End Sub End Class "); VisualStudio.SendKeys.Send(Shift(VirtualKey.F12)); const string localReferencesCaption = "'local' references"; var results = VisualStudio.FindReferencesWindow.GetContents(localReferencesCaption); var activeWindowCaption = VisualStudio.Shell.GetActiveWindowCaption(); Assert.Equal(expected: localReferencesCaption, actual: activeWindowCaption); Assert.Collection( results, new Action<Reference>[] { reference => { Assert.Equal(expected: "Dim local = 1", actual: reference.Code); Assert.Equal(expected: 3, actual: reference.Line); Assert.Equal(expected: 10, actual: reference.Column); }, reference => { Assert.Equal(expected: "Console.WriteLine(local)", actual: reference.Code); Assert.Equal(expected: 4, actual: reference.Line); Assert.Equal(expected: 24, actual: reference.Column); } }); } [WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)] public void FindReferencesToSharedField() { SetUpEditor(@" Class Program Public Shared Alpha As Int32 End Class$$ "); var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "File2.vb"); VisualStudio.SolutionExplorer.OpenFile(project, "File2.vb"); SetUpEditor(@" Class SomeOtherClass Sub M() Console.WriteLine(Program.$$Alpha) End Sub End Class "); VisualStudio.SendKeys.Send(Shift(VirtualKey.F12)); const string alphaReferencesCaption = "'Alpha' references"; var results = VisualStudio.FindReferencesWindow.GetContents(alphaReferencesCaption); var activeWindowCaption = VisualStudio.Shell.GetActiveWindowCaption(); Assert.Equal(expected: alphaReferencesCaption, actual: activeWindowCaption); Assert.Collection( results, new Action<Reference>[] { reference => { Assert.Equal(expected: "Public Shared Alpha As Int32", actual: reference.Code); Assert.Equal(expected: 2, actual: reference.Line); Assert.Equal(expected: 18, actual: reference.Column); }, reference => { Assert.Equal(expected: "Console.WriteLine(Program.Alpha)", actual: reference.Code); Assert.Equal(expected: 3, actual: reference.Line); Assert.Equal(expected: 34, actual: reference.Column); } }); } } }
// Licensed to the .NET Foundation under one or more 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; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Common; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicFindReferences : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicFindReferences(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicFindReferences)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)] public void FindReferencesToLocals() { SetUpEditor(@" Class Program Sub Main() Dim local = 1 Console.WriteLine(loca$$l) End Sub End Class "); VisualStudio.SendKeys.Send(Shift(VirtualKey.F12)); const string localReferencesCaption = "'local' references"; var results = VisualStudio.FindReferencesWindow.GetContents(localReferencesCaption); var activeWindowCaption = VisualStudio.Shell.GetActiveWindowCaption(); Assert.Equal(expected: localReferencesCaption, actual: activeWindowCaption); Assert.Collection( results, new Action<Reference>[] { reference => { Assert.Equal(expected: "Dim local = 1", actual: reference.Code); Assert.Equal(expected: 3, actual: reference.Line); Assert.Equal(expected: 10, actual: reference.Column); }, reference => { Assert.Equal(expected: "Console.WriteLine(local)", actual: reference.Code); Assert.Equal(expected: 4, actual: reference.Line); Assert.Equal(expected: 24, actual: reference.Column); } }); } [WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)] public void FindReferencesToSharedField() { SetUpEditor(@" Class Program Public Shared Alpha As Int32 End Class$$ "); var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "File2.vb"); VisualStudio.SolutionExplorer.OpenFile(project, "File2.vb"); SetUpEditor(@" Class SomeOtherClass Sub M() Console.WriteLine(Program.$$Alpha) End Sub End Class "); VisualStudio.SendKeys.Send(Shift(VirtualKey.F12)); const string alphaReferencesCaption = "'Alpha' references"; var results = VisualStudio.FindReferencesWindow.GetContents(alphaReferencesCaption); var activeWindowCaption = VisualStudio.Shell.GetActiveWindowCaption(); Assert.Equal(expected: alphaReferencesCaption, actual: activeWindowCaption); Assert.Collection( results, new Action<Reference>[] { reference => { Assert.Equal(expected: "Public Shared Alpha As Int32", actual: reference.Code); Assert.Equal(expected: 2, actual: reference.Line); Assert.Equal(expected: 18, actual: reference.Column); }, reference => { Assert.Equal(expected: "Console.WriteLine(Program.Alpha)", actual: reference.Code); Assert.Equal(expected: 3, actual: reference.Line); Assert.Equal(expected: 34, actual: reference.Column); } }); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CompilationContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed class CompilationContext { internal readonly CSharpCompilation Compilation; internal readonly Binder NamespaceBinder; // Internal for test purposes. private readonly MethodSymbol _currentFrame; private readonly ImmutableArray<LocalSymbol> _locals; private readonly ImmutableDictionary<string, DisplayClassVariable> _displayClassVariables; private readonly ImmutableArray<string> _sourceMethodParametersInOrder; private readonly ImmutableArray<LocalSymbol> _localsForBinding; private readonly bool _methodNotType; /// <summary> /// Create a context to compile expressions within a method scope. /// </summary> internal CompilationContext( CSharpCompilation compilation, MethodSymbol currentFrame, MethodSymbol? currentSourceMethod, ImmutableArray<LocalSymbol> locals, ImmutableSortedSet<int> inScopeHoistedLocalSlots, MethodDebugInfo<TypeSymbol, LocalSymbol> methodDebugInfo) { _currentFrame = currentFrame; _methodNotType = !locals.IsDefault; // NOTE: Since this is done within CompilationContext, it will not be cached. // CONSIDER: The values should be the same everywhere in the module, so they // could be cached. // (Catch: what happens in a type context without a method def?) Compilation = GetCompilationWithExternAliases(compilation, methodDebugInfo.ExternAliasRecords); // Each expression compile should use a unique compilation // to ensure expression-specific synthesized members can be // added (anonymous types, for instance). Debug.Assert(Compilation != compilation); NamespaceBinder = CreateBinderChain( Compilation, currentFrame.ContainingNamespace, methodDebugInfo.ImportRecordGroups); if (_methodNotType) { _locals = locals; _sourceMethodParametersInOrder = GetSourceMethodParametersInOrder(currentFrame, currentSourceMethod); GetDisplayClassVariables( currentFrame, _locals, inScopeHoistedLocalSlots, _sourceMethodParametersInOrder, out var displayClassVariableNamesInOrder, out _displayClassVariables); Debug.Assert(displayClassVariableNamesInOrder.Length == _displayClassVariables.Count); _localsForBinding = GetLocalsForBinding(_locals, displayClassVariableNamesInOrder, _displayClassVariables); } else { _locals = ImmutableArray<LocalSymbol>.Empty; _displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty; _localsForBinding = ImmutableArray<LocalSymbol>.Empty; } // Assert that the cheap check for "this" is equivalent to the expensive check for "this". Debug.Assert( (GetThisProxy(_displayClassVariables) != null) == _displayClassVariables.Values.Any(v => v.Kind == DisplayClassVariableKind.This)); } internal bool TryCompileExpressions( ImmutableArray<CSharpSyntaxNode> syntaxNodes, string typeNameBase, string methodName, DiagnosticBag diagnostics, [NotNullWhen(true)] out CommonPEModuleBuilder? module) { // Create a separate synthesized type for each evaluation method. // (Necessary for VB in particular since the EENamedTypeSymbol.Locations // is tied to the expression syntax in VB.) var synthesizedTypes = syntaxNodes.SelectAsArray( (syntax, i, _) => (NamedTypeSymbol)CreateSynthesizedType(syntax, typeNameBase + i, methodName, ImmutableArray<Alias>.Empty), arg: (object?)null); if (synthesizedTypes.Length == 0) { module = null; return false; } module = CreateModuleBuilder( Compilation, additionalTypes: synthesizedTypes, testData: null, diagnostics: diagnostics); Compilation.Compile( module, emittingPdb: false, diagnostics: diagnostics, filterOpt: null, CancellationToken.None); return !diagnostics.HasAnyErrors(); } internal bool TryCompileExpression( CSharpSyntaxNode syntax, string typeName, string methodName, ImmutableArray<Alias> aliases, CompilationTestData? testData, DiagnosticBag diagnostics, [NotNullWhen(true)] out CommonPEModuleBuilder? module, [NotNullWhen(true)] out EEMethodSymbol? synthesizedMethod) { var synthesizedType = CreateSynthesizedType(syntax, typeName, methodName, aliases); module = CreateModuleBuilder( Compilation, additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType), testData, diagnostics); Compilation.Compile( module, emittingPdb: false, diagnostics, filterOpt: null, CancellationToken.None); if (diagnostics.HasAnyErrors()) { module = null; synthesizedMethod = null; return false; } synthesizedMethod = GetSynthesizedMethod(synthesizedType); return true; } private EENamedTypeSymbol CreateSynthesizedType( CSharpSyntaxNode syntax, string typeName, string methodName, ImmutableArray<Alias> aliases) { var objectType = Compilation.GetSpecialType(SpecialType.System_Object); var synthesizedType = new EENamedTypeSymbol( Compilation.SourceModule.GlobalNamespace, objectType, syntax, _currentFrame, typeName, methodName, this, (EEMethodSymbol method, DiagnosticBag diags, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { var hasDisplayClassThis = GetThisProxy(_displayClassVariables) != null; var binder = ExtendBinderChain( syntax, aliases, method, NamespaceBinder, hasDisplayClassThis, _methodNotType, out declaredLocals); return (syntax is StatementSyntax statementSyntax) ? BindStatement(binder, statementSyntax, diags, out properties) : BindExpression(binder, (ExpressionSyntax)syntax, diags, out properties); }); return synthesizedType; } internal bool TryCompileAssignment( ExpressionSyntax syntax, string typeName, string methodName, ImmutableArray<Alias> aliases, CompilationTestData? testData, DiagnosticBag diagnostics, [NotNullWhen(true)] out CommonPEModuleBuilder? module, [NotNullWhen(true)] out EEMethodSymbol? synthesizedMethod) { var objectType = Compilation.GetSpecialType(SpecialType.System_Object); var synthesizedType = new EENamedTypeSymbol( Compilation.SourceModule.GlobalNamespace, objectType, syntax, _currentFrame, typeName, methodName, this, (EEMethodSymbol method, DiagnosticBag diags, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { var hasDisplayClassThis = GetThisProxy(_displayClassVariables) != null; var binder = ExtendBinderChain( syntax, aliases, method, NamespaceBinder, hasDisplayClassThis, methodNotType: true, out declaredLocals); properties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect); return BindAssignment(binder, syntax, diags); }); module = CreateModuleBuilder( Compilation, additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType), testData, diagnostics); Compilation.Compile( module, emittingPdb: false, diagnostics, filterOpt: null, CancellationToken.None); if (diagnostics.HasAnyErrors()) { module = null; synthesizedMethod = null; return false; } synthesizedMethod = GetSynthesizedMethod(synthesizedType); return true; } private static EEMethodSymbol GetSynthesizedMethod(EENamedTypeSymbol synthesizedType) => (EEMethodSymbol)synthesizedType.Methods[0]; private static string GetNextMethodName(ArrayBuilder<MethodSymbol> builder) => "<>m" + builder.Count; /// <summary> /// Generate a class containing methods that represent /// the set of arguments and locals at the current scope. /// </summary> internal CommonPEModuleBuilder? CompileGetLocals( string typeName, ArrayBuilder<LocalAndMethod> localBuilder, bool argumentsOnly, ImmutableArray<Alias> aliases, CompilationTestData? testData, DiagnosticBag diagnostics) { var objectType = Compilation.GetSpecialType(SpecialType.System_Object); var allTypeParameters = _currentFrame.GetAllTypeParameters(); var additionalTypes = ArrayBuilder<NamedTypeSymbol>.GetInstance(); EENamedTypeSymbol? typeVariablesType = null; if (!argumentsOnly && allTypeParameters.Length > 0) { // Generate a generic type with matching type parameters. // A null instance of the type will be used to represent the // "Type variables" local. typeVariablesType = new EENamedTypeSymbol( Compilation.SourceModule.GlobalNamespace, objectType, _currentFrame, ExpressionCompilerConstants.TypeVariablesClassName, (m, t) => ImmutableArray.Create<MethodSymbol>(new EEConstructorSymbol(t)), allTypeParameters, (t1, t2) => allTypeParameters.SelectAsArray((tp, i, t) => (TypeParameterSymbol)new SimpleTypeParameterSymbol(t, i, tp.Name), t2)); additionalTypes.Add(typeVariablesType); } var synthesizedType = new EENamedTypeSymbol( Compilation.SourceModule.GlobalNamespace, objectType, _currentFrame, typeName, (m, container) => { var methodBuilder = ArrayBuilder<MethodSymbol>.GetInstance(); if (!argumentsOnly) { // Pseudo-variables: $exception, $ReturnValue, etc. if (aliases.Length > 0) { var sourceAssembly = Compilation.SourceAssembly; var typeNameDecoder = new EETypeNameDecoder(Compilation, (PEModuleSymbol)_currentFrame.ContainingModule); foreach (var alias in aliases) { if (alias.IsReturnValueWithoutIndex()) { Debug.Assert(aliases.Count(a => a.Kind == DkmClrAliasKind.ReturnValue) > 1); continue; } var local = PlaceholderLocalSymbol.Create( typeNameDecoder, _currentFrame, sourceAssembly, alias); // Skip pseudo-variables with errors. if (local.HasUseSiteError) { continue; } var methodName = GetNextMethodName(methodBuilder); var syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken)); var aliasMethod = CreateMethod( container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diags, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { declaredLocals = ImmutableArray<LocalSymbol>.Empty; var expression = new BoundLocal(syntax, local, constantValueOpt: null, type: local.Type); properties = default; return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; }); var flags = local.IsWritableVariable ? DkmClrCompilationResultFlags.None : DkmClrCompilationResultFlags.ReadOnlyResult; localBuilder.Add(MakeLocalAndMethod(local, aliasMethod, flags)); methodBuilder.Add(aliasMethod); } } // "this" for non-static methods that are not display class methods or // display class methods where the display class contains "<>4__this". if (!m.IsStatic && !IsDisplayClassType(m.ContainingType) || GetThisProxy(_displayClassVariables) != null) { var methodName = GetNextMethodName(methodBuilder); var method = GetThisMethod(container, methodName); localBuilder.Add(new CSharpLocalAndMethod("this", "this", method, DkmClrCompilationResultFlags.None)); // Note: writable in dev11. methodBuilder.Add(method); } } var itemsAdded = PooledHashSet<string>.GetInstance(); // Method parameters int parameterIndex = m.IsStatic ? 0 : 1; foreach (var parameter in m.Parameters) { var parameterName = parameter.Name; if (GeneratedNameParser.GetKind(parameterName) == GeneratedNameKind.None && !IsDisplayClassParameter(parameter)) { itemsAdded.Add(parameterName); AppendParameterAndMethod(localBuilder, methodBuilder, parameter, container, parameterIndex); } parameterIndex++; } // In case of iterator or async state machine, the 'm' method has no parameters // but the source method can have parameters to iterate over. if (itemsAdded.Count == 0 && _sourceMethodParametersInOrder.Length != 0) { var localsDictionary = PooledDictionary<string, (LocalSymbol, int)>.GetInstance(); int localIndex = 0; foreach (var local in _localsForBinding) { localsDictionary.Add(local.Name, (local, localIndex)); localIndex++; } foreach (var argumentName in _sourceMethodParametersInOrder) { (LocalSymbol local, int localIndex) localSymbolAndIndex; if (localsDictionary.TryGetValue(argumentName, out localSymbolAndIndex)) { itemsAdded.Add(argumentName); var local = localSymbolAndIndex.local; AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localSymbolAndIndex.localIndex, GetLocalResultFlags(local)); } } localsDictionary.Free(); } if (!argumentsOnly) { // Locals which were not added as parameters or parameters of the source method. int localIndex = 0; foreach (var local in _localsForBinding) { if (!itemsAdded.Contains(local.Name)) { AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localIndex, GetLocalResultFlags(local)); } localIndex++; } // "Type variables". if (typeVariablesType is object) { var methodName = GetNextMethodName(methodBuilder); var returnType = typeVariablesType.Construct(allTypeParameters.Cast<TypeParameterSymbol, TypeSymbol>()); var method = GetTypeVariablesMethod(container, methodName, returnType); localBuilder.Add(new CSharpLocalAndMethod( ExpressionCompilerConstants.TypeVariablesLocalName, ExpressionCompilerConstants.TypeVariablesLocalName, method, DkmClrCompilationResultFlags.ReadOnlyResult)); methodBuilder.Add(method); } } itemsAdded.Free(); return methodBuilder.ToImmutableAndFree(); }); additionalTypes.Add(synthesizedType); var module = CreateModuleBuilder( Compilation, additionalTypes.ToImmutableAndFree(), testData, diagnostics); RoslynDebug.AssertNotNull(module); Compilation.Compile( module, emittingPdb: false, diagnostics, filterOpt: null, CancellationToken.None); return diagnostics.HasAnyErrors() ? null : module; } private void AppendLocalAndMethod( ArrayBuilder<LocalAndMethod> localBuilder, ArrayBuilder<MethodSymbol> methodBuilder, LocalSymbol local, EENamedTypeSymbol container, int localIndex, DkmClrCompilationResultFlags resultFlags) { var methodName = GetNextMethodName(methodBuilder); var method = GetLocalMethod(container, methodName, local.Name, localIndex); localBuilder.Add(MakeLocalAndMethod(local, method, resultFlags)); methodBuilder.Add(method); } private void AppendParameterAndMethod( ArrayBuilder<LocalAndMethod> localBuilder, ArrayBuilder<MethodSymbol> methodBuilder, ParameterSymbol parameter, EENamedTypeSymbol container, int parameterIndex) { // Note: The native EE doesn't do this, but if we don't escape keyword identifiers, // the ResultProvider needs to be able to disambiguate cases like "this" and "@this", // which it can't do correctly without semantic information. var name = SyntaxHelpers.EscapeKeywordIdentifiers(parameter.Name); var methodName = GetNextMethodName(methodBuilder); var method = GetParameterMethod(container, methodName, name, parameterIndex); localBuilder.Add(new CSharpLocalAndMethod(name, name, method, DkmClrCompilationResultFlags.None)); methodBuilder.Add(method); } private static LocalAndMethod MakeLocalAndMethod(LocalSymbol local, MethodSymbol method, DkmClrCompilationResultFlags flags) { // Note: The native EE doesn't do this, but if we don't escape keyword identifiers, // the ResultProvider needs to be able to disambiguate cases like "this" and "@this", // which it can't do correctly without semantic information. var escapedName = SyntaxHelpers.EscapeKeywordIdentifiers(local.Name); var displayName = (local as PlaceholderLocalSymbol)?.DisplayName ?? escapedName; return new CSharpLocalAndMethod(escapedName, displayName, method, flags); } private static EEAssemblyBuilder CreateModuleBuilder( CSharpCompilation compilation, ImmutableArray<NamedTypeSymbol> additionalTypes, CompilationTestData? testData, DiagnosticBag diagnostics) { // Each assembly must have a unique name. var emitOptions = new EmitOptions(outputNameOverride: ExpressionCompilerUtilities.GenerateUniqueName()); string? runtimeMetadataVersion = compilation.GetRuntimeMetadataVersion(emitOptions, diagnostics); var serializationProperties = compilation.ConstructModuleSerializationProperties(emitOptions, runtimeMetadataVersion); return new EEAssemblyBuilder( compilation.SourceAssembly, emitOptions, serializationProperties, additionalTypes, contextType => GetNonDisplayClassContainer(((EENamedTypeSymbol)contextType).SubstitutedSourceType), testData); } internal EEMethodSymbol CreateMethod( EENamedTypeSymbol container, string methodName, CSharpSyntaxNode syntax, GenerateMethodBody generateMethodBody) { return new EEMethodSymbol( container, methodName, syntax.Location, _currentFrame, _locals, _localsForBinding, _displayClassVariables, generateMethodBody); } private EEMethodSymbol GetLocalMethod(EENamedTypeSymbol container, string methodName, string localName, int localIndex) { var syntax = SyntaxFactory.IdentifierName(localName); return CreateMethod(container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { declaredLocals = ImmutableArray<LocalSymbol>.Empty; var local = method.LocalsForBinding[localIndex]; var expression = new BoundLocal(syntax, local, constantValueOpt: local.GetConstantValue(null, null, new BindingDiagnosticBag(diagnostics)), type: local.Type); properties = default; return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; }); } private EEMethodSymbol GetParameterMethod(EENamedTypeSymbol container, string methodName, string parameterName, int parameterIndex) { var syntax = SyntaxFactory.IdentifierName(parameterName); return CreateMethod(container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { declaredLocals = ImmutableArray<LocalSymbol>.Empty; var parameter = method.Parameters[parameterIndex]; var expression = new BoundParameter(syntax, parameter); properties = default; return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; }); } private EEMethodSymbol GetThisMethod(EENamedTypeSymbol container, string methodName) { var syntax = SyntaxFactory.ThisExpression(); return CreateMethod(container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { declaredLocals = ImmutableArray<LocalSymbol>.Empty; var expression = new BoundThisReference(syntax, GetNonDisplayClassContainer(container.SubstitutedSourceType)); properties = default; return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; }); } private EEMethodSymbol GetTypeVariablesMethod(EENamedTypeSymbol container, string methodName, NamedTypeSymbol typeVariablesType) { var syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken)); return CreateMethod(container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { declaredLocals = ImmutableArray<LocalSymbol>.Empty; var type = method.TypeMap.SubstituteNamedType(typeVariablesType); var expression = new BoundObjectCreationExpression(syntax, type.InstanceConstructors[0]); var statement = new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; properties = default; return statement; }); } private static BoundStatement? BindExpression(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics, out ResultProperties resultProperties) { var flags = DkmClrCompilationResultFlags.None; var bindingDiagnostics = new BindingDiagnosticBag(diagnostics); // In addition to C# expressions, the native EE also supports // type names which are bound to a representation of the type // (but not System.Type) that the user can expand to see the // base type. Instead, we only allow valid C# expressions. var expression = IsDeconstruction(syntax) ? binder.BindDeconstruction((AssignmentExpressionSyntax)syntax, bindingDiagnostics, resultIsUsedOverride: true) : binder.BindRValueWithoutTargetType(syntax, bindingDiagnostics); if (diagnostics.HasAnyErrors()) { resultProperties = default; return null; } try { if (MayHaveSideEffectsVisitor.MayHaveSideEffects(expression)) { flags |= DkmClrCompilationResultFlags.PotentialSideEffect; } } catch (BoundTreeVisitor.CancelledByStackGuardException ex) { ex.AddAnError(diagnostics); resultProperties = default; return null; } var expressionType = expression.Type; if (expressionType is null) { expression = binder.CreateReturnConversion( syntax, bindingDiagnostics, expression, RefKind.None, binder.Compilation.GetSpecialType(SpecialType.System_Object)); if (diagnostics.HasAnyErrors()) { resultProperties = default; return null; } } else if (expressionType.SpecialType == SpecialType.System_Void) { flags |= DkmClrCompilationResultFlags.ReadOnlyResult; Debug.Assert(expression.ConstantValue == null); resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, isConstant: false); return new BoundExpressionStatement(syntax, expression) { WasCompilerGenerated = true }; } else if (expressionType.SpecialType == SpecialType.System_Boolean) { flags |= DkmClrCompilationResultFlags.BoolResult; } if (!IsAssignableExpression(binder, expression)) { flags |= DkmClrCompilationResultFlags.ReadOnlyResult; } resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, expression.ConstantValue != null); return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; } private static bool IsDeconstruction(ExpressionSyntax syntax) { if (syntax.Kind() != SyntaxKind.SimpleAssignmentExpression) { return false; } var node = (AssignmentExpressionSyntax)syntax; return node.Left.Kind() == SyntaxKind.TupleExpression || node.Left.Kind() == SyntaxKind.DeclarationExpression; } private static BoundStatement BindStatement(Binder binder, StatementSyntax syntax, DiagnosticBag diagnostics, out ResultProperties properties) { properties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); return binder.BindStatement(syntax, new BindingDiagnosticBag(diagnostics)); } private static bool IsAssignableExpression(Binder binder, BoundExpression expression) { var result = binder.CheckValueKind(expression.Syntax, expression, Binder.BindValueKind.Assignable, checkingReceiver: false, BindingDiagnosticBag.Discarded); return result; } private static BoundStatement? BindAssignment(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics) { var expression = binder.BindValue(syntax, new BindingDiagnosticBag(diagnostics), Binder.BindValueKind.RValue); if (diagnostics.HasAnyErrors()) { return null; } return new BoundExpressionStatement(expression.Syntax, expression) { WasCompilerGenerated = true }; } private static Binder CreateBinderChain( CSharpCompilation compilation, NamespaceSymbol @namespace, ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups) { var stack = ArrayBuilder<string>.GetInstance(); while (@namespace is object) { stack.Push(@namespace.Name); @namespace = @namespace.ContainingNamespace; } Binder binder = new BuckStopsHereBinder(compilation); var hasImports = !importRecordGroups.IsDefaultOrEmpty; var numImportStringGroups = hasImports ? importRecordGroups.Length : 0; var currentStringGroup = numImportStringGroups - 1; // PERF: We used to call compilation.GetCompilationNamespace on every iteration, // but that involved walking up to the global namespace, which we have to do // anyway. Instead, we'll inline the functionality into our own walk of the // namespace chain. @namespace = compilation.GlobalNamespace; while (stack.Count > 0) { var namespaceName = stack.Pop(); if (namespaceName.Length > 0) { // We're re-getting the namespace, rather than using the one containing // the current frame method, because we want the merged namespace. @namespace = @namespace.GetNestedNamespace(namespaceName); RoslynDebug.AssertNotNull(@namespace); } else { Debug.Assert((object)@namespace == compilation.GlobalNamespace); } if (hasImports) { if (currentStringGroup < 0) { Debug.WriteLine($"No import string group for namespace '{@namespace}'"); break; } var importsBinder = new InContainerBinder(@namespace, binder); Imports imports = BuildImports(compilation, importRecordGroups[currentStringGroup], importsBinder); currentStringGroup--; binder = WithExternAndUsingAliasesBinder.Create(imports.ExternAliases, imports.UsingAliases, WithUsingNamespacesAndTypesBinder.Create(imports.Usings, binder)); } binder = new InContainerBinder(@namespace, binder); } stack.Free(); if (currentStringGroup >= 0) { // CONSIDER: We could lump these into the outermost namespace. It's probably not worthwhile since // the usings are already for the wrong method. Debug.WriteLine($"Found {currentStringGroup + 1} import string groups without corresponding namespaces"); } return binder; } private static CSharpCompilation GetCompilationWithExternAliases(CSharpCompilation compilation, ImmutableArray<ExternAliasRecord> externAliasRecords) { if (externAliasRecords.IsDefaultOrEmpty) { return compilation.Clone(); } var updatedReferences = ArrayBuilder<MetadataReference>.GetInstance(); var assembliesAndModulesBuilder = ArrayBuilder<Symbol>.GetInstance(); foreach (var reference in compilation.References) { updatedReferences.Add(reference); assembliesAndModulesBuilder.Add(compilation.GetAssemblyOrModuleSymbol(reference)!); } Debug.Assert(assembliesAndModulesBuilder.Count == updatedReferences.Count); var assembliesAndModules = assembliesAndModulesBuilder.ToImmutableAndFree(); foreach (var externAliasRecord in externAliasRecords) { var targetAssembly = externAliasRecord.TargetAssembly as AssemblySymbol; int index; if (targetAssembly != null) { index = assembliesAndModules.IndexOf(targetAssembly); } else { index = IndexOfMatchingAssembly((AssemblyIdentity)externAliasRecord.TargetAssembly, assembliesAndModules, compilation.Options.AssemblyIdentityComparer); } if (index < 0) { Debug.WriteLine($"Unable to find corresponding assembly reference for extern alias '{externAliasRecord}'"); continue; } var externAlias = externAliasRecord.Alias; var assemblyReference = updatedReferences[index]; var oldAliases = assemblyReference.Properties.Aliases; var newAliases = oldAliases.IsEmpty ? ImmutableArray.Create(MetadataReferenceProperties.GlobalAlias, externAlias) : oldAliases.Concat(ImmutableArray.Create(externAlias)); // NOTE: Dev12 didn't emit custom debug info about "global", so we don't have // a good way to distinguish between a module aliased with both (e.g.) "X" and // "global" and a module aliased with only "X". As in Dev12, we assume that // "global" is a valid alias to remain at least as permissive as source. // NOTE: In the event that this introduces ambiguities between two assemblies // (e.g. because one was "global" in source and the other was "X"), it should be // possible to disambiguate as long as each assembly has a distinct extern alias, // not necessarily used in source. Debug.Assert(newAliases.Contains(MetadataReferenceProperties.GlobalAlias)); // Replace the value in the map with the updated reference. updatedReferences[index] = assemblyReference.WithAliases(newAliases); } compilation = compilation.WithReferences(updatedReferences); updatedReferences.Free(); return compilation; } private static int IndexOfMatchingAssembly(AssemblyIdentity referenceIdentity, ImmutableArray<Symbol> assembliesAndModules, AssemblyIdentityComparer assemblyIdentityComparer) { for (int i = 0; i < assembliesAndModules.Length; i++) { if (assembliesAndModules[i] is AssemblySymbol assembly && assemblyIdentityComparer.ReferenceMatchesDefinition(referenceIdentity, assembly.Identity)) { return i; } } return -1; } private static Binder ExtendBinderChain( CSharpSyntaxNode syntax, ImmutableArray<Alias> aliases, EEMethodSymbol method, Binder binder, bool hasDisplayClassThis, bool methodNotType, out ImmutableArray<LocalSymbol> declaredLocals) { var substitutedSourceMethod = GetSubstitutedSourceMethod(method.SubstitutedSourceMethod, hasDisplayClassThis); var substitutedSourceType = substitutedSourceMethod.ContainingType; var stack = ArrayBuilder<NamedTypeSymbol>.GetInstance(); for (var type = substitutedSourceType; type is object; type = type.ContainingType) { stack.Add(type); } while (stack.Count > 0) { substitutedSourceType = stack.Pop(); binder = new InContainerBinder(substitutedSourceType, binder); if (substitutedSourceType.Arity > 0) { binder = new WithTypeArgumentsBinder(substitutedSourceType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics, binder); } } stack.Free(); if (substitutedSourceMethod.Arity > 0) { binder = new WithTypeArgumentsBinder(substitutedSourceMethod.TypeArgumentsWithAnnotations, binder); } // Method locals and parameters shadow pseudo-variables. // That is why we place PlaceholderLocalBinder and ExecutableCodeBinder before EEMethodBinder. if (methodNotType) { var typeNameDecoder = new EETypeNameDecoder(binder.Compilation, (PEModuleSymbol)substitutedSourceMethod.ContainingModule); binder = new PlaceholderLocalBinder( syntax, aliases, method, typeNameDecoder, binder); } binder = new EEMethodBinder(method, substitutedSourceMethod, binder); if (methodNotType) { binder = new SimpleLocalScopeBinder(method.LocalsForBinding, binder); } Binder? actualRootBinder = null; SyntaxNode? declaredLocalsScopeDesignator = null; var executableBinder = new ExecutableCodeBinder(syntax, substitutedSourceMethod, binder, (rootBinder, declaredLocalsScopeDesignatorOpt) => { actualRootBinder = rootBinder; declaredLocalsScopeDesignator = declaredLocalsScopeDesignatorOpt; }); // We just need to trigger the process of building the binder map // so that the lambda above was executed. executableBinder.GetBinder(syntax); RoslynDebug.AssertNotNull(actualRootBinder); if (declaredLocalsScopeDesignator != null) { declaredLocals = actualRootBinder.GetDeclaredLocalsForScope(declaredLocalsScopeDesignator); } else { declaredLocals = ImmutableArray<LocalSymbol>.Empty; } return actualRootBinder; } private static Imports BuildImports(CSharpCompilation compilation, ImmutableArray<ImportRecord> importRecords, InContainerBinder binder) { // We make a first pass to extract all of the extern aliases because other imports may depend on them. var externsBuilder = ArrayBuilder<AliasAndExternAliasDirective>.GetInstance(); foreach (var importRecord in importRecords) { if (importRecord.TargetKind != ImportTargetKind.Assembly) { continue; } var alias = importRecord.Alias; RoslynDebug.AssertNotNull(alias); if (!TryParseIdentifierNameSyntax(alias, out var aliasNameSyntax)) { Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{alias}'"); continue; } NamespaceSymbol target; compilation.GetExternAliasTarget(aliasNameSyntax.Identifier.ValueText, out target); Debug.Assert(target.IsGlobalNamespace); var aliasSymbol = AliasSymbol.CreateCustomDebugInfoAlias(target, aliasNameSyntax.Identifier, binder.ContainingMemberOrLambda, isExtern: true); externsBuilder.Add(new AliasAndExternAliasDirective(aliasSymbol, externAliasDirective: null, skipInLookup: false)); } var externs = externsBuilder.ToImmutableAndFree(); if (externs.Any()) { // NB: This binder (and corresponding Imports) is only used to bind the other imports. // We'll merge the externs into a final Imports object and return that to be used in // the actual binder chain. binder = new InContainerBinder( binder.Container, WithExternAliasesBinder.Create(externs, binder)); } var usingAliases = ImmutableDictionary.CreateBuilder<string, AliasAndUsingDirective>(); var usingsBuilder = ArrayBuilder<NamespaceOrTypeAndUsingDirective>.GetInstance(); foreach (var importRecord in importRecords) { switch (importRecord.TargetKind) { case ImportTargetKind.Type: { var typeSymbol = (TypeSymbol?)importRecord.TargetType; RoslynDebug.AssertNotNull(typeSymbol); if (typeSymbol.IsErrorType()) { // Type is unrecognized. The import may have been // valid in the original source but unnecessary. continue; // Don't add anything for this import. } else if (importRecord.Alias == null && !typeSymbol.IsStatic) { // Only static types can be directly imported. continue; } if (!TryAddImport(importRecord.Alias, typeSymbol, usingsBuilder, usingAliases, binder, importRecord)) { continue; } break; } case ImportTargetKind.Namespace: { var namespaceName = importRecord.TargetString; RoslynDebug.AssertNotNull(namespaceName); if (!SyntaxHelpers.TryParseDottedName(namespaceName, out _)) { // DevDiv #999086: Some previous version of VS apparently generated type aliases as "UA{alias} T{alias-qualified type name}". // Neither Roslyn nor Dev12 parses such imports. However, Roslyn discards them, rather than interpreting them as "UA{alias}" // (which will rarely work and never be correct). Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid target '{importRecord.TargetString}'"); continue; } NamespaceSymbol globalNamespace; var targetAssembly = (AssemblySymbol?)importRecord.TargetAssembly; if (targetAssembly is object) { if (targetAssembly.IsMissing) { Debug.WriteLine($"Import record '{importRecord}' has invalid assembly reference '{targetAssembly.Identity}'"); continue; } globalNamespace = targetAssembly.GlobalNamespace; } else if (importRecord.TargetAssemblyAlias != null) { if (!TryParseIdentifierNameSyntax(importRecord.TargetAssemblyAlias, out var externAliasSyntax)) { Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{importRecord.TargetAssemblyAlias}'"); continue; } var aliasSymbol = (AliasSymbol)binder.BindNamespaceAliasSymbol(externAliasSyntax, BindingDiagnosticBag.Discarded); if (aliasSymbol is null) { Debug.WriteLine($"Import record '{importRecord}' requires unknown extern alias '{importRecord.TargetAssemblyAlias}'"); continue; } globalNamespace = (NamespaceSymbol)aliasSymbol.Target; } else { globalNamespace = compilation.GlobalNamespace; } var namespaceSymbol = BindNamespace(namespaceName, globalNamespace); if (namespaceSymbol is null) { // Namespace is unrecognized. The import may have been // valid in the original source but unnecessary. continue; // Don't add anything for this import. } if (!TryAddImport(importRecord.Alias, namespaceSymbol, usingsBuilder, usingAliases, binder, importRecord)) { continue; } break; } case ImportTargetKind.Assembly: // Handled in first pass (above). break; default: throw ExceptionUtilities.UnexpectedValue(importRecord.TargetKind); } } return Imports.Create(usingAliases.ToImmutableDictionary(), usingsBuilder.ToImmutableAndFree(), externs); } private static NamespaceSymbol? BindNamespace(string namespaceName, NamespaceSymbol globalNamespace) { NamespaceSymbol? namespaceSymbol = globalNamespace; foreach (var name in namespaceName.Split('.')) { var members = namespaceSymbol.GetMembers(name); namespaceSymbol = (members.Length == 1) ? members[0] as NamespaceSymbol : null; if (namespaceSymbol is null) { break; } } return namespaceSymbol; } private static bool TryAddImport( string? alias, NamespaceOrTypeSymbol targetSymbol, ArrayBuilder<NamespaceOrTypeAndUsingDirective> usingsBuilder, ImmutableDictionary<string, AliasAndUsingDirective>.Builder usingAliases, InContainerBinder binder, ImportRecord importRecord) { if (alias == null) { usingsBuilder.Add(new NamespaceOrTypeAndUsingDirective(targetSymbol, usingDirective: null, dependencies: default)); } else { if (!TryParseIdentifierNameSyntax(alias, out var aliasSyntax)) { Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid alias '{alias}'"); return false; } var aliasSymbol = AliasSymbol.CreateCustomDebugInfoAlias(targetSymbol, aliasSyntax.Identifier, binder.ContainingMemberOrLambda, isExtern: false); usingAliases.Add(alias, new AliasAndUsingDirective(aliasSymbol, usingDirective: null)); } return true; } private static bool TryParseIdentifierNameSyntax(string name, [NotNullWhen(true)] out IdentifierNameSyntax? syntax) { if (name == MetadataReferenceProperties.GlobalAlias) { syntax = SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)); return true; } if (!SyntaxHelpers.TryParseDottedName(name, out var nameSyntax) || nameSyntax.Kind() != SyntaxKind.IdentifierName) { syntax = null; return false; } syntax = (IdentifierNameSyntax)nameSyntax; return true; } internal CommonMessageProvider MessageProvider { get { return Compilation.MessageProvider; } } private static DkmClrCompilationResultFlags GetLocalResultFlags(LocalSymbol local) { // CONSIDER: We might want to prevent the user from modifying pinned locals - // that's pretty dangerous. return local.IsConst ? DkmClrCompilationResultFlags.ReadOnlyResult : DkmClrCompilationResultFlags.None; } /// <summary> /// Generate the set of locals to use for binding. /// </summary> private static ImmutableArray<LocalSymbol> GetLocalsForBinding( ImmutableArray<LocalSymbol> locals, ImmutableArray<string> displayClassVariableNamesInOrder, ImmutableDictionary<string, DisplayClassVariable> displayClassVariables) { var builder = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var local in locals) { var name = local.Name; if (name == null) { continue; } if (GeneratedNameParser.GetKind(name) != GeneratedNameKind.None) { continue; } // Although Roslyn doesn't name synthesized locals unless they are well-known to EE, // Dev12 did so we need to skip them here. if (GeneratedNameParser.IsSynthesizedLocalName(name)) { continue; } builder.Add(local); } foreach (var variableName in displayClassVariableNamesInOrder) { var variable = displayClassVariables[variableName]; switch (variable.Kind) { case DisplayClassVariableKind.Local: case DisplayClassVariableKind.Parameter: builder.Add(new EEDisplayClassFieldLocalSymbol(variable)); break; } } return builder.ToImmutableAndFree(); } private static ImmutableArray<string> GetSourceMethodParametersInOrder( MethodSymbol method, MethodSymbol? sourceMethod) { var containingType = method.ContainingType; bool isIteratorOrAsyncMethod = IsDisplayClassType(containingType) && GeneratedNameParser.GetKind(containingType.Name) == GeneratedNameKind.StateMachineType; var parameterNamesInOrder = ArrayBuilder<string>.GetInstance(); // For version before .NET 4.5, we cannot find the sourceMethod properly: // The source method coincides with the original method in the case. // Therefore, for iterators and async state machines, we have to get parameters from the containingType. // This does not guarantee the proper order of parameters. if (isIteratorOrAsyncMethod && method == sourceMethod) { Debug.Assert(IsDisplayClassType(containingType)); foreach (var member in containingType.GetMembers()) { if (member.Kind != SymbolKind.Field) { continue; } var field = (FieldSymbol)member; var fieldName = field.Name; if (GeneratedNameParser.GetKind(fieldName) == GeneratedNameKind.None) { parameterNamesInOrder.Add(fieldName); } } } else { if (sourceMethod is object) { foreach (var p in sourceMethod.Parameters) { parameterNamesInOrder.Add(p.Name); } } } return parameterNamesInOrder.ToImmutableAndFree(); } /// <summary> /// Return a mapping of captured variables (parameters, locals, and /// "this") to locals. The mapping is needed to expose the original /// local identifiers (those from source) in the binder. /// </summary> private static void GetDisplayClassVariables( MethodSymbol method, ImmutableArray<LocalSymbol> locals, ImmutableSortedSet<int> inScopeHoistedLocalSlots, ImmutableArray<string> parameterNamesInOrder, out ImmutableArray<string> displayClassVariableNamesInOrder, out ImmutableDictionary<string, DisplayClassVariable> displayClassVariables) { // Calculate the shortest paths from locals to instances of display // classes. There should not be two instances of the same display // class immediately within any particular method. var displayClassInstances = ArrayBuilder<DisplayClassInstanceAndFields>.GetInstance(); foreach (var parameter in method.Parameters) { if (GeneratedNameParser.GetKind(parameter.Name) == GeneratedNameKind.TransparentIdentifier || IsDisplayClassParameter(parameter)) { var instance = new DisplayClassInstanceFromParameter(parameter); displayClassInstances.Add(new DisplayClassInstanceAndFields(instance)); } } if (IsDisplayClassType(method.ContainingType) && !method.IsStatic) { // Add "this" display class instance. var instance = new DisplayClassInstanceFromParameter(method.ThisParameter); displayClassInstances.Add(new DisplayClassInstanceAndFields(instance)); } var displayClassTypes = PooledHashSet<TypeSymbol>.GetInstance(); foreach (var instance in displayClassInstances) { displayClassTypes.Add(instance.Instance.Type); } // Find any additional display class instances. GetAdditionalDisplayClassInstances(displayClassTypes, displayClassInstances, startIndex: 0); // Add any display class instances from locals (these will contain any hoisted locals). // Locals are only added after finding all display class instances reachable from // parameters because locals may be null (temporary locals in async state machine // for instance) so we prefer parameters to locals. int startIndex = displayClassInstances.Count; foreach (var local in locals) { var name = local.Name; if (name != null && GeneratedNameParser.GetKind(name) == GeneratedNameKind.DisplayClassLocalOrField) { var localType = local.Type; if (localType is object && displayClassTypes.Add(localType)) { var instance = new DisplayClassInstanceFromLocal((EELocalSymbol)local); displayClassInstances.Add(new DisplayClassInstanceAndFields(instance)); } } } GetAdditionalDisplayClassInstances(displayClassTypes, displayClassInstances, startIndex); displayClassTypes.Free(); if (displayClassInstances.Any()) { var parameterNames = PooledHashSet<string>.GetInstance(); foreach (var name in parameterNamesInOrder) { parameterNames.Add(name); } // The locals are the set of all fields from the display classes. var displayClassVariableNamesInOrderBuilder = ArrayBuilder<string>.GetInstance(); var displayClassVariablesBuilder = PooledDictionary<string, DisplayClassVariable>.GetInstance(); foreach (var instance in displayClassInstances) { GetDisplayClassVariables( displayClassVariableNamesInOrderBuilder, displayClassVariablesBuilder, parameterNames, inScopeHoistedLocalSlots, instance); } displayClassVariableNamesInOrder = displayClassVariableNamesInOrderBuilder.ToImmutableAndFree(); displayClassVariables = displayClassVariablesBuilder.ToImmutableDictionary(); displayClassVariablesBuilder.Free(); parameterNames.Free(); } else { displayClassVariableNamesInOrder = ImmutableArray<string>.Empty; displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty; } displayClassInstances.Free(); } private static void GetAdditionalDisplayClassInstances( HashSet<TypeSymbol> displayClassTypes, ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances, int startIndex) { // Find any additional display class instances breadth first. for (int i = startIndex; i < displayClassInstances.Count; i++) { GetDisplayClassInstances(displayClassTypes, displayClassInstances, displayClassInstances[i]); } } private static void GetDisplayClassInstances( HashSet<TypeSymbol> displayClassTypes, ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances, DisplayClassInstanceAndFields instance) { // Display class instance. The display class fields are variables. foreach (var member in instance.Type.GetMembers()) { if (member.Kind != SymbolKind.Field) { continue; } var field = (FieldSymbol)member; var fieldType = field.Type; var fieldName = field.Name; TryParseGeneratedName(fieldName, out var fieldKind, out var part); switch (fieldKind) { case GeneratedNameKind.DisplayClassLocalOrField: case GeneratedNameKind.TransparentIdentifier: break; case GeneratedNameKind.AnonymousTypeField: RoslynDebug.AssertNotNull(part); if (GeneratedNameParser.GetKind(part) != GeneratedNameKind.TransparentIdentifier) { continue; } break; case GeneratedNameKind.ThisProxyField: if (GeneratedNameParser.GetKind(fieldType.Name) != GeneratedNameKind.LambdaDisplayClass) { continue; } // Async lambda case. break; default: continue; } Debug.Assert(!field.IsStatic); // A hoisted local that is itself a display class instance. if (displayClassTypes.Add(fieldType)) { var other = instance.FromField(field); displayClassInstances.Add(other); } } } /// <summary> /// Returns true if the parameter is a synthesized parameter representing /// a display class instance (used to pass hoisted symbols to local functions). /// </summary> private static bool IsDisplayClassParameter(ParameterSymbol parameter) { var type = parameter.Type; var result = type.Kind == SymbolKind.NamedType && IsDisplayClassType((NamedTypeSymbol)type); Debug.Assert(!result || parameter.MetadataName == ""); return result; } private static void GetDisplayClassVariables( ArrayBuilder<string> displayClassVariableNamesInOrderBuilder, Dictionary<string, DisplayClassVariable> displayClassVariablesBuilder, HashSet<string> parameterNames, ImmutableSortedSet<int> inScopeHoistedLocalSlots, DisplayClassInstanceAndFields instance) { // Display class instance. The display class fields are variables. foreach (var member in instance.Type.GetMembers()) { if (member.Kind != SymbolKind.Field) { continue; } var field = (FieldSymbol)member; var fieldName = field.Name; REPARSE: DisplayClassVariableKind variableKind; string variableName; TryParseGeneratedName(fieldName, out var fieldKind, out var part); switch (fieldKind) { case GeneratedNameKind.AnonymousTypeField: RoslynDebug.AssertNotNull(part); Debug.Assert(fieldName == field.Name); // This only happens once. fieldName = part; goto REPARSE; case GeneratedNameKind.TransparentIdentifier: // A transparent identifier (field) in an anonymous type synthesized for a transparent identifier. Debug.Assert(!field.IsStatic); continue; case GeneratedNameKind.DisplayClassLocalOrField: // A local that is itself a display class instance. Debug.Assert(!field.IsStatic); continue; case GeneratedNameKind.HoistedLocalField: RoslynDebug.AssertNotNull(part); // Filter out hoisted locals that are known to be out-of-scope at the current IL offset. // Hoisted locals with invalid indices will be included since more information is better // than less in error scenarios. if (GeneratedNameParser.TryParseSlotIndex(fieldName, out int slotIndex) && !inScopeHoistedLocalSlots.Contains(slotIndex)) { continue; } variableName = part; variableKind = DisplayClassVariableKind.Local; Debug.Assert(!field.IsStatic); break; case GeneratedNameKind.ThisProxyField: // A reference to "this". variableName = ""; // Should not be referenced by name. variableKind = DisplayClassVariableKind.This; Debug.Assert(!field.IsStatic); break; case GeneratedNameKind.None: // A reference to a parameter or local. variableName = fieldName; variableKind = parameterNames.Contains(variableName) ? DisplayClassVariableKind.Parameter : DisplayClassVariableKind.Local; Debug.Assert(!field.IsStatic); break; default: continue; } if (displayClassVariablesBuilder.ContainsKey(variableName)) { // Only expecting duplicates for async state machine // fields (that should be at the top-level). Debug.Assert(displayClassVariablesBuilder[variableName].DisplayClassFields.Count() == 1); if (!instance.Fields.Any()) { // Prefer parameters over locals. Debug.Assert(instance.Instance is DisplayClassInstanceFromLocal); } else { Debug.Assert(instance.Fields.Count() >= 1); // greater depth Debug.Assert(variableKind == DisplayClassVariableKind.Parameter || variableKind == DisplayClassVariableKind.This); if (variableKind == DisplayClassVariableKind.Parameter && GeneratedNameParser.GetKind(instance.Type.Name) == GeneratedNameKind.LambdaDisplayClass) { displayClassVariablesBuilder[variableName] = instance.ToVariable(variableName, variableKind, field); } } } else if (variableKind != DisplayClassVariableKind.This || GeneratedNameParser.GetKind(instance.Type.ContainingType.Name) != GeneratedNameKind.LambdaDisplayClass) { // In async lambdas, the hoisted "this" field in the state machine type will point to the display class instance, if there is one. // In such cases, we want to add the display class "this" to the map instead (or nothing, if it lacks one). displayClassVariableNamesInOrderBuilder.Add(variableName); displayClassVariablesBuilder.Add(variableName, instance.ToVariable(variableName, variableKind, field)); } } } private static void TryParseGeneratedName(string name, out GeneratedNameKind kind, out string? part) { _ = GeneratedNameParser.TryParseGeneratedName(name, out kind, out int openBracketOffset, out int closeBracketOffset); switch (kind) { case GeneratedNameKind.AnonymousTypeField: case GeneratedNameKind.HoistedLocalField: part = name.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1); break; default: part = null; break; } } private static bool IsDisplayClassType(TypeSymbol type) { switch (GeneratedNameParser.GetKind(type.Name)) { case GeneratedNameKind.LambdaDisplayClass: case GeneratedNameKind.StateMachineType: return true; default: return false; } } internal static DisplayClassVariable GetThisProxy(ImmutableDictionary<string, DisplayClassVariable> displayClassVariables) { return displayClassVariables.Values.FirstOrDefault(v => v.Kind == DisplayClassVariableKind.This); } private static NamedTypeSymbol GetNonDisplayClassContainer(NamedTypeSymbol type) { // 1) Display class and state machine types are always nested within the types // that use them (so that they can access private members of those types). // 2) The native compiler used to produce nested display classes for nested lambdas, // so we may have to walk out more than one level. while (IsDisplayClassType(type)) { type = type.ContainingType!; } return type; } /// <summary> /// Identifies the method in which binding should occur. /// </summary> /// <param name="candidateSubstitutedSourceMethod"> /// The symbol of the method that is currently on top of the callstack, with /// EE type parameters substituted in place of the original type parameters. /// </param> /// <param name="sourceMethodMustBeInstance"> /// True if "this" is available via a display class in the current context. /// </param> /// <returns> /// If <paramref name="candidateSubstitutedSourceMethod"/> is compiler-generated, /// then we will attempt to determine which user-defined method caused it to be /// generated. For example, if <paramref name="candidateSubstitutedSourceMethod"/> /// is a state machine MoveNext method, then we will try to find the iterator or /// async method for which it was generated. If we are able to find the original /// method, then we will substitute in the EE type parameters. Otherwise, we will /// return <paramref name="candidateSubstitutedSourceMethod"/>. /// </returns> /// <remarks> /// In the event that the original method is overloaded, we may not be able to determine /// which overload actually corresponds to the state machine. In particular, we do not /// have information about the signature of the original method (i.e. number of parameters, /// parameter types and ref-kinds, return type). However, we conjecture that this /// level of uncertainty is acceptable, since parameters are managed by a separate binder /// in the synthesized binder chain and we have enough information to check the other method /// properties that are used during binding (e.g. static-ness, generic arity, type parameter /// constraints). /// </remarks> internal static MethodSymbol GetSubstitutedSourceMethod( MethodSymbol candidateSubstitutedSourceMethod, bool sourceMethodMustBeInstance) { var candidateSubstitutedSourceType = candidateSubstitutedSourceMethod.ContainingType; string? desiredMethodName; if (GeneratedNameParser.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceType.Name, GeneratedNameKind.StateMachineType, out desiredMethodName) || GeneratedNameParser.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceMethod.Name, GeneratedNameKind.LambdaMethod, out desiredMethodName) || GeneratedNameParser.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceMethod.Name, GeneratedNameKind.LocalFunction, out desiredMethodName)) { // We could be in the MoveNext method of an async lambda. string? tempMethodName; if (GeneratedNameParser.TryParseSourceMethodNameFromGeneratedName(desiredMethodName, GeneratedNameKind.LambdaMethod, out tempMethodName) || GeneratedNameParser.TryParseSourceMethodNameFromGeneratedName(desiredMethodName, GeneratedNameKind.LocalFunction, out tempMethodName)) { desiredMethodName = tempMethodName; var containing = candidateSubstitutedSourceType.ContainingType; RoslynDebug.AssertNotNull(containing); if (GeneratedNameParser.GetKind(containing.Name) == GeneratedNameKind.LambdaDisplayClass) { candidateSubstitutedSourceType = containing; sourceMethodMustBeInstance = candidateSubstitutedSourceType.MemberNames.Select(GeneratedNameParser.GetKind).Contains(GeneratedNameKind.ThisProxyField); } } var desiredTypeParameters = candidateSubstitutedSourceType.OriginalDefinition.TypeParameters; // Type containing the original iterator, async, or lambda-containing method. var substitutedSourceType = GetNonDisplayClassContainer(candidateSubstitutedSourceType); foreach (var candidateMethod in substitutedSourceType.GetMembers().OfType<MethodSymbol>()) { if (IsViableSourceMethod(candidateMethod, desiredMethodName, desiredTypeParameters, sourceMethodMustBeInstance)) { return desiredTypeParameters.Length == 0 ? candidateMethod : candidateMethod.Construct(candidateSubstitutedSourceType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics); } } Debug.Fail("Why didn't we find a substituted source method for " + candidateSubstitutedSourceMethod + "?"); } return candidateSubstitutedSourceMethod; } private static bool IsViableSourceMethod( MethodSymbol candidateMethod, string desiredMethodName, ImmutableArray<TypeParameterSymbol> desiredTypeParameters, bool desiredMethodMustBeInstance) { return !candidateMethod.IsAbstract && !(desiredMethodMustBeInstance && candidateMethod.IsStatic) && candidateMethod.Name == desiredMethodName && HaveSameConstraints(candidateMethod.TypeParameters, desiredTypeParameters); } private static bool HaveSameConstraints(ImmutableArray<TypeParameterSymbol> candidateTypeParameters, ImmutableArray<TypeParameterSymbol> desiredTypeParameters) { int arity = candidateTypeParameters.Length; if (arity != desiredTypeParameters.Length) { return false; } if (arity == 0) { return true; } var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity); var candidateTypeMap = new TypeMap(candidateTypeParameters, indexedTypeParameters, allowAlpha: true); var desiredTypeMap = new TypeMap(desiredTypeParameters, indexedTypeParameters, allowAlpha: true); return MemberSignatureComparer.HaveSameConstraints(candidateTypeParameters, candidateTypeMap, desiredTypeParameters, desiredTypeMap); } [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] private readonly struct DisplayClassInstanceAndFields { internal readonly DisplayClassInstance Instance; internal readonly ConsList<FieldSymbol> Fields; internal DisplayClassInstanceAndFields(DisplayClassInstance instance) : this(instance, ConsList<FieldSymbol>.Empty) { Debug.Assert(IsDisplayClassType(instance.Type) || GeneratedNameParser.GetKind(instance.Type.Name) == GeneratedNameKind.AnonymousType); } private DisplayClassInstanceAndFields(DisplayClassInstance instance, ConsList<FieldSymbol> fields) { Instance = instance; Fields = fields; } internal TypeSymbol Type => Fields.Any() ? Fields.Head.Type : Instance.Type; internal int Depth => Fields.Count(); internal DisplayClassInstanceAndFields FromField(FieldSymbol field) { Debug.Assert(IsDisplayClassType(field.Type) || GeneratedNameParser.GetKind(field.Type.Name) == GeneratedNameKind.AnonymousType); return new DisplayClassInstanceAndFields(Instance, Fields.Prepend(field)); } internal DisplayClassVariable ToVariable(string name, DisplayClassVariableKind kind, FieldSymbol field) { return new DisplayClassVariable(name, kind, Instance, Fields.Prepend(field)); } private string GetDebuggerDisplay() { return Instance.GetDebuggerDisplay(Fields); } } } }
// Licensed to the .NET Foundation under one or more 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.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed class CompilationContext { internal readonly CSharpCompilation Compilation; internal readonly Binder NamespaceBinder; // Internal for test purposes. private readonly MethodSymbol _currentFrame; private readonly ImmutableArray<LocalSymbol> _locals; private readonly ImmutableDictionary<string, DisplayClassVariable> _displayClassVariables; private readonly ImmutableArray<string> _sourceMethodParametersInOrder; private readonly ImmutableArray<LocalSymbol> _localsForBinding; private readonly bool _methodNotType; /// <summary> /// Create a context to compile expressions within a method scope. /// </summary> internal CompilationContext( CSharpCompilation compilation, MethodSymbol currentFrame, MethodSymbol? currentSourceMethod, ImmutableArray<LocalSymbol> locals, ImmutableSortedSet<int> inScopeHoistedLocalSlots, MethodDebugInfo<TypeSymbol, LocalSymbol> methodDebugInfo) { _currentFrame = currentFrame; _methodNotType = !locals.IsDefault; // NOTE: Since this is done within CompilationContext, it will not be cached. // CONSIDER: The values should be the same everywhere in the module, so they // could be cached. // (Catch: what happens in a type context without a method def?) Compilation = GetCompilationWithExternAliases(compilation, methodDebugInfo.ExternAliasRecords); // Each expression compile should use a unique compilation // to ensure expression-specific synthesized members can be // added (anonymous types, for instance). Debug.Assert(Compilation != compilation); NamespaceBinder = CreateBinderChain( Compilation, currentFrame.ContainingNamespace, methodDebugInfo.ImportRecordGroups); if (_methodNotType) { _locals = locals; _sourceMethodParametersInOrder = GetSourceMethodParametersInOrder(currentFrame, currentSourceMethod); GetDisplayClassVariables( currentFrame, _locals, inScopeHoistedLocalSlots, _sourceMethodParametersInOrder, out var displayClassVariableNamesInOrder, out _displayClassVariables); Debug.Assert(displayClassVariableNamesInOrder.Length == _displayClassVariables.Count); _localsForBinding = GetLocalsForBinding(_locals, displayClassVariableNamesInOrder, _displayClassVariables); } else { _locals = ImmutableArray<LocalSymbol>.Empty; _displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty; _localsForBinding = ImmutableArray<LocalSymbol>.Empty; } // Assert that the cheap check for "this" is equivalent to the expensive check for "this". Debug.Assert( (GetThisProxy(_displayClassVariables) != null) == _displayClassVariables.Values.Any(v => v.Kind == DisplayClassVariableKind.This)); } internal bool TryCompileExpressions( ImmutableArray<CSharpSyntaxNode> syntaxNodes, string typeNameBase, string methodName, DiagnosticBag diagnostics, [NotNullWhen(true)] out CommonPEModuleBuilder? module) { // Create a separate synthesized type for each evaluation method. // (Necessary for VB in particular since the EENamedTypeSymbol.Locations // is tied to the expression syntax in VB.) var synthesizedTypes = syntaxNodes.SelectAsArray( (syntax, i, _) => (NamedTypeSymbol)CreateSynthesizedType(syntax, typeNameBase + i, methodName, ImmutableArray<Alias>.Empty), arg: (object?)null); if (synthesizedTypes.Length == 0) { module = null; return false; } module = CreateModuleBuilder( Compilation, additionalTypes: synthesizedTypes, testData: null, diagnostics: diagnostics); Compilation.Compile( module, emittingPdb: false, diagnostics: diagnostics, filterOpt: null, CancellationToken.None); return !diagnostics.HasAnyErrors(); } internal bool TryCompileExpression( CSharpSyntaxNode syntax, string typeName, string methodName, ImmutableArray<Alias> aliases, CompilationTestData? testData, DiagnosticBag diagnostics, [NotNullWhen(true)] out CommonPEModuleBuilder? module, [NotNullWhen(true)] out EEMethodSymbol? synthesizedMethod) { var synthesizedType = CreateSynthesizedType(syntax, typeName, methodName, aliases); module = CreateModuleBuilder( Compilation, additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType), testData, diagnostics); Compilation.Compile( module, emittingPdb: false, diagnostics, filterOpt: null, CancellationToken.None); if (diagnostics.HasAnyErrors()) { module = null; synthesizedMethod = null; return false; } synthesizedMethod = GetSynthesizedMethod(synthesizedType); return true; } private EENamedTypeSymbol CreateSynthesizedType( CSharpSyntaxNode syntax, string typeName, string methodName, ImmutableArray<Alias> aliases) { var objectType = Compilation.GetSpecialType(SpecialType.System_Object); var synthesizedType = new EENamedTypeSymbol( Compilation.SourceModule.GlobalNamespace, objectType, syntax, _currentFrame, typeName, methodName, this, (EEMethodSymbol method, DiagnosticBag diags, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { var hasDisplayClassThis = GetThisProxy(_displayClassVariables) != null; var binder = ExtendBinderChain( syntax, aliases, method, NamespaceBinder, hasDisplayClassThis, _methodNotType, out declaredLocals); return (syntax is StatementSyntax statementSyntax) ? BindStatement(binder, statementSyntax, diags, out properties) : BindExpression(binder, (ExpressionSyntax)syntax, diags, out properties); }); return synthesizedType; } internal bool TryCompileAssignment( ExpressionSyntax syntax, string typeName, string methodName, ImmutableArray<Alias> aliases, CompilationTestData? testData, DiagnosticBag diagnostics, [NotNullWhen(true)] out CommonPEModuleBuilder? module, [NotNullWhen(true)] out EEMethodSymbol? synthesizedMethod) { var objectType = Compilation.GetSpecialType(SpecialType.System_Object); var synthesizedType = new EENamedTypeSymbol( Compilation.SourceModule.GlobalNamespace, objectType, syntax, _currentFrame, typeName, methodName, this, (EEMethodSymbol method, DiagnosticBag diags, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { var hasDisplayClassThis = GetThisProxy(_displayClassVariables) != null; var binder = ExtendBinderChain( syntax, aliases, method, NamespaceBinder, hasDisplayClassThis, methodNotType: true, out declaredLocals); properties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect); return BindAssignment(binder, syntax, diags); }); module = CreateModuleBuilder( Compilation, additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType), testData, diagnostics); Compilation.Compile( module, emittingPdb: false, diagnostics, filterOpt: null, CancellationToken.None); if (diagnostics.HasAnyErrors()) { module = null; synthesizedMethod = null; return false; } synthesizedMethod = GetSynthesizedMethod(synthesizedType); return true; } private static EEMethodSymbol GetSynthesizedMethod(EENamedTypeSymbol synthesizedType) => (EEMethodSymbol)synthesizedType.Methods[0]; private static string GetNextMethodName(ArrayBuilder<MethodSymbol> builder) => "<>m" + builder.Count; /// <summary> /// Generate a class containing methods that represent /// the set of arguments and locals at the current scope. /// </summary> internal CommonPEModuleBuilder? CompileGetLocals( string typeName, ArrayBuilder<LocalAndMethod> localBuilder, bool argumentsOnly, ImmutableArray<Alias> aliases, CompilationTestData? testData, DiagnosticBag diagnostics) { var objectType = Compilation.GetSpecialType(SpecialType.System_Object); var allTypeParameters = _currentFrame.GetAllTypeParameters(); var additionalTypes = ArrayBuilder<NamedTypeSymbol>.GetInstance(); EENamedTypeSymbol? typeVariablesType = null; if (!argumentsOnly && allTypeParameters.Length > 0) { // Generate a generic type with matching type parameters. // A null instance of the type will be used to represent the // "Type variables" local. typeVariablesType = new EENamedTypeSymbol( Compilation.SourceModule.GlobalNamespace, objectType, _currentFrame, ExpressionCompilerConstants.TypeVariablesClassName, (m, t) => ImmutableArray.Create<MethodSymbol>(new EEConstructorSymbol(t)), allTypeParameters, (t1, t2) => allTypeParameters.SelectAsArray((tp, i, t) => (TypeParameterSymbol)new SimpleTypeParameterSymbol(t, i, tp.Name), t2)); additionalTypes.Add(typeVariablesType); } var synthesizedType = new EENamedTypeSymbol( Compilation.SourceModule.GlobalNamespace, objectType, _currentFrame, typeName, (m, container) => { var methodBuilder = ArrayBuilder<MethodSymbol>.GetInstance(); if (!argumentsOnly) { // Pseudo-variables: $exception, $ReturnValue, etc. if (aliases.Length > 0) { var sourceAssembly = Compilation.SourceAssembly; var typeNameDecoder = new EETypeNameDecoder(Compilation, (PEModuleSymbol)_currentFrame.ContainingModule); foreach (var alias in aliases) { if (alias.IsReturnValueWithoutIndex()) { Debug.Assert(aliases.Count(a => a.Kind == DkmClrAliasKind.ReturnValue) > 1); continue; } var local = PlaceholderLocalSymbol.Create( typeNameDecoder, _currentFrame, sourceAssembly, alias); // Skip pseudo-variables with errors. if (local.HasUseSiteError) { continue; } var methodName = GetNextMethodName(methodBuilder); var syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken)); var aliasMethod = CreateMethod( container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diags, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { declaredLocals = ImmutableArray<LocalSymbol>.Empty; var expression = new BoundLocal(syntax, local, constantValueOpt: null, type: local.Type); properties = default; return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; }); var flags = local.IsWritableVariable ? DkmClrCompilationResultFlags.None : DkmClrCompilationResultFlags.ReadOnlyResult; localBuilder.Add(MakeLocalAndMethod(local, aliasMethod, flags)); methodBuilder.Add(aliasMethod); } } // "this" for non-static methods that are not display class methods or // display class methods where the display class contains "<>4__this". if (!m.IsStatic && !IsDisplayClassType(m.ContainingType) || GetThisProxy(_displayClassVariables) != null) { var methodName = GetNextMethodName(methodBuilder); var method = GetThisMethod(container, methodName); localBuilder.Add(new CSharpLocalAndMethod("this", "this", method, DkmClrCompilationResultFlags.None)); // Note: writable in dev11. methodBuilder.Add(method); } } var itemsAdded = PooledHashSet<string>.GetInstance(); // Method parameters int parameterIndex = m.IsStatic ? 0 : 1; foreach (var parameter in m.Parameters) { var parameterName = parameter.Name; if (GeneratedNameParser.GetKind(parameterName) == GeneratedNameKind.None && !IsDisplayClassParameter(parameter)) { itemsAdded.Add(parameterName); AppendParameterAndMethod(localBuilder, methodBuilder, parameter, container, parameterIndex); } parameterIndex++; } // In case of iterator or async state machine, the 'm' method has no parameters // but the source method can have parameters to iterate over. if (itemsAdded.Count == 0 && _sourceMethodParametersInOrder.Length != 0) { var localsDictionary = PooledDictionary<string, (LocalSymbol, int)>.GetInstance(); int localIndex = 0; foreach (var local in _localsForBinding) { localsDictionary.Add(local.Name, (local, localIndex)); localIndex++; } foreach (var argumentName in _sourceMethodParametersInOrder) { (LocalSymbol local, int localIndex) localSymbolAndIndex; if (localsDictionary.TryGetValue(argumentName, out localSymbolAndIndex)) { itemsAdded.Add(argumentName); var local = localSymbolAndIndex.local; AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localSymbolAndIndex.localIndex, GetLocalResultFlags(local)); } } localsDictionary.Free(); } if (!argumentsOnly) { // Locals which were not added as parameters or parameters of the source method. int localIndex = 0; foreach (var local in _localsForBinding) { if (!itemsAdded.Contains(local.Name)) { AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localIndex, GetLocalResultFlags(local)); } localIndex++; } // "Type variables". if (typeVariablesType is object) { var methodName = GetNextMethodName(methodBuilder); var returnType = typeVariablesType.Construct(allTypeParameters.Cast<TypeParameterSymbol, TypeSymbol>()); var method = GetTypeVariablesMethod(container, methodName, returnType); localBuilder.Add(new CSharpLocalAndMethod( ExpressionCompilerConstants.TypeVariablesLocalName, ExpressionCompilerConstants.TypeVariablesLocalName, method, DkmClrCompilationResultFlags.ReadOnlyResult)); methodBuilder.Add(method); } } itemsAdded.Free(); return methodBuilder.ToImmutableAndFree(); }); additionalTypes.Add(synthesizedType); var module = CreateModuleBuilder( Compilation, additionalTypes.ToImmutableAndFree(), testData, diagnostics); RoslynDebug.AssertNotNull(module); Compilation.Compile( module, emittingPdb: false, diagnostics, filterOpt: null, CancellationToken.None); return diagnostics.HasAnyErrors() ? null : module; } private void AppendLocalAndMethod( ArrayBuilder<LocalAndMethod> localBuilder, ArrayBuilder<MethodSymbol> methodBuilder, LocalSymbol local, EENamedTypeSymbol container, int localIndex, DkmClrCompilationResultFlags resultFlags) { var methodName = GetNextMethodName(methodBuilder); var method = GetLocalMethod(container, methodName, local.Name, localIndex); localBuilder.Add(MakeLocalAndMethod(local, method, resultFlags)); methodBuilder.Add(method); } private void AppendParameterAndMethod( ArrayBuilder<LocalAndMethod> localBuilder, ArrayBuilder<MethodSymbol> methodBuilder, ParameterSymbol parameter, EENamedTypeSymbol container, int parameterIndex) { // Note: The native EE doesn't do this, but if we don't escape keyword identifiers, // the ResultProvider needs to be able to disambiguate cases like "this" and "@this", // which it can't do correctly without semantic information. var name = SyntaxHelpers.EscapeKeywordIdentifiers(parameter.Name); var methodName = GetNextMethodName(methodBuilder); var method = GetParameterMethod(container, methodName, name, parameterIndex); localBuilder.Add(new CSharpLocalAndMethod(name, name, method, DkmClrCompilationResultFlags.None)); methodBuilder.Add(method); } private static LocalAndMethod MakeLocalAndMethod(LocalSymbol local, MethodSymbol method, DkmClrCompilationResultFlags flags) { // Note: The native EE doesn't do this, but if we don't escape keyword identifiers, // the ResultProvider needs to be able to disambiguate cases like "this" and "@this", // which it can't do correctly without semantic information. var escapedName = SyntaxHelpers.EscapeKeywordIdentifiers(local.Name); var displayName = (local as PlaceholderLocalSymbol)?.DisplayName ?? escapedName; return new CSharpLocalAndMethod(escapedName, displayName, method, flags); } private static EEAssemblyBuilder CreateModuleBuilder( CSharpCompilation compilation, ImmutableArray<NamedTypeSymbol> additionalTypes, CompilationTestData? testData, DiagnosticBag diagnostics) { // Each assembly must have a unique name. var emitOptions = new EmitOptions(outputNameOverride: ExpressionCompilerUtilities.GenerateUniqueName()); string? runtimeMetadataVersion = compilation.GetRuntimeMetadataVersion(emitOptions, diagnostics); var serializationProperties = compilation.ConstructModuleSerializationProperties(emitOptions, runtimeMetadataVersion); return new EEAssemblyBuilder( compilation.SourceAssembly, emitOptions, serializationProperties, additionalTypes, contextType => GetNonDisplayClassContainer(((EENamedTypeSymbol)contextType).SubstitutedSourceType), testData); } internal EEMethodSymbol CreateMethod( EENamedTypeSymbol container, string methodName, CSharpSyntaxNode syntax, GenerateMethodBody generateMethodBody) { return new EEMethodSymbol( container, methodName, syntax.Location, _currentFrame, _locals, _localsForBinding, _displayClassVariables, generateMethodBody); } private EEMethodSymbol GetLocalMethod(EENamedTypeSymbol container, string methodName, string localName, int localIndex) { var syntax = SyntaxFactory.IdentifierName(localName); return CreateMethod(container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { declaredLocals = ImmutableArray<LocalSymbol>.Empty; var local = method.LocalsForBinding[localIndex]; var expression = new BoundLocal(syntax, local, constantValueOpt: local.GetConstantValue(null, null, new BindingDiagnosticBag(diagnostics)), type: local.Type); properties = default; return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; }); } private EEMethodSymbol GetParameterMethod(EENamedTypeSymbol container, string methodName, string parameterName, int parameterIndex) { var syntax = SyntaxFactory.IdentifierName(parameterName); return CreateMethod(container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { declaredLocals = ImmutableArray<LocalSymbol>.Empty; var parameter = method.Parameters[parameterIndex]; var expression = new BoundParameter(syntax, parameter); properties = default; return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; }); } private EEMethodSymbol GetThisMethod(EENamedTypeSymbol container, string methodName) { var syntax = SyntaxFactory.ThisExpression(); return CreateMethod(container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { declaredLocals = ImmutableArray<LocalSymbol>.Empty; var expression = new BoundThisReference(syntax, GetNonDisplayClassContainer(container.SubstitutedSourceType)); properties = default; return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; }); } private EEMethodSymbol GetTypeVariablesMethod(EENamedTypeSymbol container, string methodName, NamedTypeSymbol typeVariablesType) { var syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken)); return CreateMethod(container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { declaredLocals = ImmutableArray<LocalSymbol>.Empty; var type = method.TypeMap.SubstituteNamedType(typeVariablesType); var expression = new BoundObjectCreationExpression(syntax, type.InstanceConstructors[0]); var statement = new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; properties = default; return statement; }); } private static BoundStatement? BindExpression(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics, out ResultProperties resultProperties) { var flags = DkmClrCompilationResultFlags.None; var bindingDiagnostics = new BindingDiagnosticBag(diagnostics); // In addition to C# expressions, the native EE also supports // type names which are bound to a representation of the type // (but not System.Type) that the user can expand to see the // base type. Instead, we only allow valid C# expressions. var expression = IsDeconstruction(syntax) ? binder.BindDeconstruction((AssignmentExpressionSyntax)syntax, bindingDiagnostics, resultIsUsedOverride: true) : binder.BindRValueWithoutTargetType(syntax, bindingDiagnostics); if (diagnostics.HasAnyErrors()) { resultProperties = default; return null; } try { if (MayHaveSideEffectsVisitor.MayHaveSideEffects(expression)) { flags |= DkmClrCompilationResultFlags.PotentialSideEffect; } } catch (BoundTreeVisitor.CancelledByStackGuardException ex) { ex.AddAnError(diagnostics); resultProperties = default; return null; } var expressionType = expression.Type; if (expressionType is null) { expression = binder.CreateReturnConversion( syntax, bindingDiagnostics, expression, RefKind.None, binder.Compilation.GetSpecialType(SpecialType.System_Object)); if (diagnostics.HasAnyErrors()) { resultProperties = default; return null; } } else if (expressionType.SpecialType == SpecialType.System_Void) { flags |= DkmClrCompilationResultFlags.ReadOnlyResult; Debug.Assert(expression.ConstantValue == null); resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, isConstant: false); return new BoundExpressionStatement(syntax, expression) { WasCompilerGenerated = true }; } else if (expressionType.SpecialType == SpecialType.System_Boolean) { flags |= DkmClrCompilationResultFlags.BoolResult; } if (!IsAssignableExpression(binder, expression)) { flags |= DkmClrCompilationResultFlags.ReadOnlyResult; } resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, expression.ConstantValue != null); return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; } private static bool IsDeconstruction(ExpressionSyntax syntax) { if (syntax.Kind() != SyntaxKind.SimpleAssignmentExpression) { return false; } var node = (AssignmentExpressionSyntax)syntax; return node.Left.Kind() == SyntaxKind.TupleExpression || node.Left.Kind() == SyntaxKind.DeclarationExpression; } private static BoundStatement BindStatement(Binder binder, StatementSyntax syntax, DiagnosticBag diagnostics, out ResultProperties properties) { properties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); return binder.BindStatement(syntax, new BindingDiagnosticBag(diagnostics)); } private static bool IsAssignableExpression(Binder binder, BoundExpression expression) { var result = binder.CheckValueKind(expression.Syntax, expression, Binder.BindValueKind.Assignable, checkingReceiver: false, BindingDiagnosticBag.Discarded); return result; } private static BoundStatement? BindAssignment(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics) { var expression = binder.BindValue(syntax, new BindingDiagnosticBag(diagnostics), Binder.BindValueKind.RValue); if (diagnostics.HasAnyErrors()) { return null; } return new BoundExpressionStatement(expression.Syntax, expression) { WasCompilerGenerated = true }; } private static Binder CreateBinderChain( CSharpCompilation compilation, NamespaceSymbol @namespace, ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups) { var stack = ArrayBuilder<string>.GetInstance(); while (@namespace is object) { stack.Push(@namespace.Name); @namespace = @namespace.ContainingNamespace; } Binder binder = new BuckStopsHereBinder(compilation); var hasImports = !importRecordGroups.IsDefaultOrEmpty; var numImportStringGroups = hasImports ? importRecordGroups.Length : 0; var currentStringGroup = numImportStringGroups - 1; // PERF: We used to call compilation.GetCompilationNamespace on every iteration, // but that involved walking up to the global namespace, which we have to do // anyway. Instead, we'll inline the functionality into our own walk of the // namespace chain. @namespace = compilation.GlobalNamespace; while (stack.Count > 0) { var namespaceName = stack.Pop(); if (namespaceName.Length > 0) { // We're re-getting the namespace, rather than using the one containing // the current frame method, because we want the merged namespace. @namespace = @namespace.GetNestedNamespace(namespaceName); RoslynDebug.AssertNotNull(@namespace); } else { Debug.Assert((object)@namespace == compilation.GlobalNamespace); } if (hasImports) { if (currentStringGroup < 0) { Debug.WriteLine($"No import string group for namespace '{@namespace}'"); break; } var importsBinder = new InContainerBinder(@namespace, binder); Imports imports = BuildImports(compilation, importRecordGroups[currentStringGroup], importsBinder); currentStringGroup--; binder = WithExternAndUsingAliasesBinder.Create(imports.ExternAliases, imports.UsingAliases, WithUsingNamespacesAndTypesBinder.Create(imports.Usings, binder)); } binder = new InContainerBinder(@namespace, binder); } stack.Free(); if (currentStringGroup >= 0) { // CONSIDER: We could lump these into the outermost namespace. It's probably not worthwhile since // the usings are already for the wrong method. Debug.WriteLine($"Found {currentStringGroup + 1} import string groups without corresponding namespaces"); } return binder; } private static CSharpCompilation GetCompilationWithExternAliases(CSharpCompilation compilation, ImmutableArray<ExternAliasRecord> externAliasRecords) { if (externAliasRecords.IsDefaultOrEmpty) { return compilation.Clone(); } var updatedReferences = ArrayBuilder<MetadataReference>.GetInstance(); var assembliesAndModulesBuilder = ArrayBuilder<Symbol>.GetInstance(); foreach (var reference in compilation.References) { updatedReferences.Add(reference); assembliesAndModulesBuilder.Add(compilation.GetAssemblyOrModuleSymbol(reference)!); } Debug.Assert(assembliesAndModulesBuilder.Count == updatedReferences.Count); var assembliesAndModules = assembliesAndModulesBuilder.ToImmutableAndFree(); foreach (var externAliasRecord in externAliasRecords) { var targetAssembly = externAliasRecord.TargetAssembly as AssemblySymbol; int index; if (targetAssembly != null) { index = assembliesAndModules.IndexOf(targetAssembly); } else { index = IndexOfMatchingAssembly((AssemblyIdentity)externAliasRecord.TargetAssembly, assembliesAndModules, compilation.Options.AssemblyIdentityComparer); } if (index < 0) { Debug.WriteLine($"Unable to find corresponding assembly reference for extern alias '{externAliasRecord}'"); continue; } var externAlias = externAliasRecord.Alias; var assemblyReference = updatedReferences[index]; var oldAliases = assemblyReference.Properties.Aliases; var newAliases = oldAliases.IsEmpty ? ImmutableArray.Create(MetadataReferenceProperties.GlobalAlias, externAlias) : oldAliases.Concat(ImmutableArray.Create(externAlias)); // NOTE: Dev12 didn't emit custom debug info about "global", so we don't have // a good way to distinguish between a module aliased with both (e.g.) "X" and // "global" and a module aliased with only "X". As in Dev12, we assume that // "global" is a valid alias to remain at least as permissive as source. // NOTE: In the event that this introduces ambiguities between two assemblies // (e.g. because one was "global" in source and the other was "X"), it should be // possible to disambiguate as long as each assembly has a distinct extern alias, // not necessarily used in source. Debug.Assert(newAliases.Contains(MetadataReferenceProperties.GlobalAlias)); // Replace the value in the map with the updated reference. updatedReferences[index] = assemblyReference.WithAliases(newAliases); } compilation = compilation.WithReferences(updatedReferences); updatedReferences.Free(); return compilation; } private static int IndexOfMatchingAssembly(AssemblyIdentity referenceIdentity, ImmutableArray<Symbol> assembliesAndModules, AssemblyIdentityComparer assemblyIdentityComparer) { for (int i = 0; i < assembliesAndModules.Length; i++) { if (assembliesAndModules[i] is AssemblySymbol assembly && assemblyIdentityComparer.ReferenceMatchesDefinition(referenceIdentity, assembly.Identity)) { return i; } } return -1; } private static Binder ExtendBinderChain( CSharpSyntaxNode syntax, ImmutableArray<Alias> aliases, EEMethodSymbol method, Binder binder, bool hasDisplayClassThis, bool methodNotType, out ImmutableArray<LocalSymbol> declaredLocals) { var substitutedSourceMethod = GetSubstitutedSourceMethod(method.SubstitutedSourceMethod, hasDisplayClassThis); var substitutedSourceType = substitutedSourceMethod.ContainingType; var stack = ArrayBuilder<NamedTypeSymbol>.GetInstance(); for (var type = substitutedSourceType; type is object; type = type.ContainingType) { stack.Add(type); } while (stack.Count > 0) { substitutedSourceType = stack.Pop(); binder = new InContainerBinder(substitutedSourceType, binder); if (substitutedSourceType.Arity > 0) { binder = new WithTypeArgumentsBinder(substitutedSourceType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics, binder); } } stack.Free(); if (substitutedSourceMethod.Arity > 0) { binder = new WithTypeArgumentsBinder(substitutedSourceMethod.TypeArgumentsWithAnnotations, binder); } // Method locals and parameters shadow pseudo-variables. // That is why we place PlaceholderLocalBinder and ExecutableCodeBinder before EEMethodBinder. if (methodNotType) { var typeNameDecoder = new EETypeNameDecoder(binder.Compilation, (PEModuleSymbol)substitutedSourceMethod.ContainingModule); binder = new PlaceholderLocalBinder( syntax, aliases, method, typeNameDecoder, binder); } binder = new EEMethodBinder(method, substitutedSourceMethod, binder); if (methodNotType) { binder = new SimpleLocalScopeBinder(method.LocalsForBinding, binder); } Binder? actualRootBinder = null; SyntaxNode? declaredLocalsScopeDesignator = null; var executableBinder = new ExecutableCodeBinder(syntax, substitutedSourceMethod, binder, (rootBinder, declaredLocalsScopeDesignatorOpt) => { actualRootBinder = rootBinder; declaredLocalsScopeDesignator = declaredLocalsScopeDesignatorOpt; }); // We just need to trigger the process of building the binder map // so that the lambda above was executed. executableBinder.GetBinder(syntax); RoslynDebug.AssertNotNull(actualRootBinder); if (declaredLocalsScopeDesignator != null) { declaredLocals = actualRootBinder.GetDeclaredLocalsForScope(declaredLocalsScopeDesignator); } else { declaredLocals = ImmutableArray<LocalSymbol>.Empty; } return actualRootBinder; } private static Imports BuildImports(CSharpCompilation compilation, ImmutableArray<ImportRecord> importRecords, InContainerBinder binder) { // We make a first pass to extract all of the extern aliases because other imports may depend on them. var externsBuilder = ArrayBuilder<AliasAndExternAliasDirective>.GetInstance(); foreach (var importRecord in importRecords) { if (importRecord.TargetKind != ImportTargetKind.Assembly) { continue; } var alias = importRecord.Alias; RoslynDebug.AssertNotNull(alias); if (!TryParseIdentifierNameSyntax(alias, out var aliasNameSyntax)) { Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{alias}'"); continue; } NamespaceSymbol target; compilation.GetExternAliasTarget(aliasNameSyntax.Identifier.ValueText, out target); Debug.Assert(target.IsGlobalNamespace); var aliasSymbol = AliasSymbol.CreateCustomDebugInfoAlias(target, aliasNameSyntax.Identifier, binder.ContainingMemberOrLambda, isExtern: true); externsBuilder.Add(new AliasAndExternAliasDirective(aliasSymbol, externAliasDirective: null, skipInLookup: false)); } var externs = externsBuilder.ToImmutableAndFree(); if (externs.Any()) { // NB: This binder (and corresponding Imports) is only used to bind the other imports. // We'll merge the externs into a final Imports object and return that to be used in // the actual binder chain. binder = new InContainerBinder( binder.Container, WithExternAliasesBinder.Create(externs, binder)); } var usingAliases = ImmutableDictionary.CreateBuilder<string, AliasAndUsingDirective>(); var usingsBuilder = ArrayBuilder<NamespaceOrTypeAndUsingDirective>.GetInstance(); foreach (var importRecord in importRecords) { switch (importRecord.TargetKind) { case ImportTargetKind.Type: { var typeSymbol = (TypeSymbol?)importRecord.TargetType; RoslynDebug.AssertNotNull(typeSymbol); if (typeSymbol.IsErrorType()) { // Type is unrecognized. The import may have been // valid in the original source but unnecessary. continue; // Don't add anything for this import. } else if (importRecord.Alias == null && !typeSymbol.IsStatic) { // Only static types can be directly imported. continue; } if (!TryAddImport(importRecord.Alias, typeSymbol, usingsBuilder, usingAliases, binder, importRecord)) { continue; } break; } case ImportTargetKind.Namespace: { var namespaceName = importRecord.TargetString; RoslynDebug.AssertNotNull(namespaceName); if (!SyntaxHelpers.TryParseDottedName(namespaceName, out _)) { // DevDiv #999086: Some previous version of VS apparently generated type aliases as "UA{alias} T{alias-qualified type name}". // Neither Roslyn nor Dev12 parses such imports. However, Roslyn discards them, rather than interpreting them as "UA{alias}" // (which will rarely work and never be correct). Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid target '{importRecord.TargetString}'"); continue; } NamespaceSymbol globalNamespace; var targetAssembly = (AssemblySymbol?)importRecord.TargetAssembly; if (targetAssembly is object) { if (targetAssembly.IsMissing) { Debug.WriteLine($"Import record '{importRecord}' has invalid assembly reference '{targetAssembly.Identity}'"); continue; } globalNamespace = targetAssembly.GlobalNamespace; } else if (importRecord.TargetAssemblyAlias != null) { if (!TryParseIdentifierNameSyntax(importRecord.TargetAssemblyAlias, out var externAliasSyntax)) { Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{importRecord.TargetAssemblyAlias}'"); continue; } var aliasSymbol = (AliasSymbol)binder.BindNamespaceAliasSymbol(externAliasSyntax, BindingDiagnosticBag.Discarded); if (aliasSymbol is null) { Debug.WriteLine($"Import record '{importRecord}' requires unknown extern alias '{importRecord.TargetAssemblyAlias}'"); continue; } globalNamespace = (NamespaceSymbol)aliasSymbol.Target; } else { globalNamespace = compilation.GlobalNamespace; } var namespaceSymbol = BindNamespace(namespaceName, globalNamespace); if (namespaceSymbol is null) { // Namespace is unrecognized. The import may have been // valid in the original source but unnecessary. continue; // Don't add anything for this import. } if (!TryAddImport(importRecord.Alias, namespaceSymbol, usingsBuilder, usingAliases, binder, importRecord)) { continue; } break; } case ImportTargetKind.Assembly: // Handled in first pass (above). break; default: throw ExceptionUtilities.UnexpectedValue(importRecord.TargetKind); } } return Imports.Create(usingAliases.ToImmutableDictionary(), usingsBuilder.ToImmutableAndFree(), externs); } private static NamespaceSymbol? BindNamespace(string namespaceName, NamespaceSymbol globalNamespace) { NamespaceSymbol? namespaceSymbol = globalNamespace; foreach (var name in namespaceName.Split('.')) { var members = namespaceSymbol.GetMembers(name); namespaceSymbol = (members.Length == 1) ? members[0] as NamespaceSymbol : null; if (namespaceSymbol is null) { break; } } return namespaceSymbol; } private static bool TryAddImport( string? alias, NamespaceOrTypeSymbol targetSymbol, ArrayBuilder<NamespaceOrTypeAndUsingDirective> usingsBuilder, ImmutableDictionary<string, AliasAndUsingDirective>.Builder usingAliases, InContainerBinder binder, ImportRecord importRecord) { if (alias == null) { usingsBuilder.Add(new NamespaceOrTypeAndUsingDirective(targetSymbol, usingDirective: null, dependencies: default)); } else { if (!TryParseIdentifierNameSyntax(alias, out var aliasSyntax)) { Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid alias '{alias}'"); return false; } var aliasSymbol = AliasSymbol.CreateCustomDebugInfoAlias(targetSymbol, aliasSyntax.Identifier, binder.ContainingMemberOrLambda, isExtern: false); usingAliases.Add(alias, new AliasAndUsingDirective(aliasSymbol, usingDirective: null)); } return true; } private static bool TryParseIdentifierNameSyntax(string name, [NotNullWhen(true)] out IdentifierNameSyntax? syntax) { if (name == MetadataReferenceProperties.GlobalAlias) { syntax = SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)); return true; } if (!SyntaxHelpers.TryParseDottedName(name, out var nameSyntax) || nameSyntax.Kind() != SyntaxKind.IdentifierName) { syntax = null; return false; } syntax = (IdentifierNameSyntax)nameSyntax; return true; } internal CommonMessageProvider MessageProvider { get { return Compilation.MessageProvider; } } private static DkmClrCompilationResultFlags GetLocalResultFlags(LocalSymbol local) { // CONSIDER: We might want to prevent the user from modifying pinned locals - // that's pretty dangerous. return local.IsConst ? DkmClrCompilationResultFlags.ReadOnlyResult : DkmClrCompilationResultFlags.None; } /// <summary> /// Generate the set of locals to use for binding. /// </summary> private static ImmutableArray<LocalSymbol> GetLocalsForBinding( ImmutableArray<LocalSymbol> locals, ImmutableArray<string> displayClassVariableNamesInOrder, ImmutableDictionary<string, DisplayClassVariable> displayClassVariables) { var builder = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var local in locals) { var name = local.Name; if (name == null) { continue; } if (GeneratedNameParser.GetKind(name) != GeneratedNameKind.None) { continue; } // Although Roslyn doesn't name synthesized locals unless they are well-known to EE, // Dev12 did so we need to skip them here. if (GeneratedNameParser.IsSynthesizedLocalName(name)) { continue; } builder.Add(local); } foreach (var variableName in displayClassVariableNamesInOrder) { var variable = displayClassVariables[variableName]; switch (variable.Kind) { case DisplayClassVariableKind.Local: case DisplayClassVariableKind.Parameter: builder.Add(new EEDisplayClassFieldLocalSymbol(variable)); break; } } return builder.ToImmutableAndFree(); } private static ImmutableArray<string> GetSourceMethodParametersInOrder( MethodSymbol method, MethodSymbol? sourceMethod) { var containingType = method.ContainingType; bool isIteratorOrAsyncMethod = IsDisplayClassType(containingType) && GeneratedNameParser.GetKind(containingType.Name) == GeneratedNameKind.StateMachineType; var parameterNamesInOrder = ArrayBuilder<string>.GetInstance(); // For version before .NET 4.5, we cannot find the sourceMethod properly: // The source method coincides with the original method in the case. // Therefore, for iterators and async state machines, we have to get parameters from the containingType. // This does not guarantee the proper order of parameters. if (isIteratorOrAsyncMethod && method == sourceMethod) { Debug.Assert(IsDisplayClassType(containingType)); foreach (var member in containingType.GetMembers()) { if (member.Kind != SymbolKind.Field) { continue; } var field = (FieldSymbol)member; var fieldName = field.Name; if (GeneratedNameParser.GetKind(fieldName) == GeneratedNameKind.None) { parameterNamesInOrder.Add(fieldName); } } } else { if (sourceMethod is object) { foreach (var p in sourceMethod.Parameters) { parameterNamesInOrder.Add(p.Name); } } } return parameterNamesInOrder.ToImmutableAndFree(); } /// <summary> /// Return a mapping of captured variables (parameters, locals, and /// "this") to locals. The mapping is needed to expose the original /// local identifiers (those from source) in the binder. /// </summary> private static void GetDisplayClassVariables( MethodSymbol method, ImmutableArray<LocalSymbol> locals, ImmutableSortedSet<int> inScopeHoistedLocalSlots, ImmutableArray<string> parameterNamesInOrder, out ImmutableArray<string> displayClassVariableNamesInOrder, out ImmutableDictionary<string, DisplayClassVariable> displayClassVariables) { // Calculate the shortest paths from locals to instances of display // classes. There should not be two instances of the same display // class immediately within any particular method. var displayClassInstances = ArrayBuilder<DisplayClassInstanceAndFields>.GetInstance(); foreach (var parameter in method.Parameters) { if (GeneratedNameParser.GetKind(parameter.Name) == GeneratedNameKind.TransparentIdentifier || IsDisplayClassParameter(parameter)) { var instance = new DisplayClassInstanceFromParameter(parameter); displayClassInstances.Add(new DisplayClassInstanceAndFields(instance)); } } if (IsDisplayClassType(method.ContainingType) && !method.IsStatic) { // Add "this" display class instance. var instance = new DisplayClassInstanceFromParameter(method.ThisParameter); displayClassInstances.Add(new DisplayClassInstanceAndFields(instance)); } var displayClassTypes = PooledHashSet<TypeSymbol>.GetInstance(); foreach (var instance in displayClassInstances) { displayClassTypes.Add(instance.Instance.Type); } // Find any additional display class instances. GetAdditionalDisplayClassInstances(displayClassTypes, displayClassInstances, startIndex: 0); // Add any display class instances from locals (these will contain any hoisted locals). // Locals are only added after finding all display class instances reachable from // parameters because locals may be null (temporary locals in async state machine // for instance) so we prefer parameters to locals. int startIndex = displayClassInstances.Count; foreach (var local in locals) { var name = local.Name; if (name != null && GeneratedNameParser.GetKind(name) == GeneratedNameKind.DisplayClassLocalOrField) { var localType = local.Type; if (localType is object && displayClassTypes.Add(localType)) { var instance = new DisplayClassInstanceFromLocal((EELocalSymbol)local); displayClassInstances.Add(new DisplayClassInstanceAndFields(instance)); } } } GetAdditionalDisplayClassInstances(displayClassTypes, displayClassInstances, startIndex); displayClassTypes.Free(); if (displayClassInstances.Any()) { var parameterNames = PooledHashSet<string>.GetInstance(); foreach (var name in parameterNamesInOrder) { parameterNames.Add(name); } // The locals are the set of all fields from the display classes. var displayClassVariableNamesInOrderBuilder = ArrayBuilder<string>.GetInstance(); var displayClassVariablesBuilder = PooledDictionary<string, DisplayClassVariable>.GetInstance(); foreach (var instance in displayClassInstances) { GetDisplayClassVariables( displayClassVariableNamesInOrderBuilder, displayClassVariablesBuilder, parameterNames, inScopeHoistedLocalSlots, instance); } displayClassVariableNamesInOrder = displayClassVariableNamesInOrderBuilder.ToImmutableAndFree(); displayClassVariables = displayClassVariablesBuilder.ToImmutableDictionary(); displayClassVariablesBuilder.Free(); parameterNames.Free(); } else { displayClassVariableNamesInOrder = ImmutableArray<string>.Empty; displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty; } displayClassInstances.Free(); } private static void GetAdditionalDisplayClassInstances( HashSet<TypeSymbol> displayClassTypes, ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances, int startIndex) { // Find any additional display class instances breadth first. for (int i = startIndex; i < displayClassInstances.Count; i++) { GetDisplayClassInstances(displayClassTypes, displayClassInstances, displayClassInstances[i]); } } private static void GetDisplayClassInstances( HashSet<TypeSymbol> displayClassTypes, ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances, DisplayClassInstanceAndFields instance) { // Display class instance. The display class fields are variables. foreach (var member in instance.Type.GetMembers()) { if (member.Kind != SymbolKind.Field) { continue; } var field = (FieldSymbol)member; var fieldType = field.Type; var fieldName = field.Name; TryParseGeneratedName(fieldName, out var fieldKind, out var part); switch (fieldKind) { case GeneratedNameKind.DisplayClassLocalOrField: case GeneratedNameKind.TransparentIdentifier: break; case GeneratedNameKind.AnonymousTypeField: RoslynDebug.AssertNotNull(part); if (GeneratedNameParser.GetKind(part) != GeneratedNameKind.TransparentIdentifier) { continue; } break; case GeneratedNameKind.ThisProxyField: if (GeneratedNameParser.GetKind(fieldType.Name) != GeneratedNameKind.LambdaDisplayClass) { continue; } // Async lambda case. break; default: continue; } Debug.Assert(!field.IsStatic); // A hoisted local that is itself a display class instance. if (displayClassTypes.Add(fieldType)) { var other = instance.FromField(field); displayClassInstances.Add(other); } } } /// <summary> /// Returns true if the parameter is a synthesized parameter representing /// a display class instance (used to pass hoisted symbols to local functions). /// </summary> private static bool IsDisplayClassParameter(ParameterSymbol parameter) { var type = parameter.Type; var result = type.Kind == SymbolKind.NamedType && IsDisplayClassType((NamedTypeSymbol)type); Debug.Assert(!result || parameter.MetadataName == ""); return result; } private static void GetDisplayClassVariables( ArrayBuilder<string> displayClassVariableNamesInOrderBuilder, Dictionary<string, DisplayClassVariable> displayClassVariablesBuilder, HashSet<string> parameterNames, ImmutableSortedSet<int> inScopeHoistedLocalSlots, DisplayClassInstanceAndFields instance) { // Display class instance. The display class fields are variables. foreach (var member in instance.Type.GetMembers()) { if (member.Kind != SymbolKind.Field) { continue; } var field = (FieldSymbol)member; var fieldName = field.Name; REPARSE: DisplayClassVariableKind variableKind; string variableName; TryParseGeneratedName(fieldName, out var fieldKind, out var part); switch (fieldKind) { case GeneratedNameKind.AnonymousTypeField: RoslynDebug.AssertNotNull(part); Debug.Assert(fieldName == field.Name); // This only happens once. fieldName = part; goto REPARSE; case GeneratedNameKind.TransparentIdentifier: // A transparent identifier (field) in an anonymous type synthesized for a transparent identifier. Debug.Assert(!field.IsStatic); continue; case GeneratedNameKind.DisplayClassLocalOrField: // A local that is itself a display class instance. Debug.Assert(!field.IsStatic); continue; case GeneratedNameKind.HoistedLocalField: RoslynDebug.AssertNotNull(part); // Filter out hoisted locals that are known to be out-of-scope at the current IL offset. // Hoisted locals with invalid indices will be included since more information is better // than less in error scenarios. if (GeneratedNameParser.TryParseSlotIndex(fieldName, out int slotIndex) && !inScopeHoistedLocalSlots.Contains(slotIndex)) { continue; } variableName = part; variableKind = DisplayClassVariableKind.Local; Debug.Assert(!field.IsStatic); break; case GeneratedNameKind.ThisProxyField: // A reference to "this". variableName = ""; // Should not be referenced by name. variableKind = DisplayClassVariableKind.This; Debug.Assert(!field.IsStatic); break; case GeneratedNameKind.None: // A reference to a parameter or local. variableName = fieldName; variableKind = parameterNames.Contains(variableName) ? DisplayClassVariableKind.Parameter : DisplayClassVariableKind.Local; Debug.Assert(!field.IsStatic); break; default: continue; } if (displayClassVariablesBuilder.ContainsKey(variableName)) { // Only expecting duplicates for async state machine // fields (that should be at the top-level). Debug.Assert(displayClassVariablesBuilder[variableName].DisplayClassFields.Count() == 1); if (!instance.Fields.Any()) { // Prefer parameters over locals. Debug.Assert(instance.Instance is DisplayClassInstanceFromLocal); } else { Debug.Assert(instance.Fields.Count() >= 1); // greater depth Debug.Assert(variableKind == DisplayClassVariableKind.Parameter || variableKind == DisplayClassVariableKind.This); if (variableKind == DisplayClassVariableKind.Parameter && GeneratedNameParser.GetKind(instance.Type.Name) == GeneratedNameKind.LambdaDisplayClass) { displayClassVariablesBuilder[variableName] = instance.ToVariable(variableName, variableKind, field); } } } else if (variableKind != DisplayClassVariableKind.This || GeneratedNameParser.GetKind(instance.Type.ContainingType.Name) != GeneratedNameKind.LambdaDisplayClass) { // In async lambdas, the hoisted "this" field in the state machine type will point to the display class instance, if there is one. // In such cases, we want to add the display class "this" to the map instead (or nothing, if it lacks one). displayClassVariableNamesInOrderBuilder.Add(variableName); displayClassVariablesBuilder.Add(variableName, instance.ToVariable(variableName, variableKind, field)); } } } private static void TryParseGeneratedName(string name, out GeneratedNameKind kind, out string? part) { _ = GeneratedNameParser.TryParseGeneratedName(name, out kind, out int openBracketOffset, out int closeBracketOffset); switch (kind) { case GeneratedNameKind.AnonymousTypeField: case GeneratedNameKind.HoistedLocalField: part = name.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1); break; default: part = null; break; } } private static bool IsDisplayClassType(TypeSymbol type) { switch (GeneratedNameParser.GetKind(type.Name)) { case GeneratedNameKind.LambdaDisplayClass: case GeneratedNameKind.StateMachineType: return true; default: return false; } } internal static DisplayClassVariable GetThisProxy(ImmutableDictionary<string, DisplayClassVariable> displayClassVariables) { return displayClassVariables.Values.FirstOrDefault(v => v.Kind == DisplayClassVariableKind.This); } private static NamedTypeSymbol GetNonDisplayClassContainer(NamedTypeSymbol type) { // 1) Display class and state machine types are always nested within the types // that use them (so that they can access private members of those types). // 2) The native compiler used to produce nested display classes for nested lambdas, // so we may have to walk out more than one level. while (IsDisplayClassType(type)) { type = type.ContainingType!; } return type; } /// <summary> /// Identifies the method in which binding should occur. /// </summary> /// <param name="candidateSubstitutedSourceMethod"> /// The symbol of the method that is currently on top of the callstack, with /// EE type parameters substituted in place of the original type parameters. /// </param> /// <param name="sourceMethodMustBeInstance"> /// True if "this" is available via a display class in the current context. /// </param> /// <returns> /// If <paramref name="candidateSubstitutedSourceMethod"/> is compiler-generated, /// then we will attempt to determine which user-defined method caused it to be /// generated. For example, if <paramref name="candidateSubstitutedSourceMethod"/> /// is a state machine MoveNext method, then we will try to find the iterator or /// async method for which it was generated. If we are able to find the original /// method, then we will substitute in the EE type parameters. Otherwise, we will /// return <paramref name="candidateSubstitutedSourceMethod"/>. /// </returns> /// <remarks> /// In the event that the original method is overloaded, we may not be able to determine /// which overload actually corresponds to the state machine. In particular, we do not /// have information about the signature of the original method (i.e. number of parameters, /// parameter types and ref-kinds, return type). However, we conjecture that this /// level of uncertainty is acceptable, since parameters are managed by a separate binder /// in the synthesized binder chain and we have enough information to check the other method /// properties that are used during binding (e.g. static-ness, generic arity, type parameter /// constraints). /// </remarks> internal static MethodSymbol GetSubstitutedSourceMethod( MethodSymbol candidateSubstitutedSourceMethod, bool sourceMethodMustBeInstance) { var candidateSubstitutedSourceType = candidateSubstitutedSourceMethod.ContainingType; string? desiredMethodName; if (GeneratedNameParser.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceType.Name, GeneratedNameKind.StateMachineType, out desiredMethodName) || GeneratedNameParser.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceMethod.Name, GeneratedNameKind.LambdaMethod, out desiredMethodName) || GeneratedNameParser.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceMethod.Name, GeneratedNameKind.LocalFunction, out desiredMethodName)) { // We could be in the MoveNext method of an async lambda. string? tempMethodName; if (GeneratedNameParser.TryParseSourceMethodNameFromGeneratedName(desiredMethodName, GeneratedNameKind.LambdaMethod, out tempMethodName) || GeneratedNameParser.TryParseSourceMethodNameFromGeneratedName(desiredMethodName, GeneratedNameKind.LocalFunction, out tempMethodName)) { desiredMethodName = tempMethodName; var containing = candidateSubstitutedSourceType.ContainingType; RoslynDebug.AssertNotNull(containing); if (GeneratedNameParser.GetKind(containing.Name) == GeneratedNameKind.LambdaDisplayClass) { candidateSubstitutedSourceType = containing; sourceMethodMustBeInstance = candidateSubstitutedSourceType.MemberNames.Select(GeneratedNameParser.GetKind).Contains(GeneratedNameKind.ThisProxyField); } } var desiredTypeParameters = candidateSubstitutedSourceType.OriginalDefinition.TypeParameters; // Type containing the original iterator, async, or lambda-containing method. var substitutedSourceType = GetNonDisplayClassContainer(candidateSubstitutedSourceType); foreach (var candidateMethod in substitutedSourceType.GetMembers().OfType<MethodSymbol>()) { if (IsViableSourceMethod(candidateMethod, desiredMethodName, desiredTypeParameters, sourceMethodMustBeInstance)) { return desiredTypeParameters.Length == 0 ? candidateMethod : candidateMethod.Construct(candidateSubstitutedSourceType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics); } } Debug.Fail("Why didn't we find a substituted source method for " + candidateSubstitutedSourceMethod + "?"); } return candidateSubstitutedSourceMethod; } private static bool IsViableSourceMethod( MethodSymbol candidateMethod, string desiredMethodName, ImmutableArray<TypeParameterSymbol> desiredTypeParameters, bool desiredMethodMustBeInstance) { return !candidateMethod.IsAbstract && !(desiredMethodMustBeInstance && candidateMethod.IsStatic) && candidateMethod.Name == desiredMethodName && HaveSameConstraints(candidateMethod.TypeParameters, desiredTypeParameters); } private static bool HaveSameConstraints(ImmutableArray<TypeParameterSymbol> candidateTypeParameters, ImmutableArray<TypeParameterSymbol> desiredTypeParameters) { int arity = candidateTypeParameters.Length; if (arity != desiredTypeParameters.Length) { return false; } if (arity == 0) { return true; } var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity); var candidateTypeMap = new TypeMap(candidateTypeParameters, indexedTypeParameters, allowAlpha: true); var desiredTypeMap = new TypeMap(desiredTypeParameters, indexedTypeParameters, allowAlpha: true); return MemberSignatureComparer.HaveSameConstraints(candidateTypeParameters, candidateTypeMap, desiredTypeParameters, desiredTypeMap); } [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] private readonly struct DisplayClassInstanceAndFields { internal readonly DisplayClassInstance Instance; internal readonly ConsList<FieldSymbol> Fields; internal DisplayClassInstanceAndFields(DisplayClassInstance instance) : this(instance, ConsList<FieldSymbol>.Empty) { Debug.Assert(IsDisplayClassType(instance.Type) || GeneratedNameParser.GetKind(instance.Type.Name) == GeneratedNameKind.AnonymousType); } private DisplayClassInstanceAndFields(DisplayClassInstance instance, ConsList<FieldSymbol> fields) { Instance = instance; Fields = fields; } internal TypeSymbol Type => Fields.Any() ? Fields.Head.Type : Instance.Type; internal int Depth => Fields.Count(); internal DisplayClassInstanceAndFields FromField(FieldSymbol field) { Debug.Assert(IsDisplayClassType(field.Type) || GeneratedNameParser.GetKind(field.Type.Name) == GeneratedNameKind.AnonymousType); return new DisplayClassInstanceAndFields(Instance, Fields.Prepend(field)); } internal DisplayClassVariable ToVariable(string name, DisplayClassVariableKind kind, FieldSymbol field) { return new DisplayClassVariable(name, kind, Instance, Fields.Prepend(field)); } private string GetDebuggerDisplay() { return Instance.GetDebuggerDisplay(Fields); } } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Query.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitRangeVariable(BoundRangeVariable node) { return VisitExpression(node.Value); } public override BoundNode VisitQueryClause(BoundQueryClause node) { return VisitExpression(node.Value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitRangeVariable(BoundRangeVariable node) { return VisitExpression(node.Value); } public override BoundNode VisitQueryClause(BoundQueryClause node) { return VisitExpression(node.Value); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Compilers/Core/Portable/PEWriter/Constants.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection; using System.Runtime.InteropServices; namespace Microsoft.Cci { internal static class Constants { // Non-portable CharSet values: public const CharSet CharSet_None = (CharSet)1; public const CharSet CharSet_Auto = (CharSet)4; // Non-portable CallingConvention values: public const System.Runtime.InteropServices.CallingConvention CallingConvention_FastCall = (System.Runtime.InteropServices.CallingConvention)5; // Non-portable UnmanagedType values: public const UnmanagedType UnmanagedType_CustomMarshaler = (UnmanagedType)44; public const UnmanagedType UnmanagedType_IDispatch = (UnmanagedType)26; public const UnmanagedType UnmanagedType_SafeArray = (UnmanagedType)29; public const UnmanagedType UnmanagedType_VBByRefStr = (UnmanagedType)34; public const UnmanagedType UnmanagedType_AnsiBStr = (UnmanagedType)35; public const UnmanagedType UnmanagedType_TBStr = (UnmanagedType)36; public const ComInterfaceType ComInterfaceType_InterfaceIsDual = 0; public const ComInterfaceType ComInterfaceType_InterfaceIsIDispatch = (ComInterfaceType)2; public const ClassInterfaceType ClassInterfaceType_AutoDispatch = (ClassInterfaceType)1; public const ClassInterfaceType ClassInterfaceType_AutoDual = (ClassInterfaceType)2; // Non-portable CompilationRelaxations value: public const int CompilationRelaxations_NoStringInterning = 0x0008; public const TypeAttributes TypeAttributes_TypeForwarder = (TypeAttributes)0x00200000; } /// <summary> /// System.Runtime.InteropServices.VarEnum is obsolete. /// </summary> internal enum VarEnum { VT_EMPTY = 0, VT_NULL = 1, VT_I2 = 2, VT_I4 = 3, VT_R4 = 4, VT_R8 = 5, VT_CY = 6, VT_DATE = 7, VT_BSTR = 8, VT_DISPATCH = 9, VT_ERROR = 10, VT_BOOL = 11, VT_VARIANT = 12, VT_UNKNOWN = 13, VT_DECIMAL = 14, VT_I1 = 16, VT_UI1 = 17, VT_UI2 = 18, VT_UI4 = 19, VT_I8 = 20, VT_UI8 = 21, VT_INT = 22, VT_UINT = 23, VT_VOID = 24, VT_HRESULT = 25, VT_PTR = 26, VT_SAFEARRAY = 27, VT_CARRAY = 28, VT_USERDEFINED = 29, VT_LPSTR = 30, VT_LPWSTR = 31, VT_RECORD = 36, VT_FILETIME = 64, VT_BLOB = 65, VT_STREAM = 66, VT_STORAGE = 67, VT_STREAMED_OBJECT = 68, VT_STORED_OBJECT = 69, VT_BLOB_OBJECT = 70, VT_CF = 71, VT_CLSID = 72, VT_VECTOR = 0x1000, VT_ARRAY = 0x2000, VT_BYREF = 0x4000 } }
// Licensed to the .NET Foundation under one or more 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.Reflection; using System.Runtime.InteropServices; namespace Microsoft.Cci { internal static class Constants { // Non-portable CharSet values: public const CharSet CharSet_None = (CharSet)1; public const CharSet CharSet_Auto = (CharSet)4; // Non-portable CallingConvention values: public const System.Runtime.InteropServices.CallingConvention CallingConvention_FastCall = (System.Runtime.InteropServices.CallingConvention)5; // Non-portable UnmanagedType values: public const UnmanagedType UnmanagedType_CustomMarshaler = (UnmanagedType)44; public const UnmanagedType UnmanagedType_IDispatch = (UnmanagedType)26; public const UnmanagedType UnmanagedType_SafeArray = (UnmanagedType)29; public const UnmanagedType UnmanagedType_VBByRefStr = (UnmanagedType)34; public const UnmanagedType UnmanagedType_AnsiBStr = (UnmanagedType)35; public const UnmanagedType UnmanagedType_TBStr = (UnmanagedType)36; public const ComInterfaceType ComInterfaceType_InterfaceIsDual = 0; public const ComInterfaceType ComInterfaceType_InterfaceIsIDispatch = (ComInterfaceType)2; public const ClassInterfaceType ClassInterfaceType_AutoDispatch = (ClassInterfaceType)1; public const ClassInterfaceType ClassInterfaceType_AutoDual = (ClassInterfaceType)2; // Non-portable CompilationRelaxations value: public const int CompilationRelaxations_NoStringInterning = 0x0008; public const TypeAttributes TypeAttributes_TypeForwarder = (TypeAttributes)0x00200000; } /// <summary> /// System.Runtime.InteropServices.VarEnum is obsolete. /// </summary> internal enum VarEnum { VT_EMPTY = 0, VT_NULL = 1, VT_I2 = 2, VT_I4 = 3, VT_R4 = 4, VT_R8 = 5, VT_CY = 6, VT_DATE = 7, VT_BSTR = 8, VT_DISPATCH = 9, VT_ERROR = 10, VT_BOOL = 11, VT_VARIANT = 12, VT_UNKNOWN = 13, VT_DECIMAL = 14, VT_I1 = 16, VT_UI1 = 17, VT_UI2 = 18, VT_UI4 = 19, VT_I8 = 20, VT_UI8 = 21, VT_INT = 22, VT_UINT = 23, VT_VOID = 24, VT_HRESULT = 25, VT_PTR = 26, VT_SAFEARRAY = 27, VT_CARRAY = 28, VT_USERDEFINED = 29, VT_LPSTR = 30, VT_LPWSTR = 31, VT_RECORD = 36, VT_FILETIME = 64, VT_BLOB = 65, VT_STREAM = 66, VT_STORAGE = 67, VT_STREAMED_OBJECT = 68, VT_STORED_OBJECT = 69, VT_BLOB_OBJECT = 70, VT_CF = 71, VT_CLSID = 72, VT_VECTOR = 0x1000, VT_ARRAY = 0x2000, VT_BYREF = 0x4000 } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ThisKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ThisKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ThisKeywordRecommender() : base(SyntaxKind.ThisKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return IsInstanceExpressionOrStatement(context) || IsThisParameterModifierContext(context) || IsConstructorInitializerContext(context); } private static bool IsInstanceExpressionOrStatement(CSharpSyntaxContext context) { if (context.IsInstanceContext) { return context.IsNonAttributeExpressionContext || context.IsStatementContext; } return false; } private static bool IsConstructorInitializerContext(CSharpSyntaxContext context) { // cases: // Goo() : | var token = context.TargetToken; if (token.Kind() == SyntaxKind.ColonToken && token.Parent is ConstructorInitializerSyntax && token.Parent.IsParentKind(SyntaxKind.ConstructorDeclaration)) { var constructor = token.GetAncestor<ConstructorDeclarationSyntax>(); if (constructor.Modifiers.Any(SyntaxKind.StaticKeyword)) { return false; } return true; } return false; } private static bool IsThisParameterModifierContext(CSharpSyntaxContext context) { if (context.SyntaxTree.IsParameterModifierContext( context.Position, context.LeftToken, includeOperators: false, out var parameterIndex, out var previousModifier)) { if (previousModifier == SyntaxKind.None || previousModifier == SyntaxKind.RefKeyword || previousModifier == SyntaxKind.InKeyword) { if (parameterIndex == 0 && context.SyntaxTree.IsPossibleExtensionMethodContext(context.LeftToken)) { return true; } } } return false; } protected override bool ShouldPreselect(CSharpSyntaxContext context, CancellationToken cancellationToken) { var outerType = context.SemanticModel.GetEnclosingNamedType(context.Position, cancellationToken); return context.InferredTypes.Any(t => Equals(t, outerType)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ThisKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ThisKeywordRecommender() : base(SyntaxKind.ThisKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return IsInstanceExpressionOrStatement(context) || IsThisParameterModifierContext(context) || IsConstructorInitializerContext(context); } private static bool IsInstanceExpressionOrStatement(CSharpSyntaxContext context) { if (context.IsInstanceContext) { return context.IsNonAttributeExpressionContext || context.IsStatementContext; } return false; } private static bool IsConstructorInitializerContext(CSharpSyntaxContext context) { // cases: // Goo() : | var token = context.TargetToken; if (token.Kind() == SyntaxKind.ColonToken && token.Parent is ConstructorInitializerSyntax && token.Parent.IsParentKind(SyntaxKind.ConstructorDeclaration)) { var constructor = token.GetAncestor<ConstructorDeclarationSyntax>(); if (constructor.Modifiers.Any(SyntaxKind.StaticKeyword)) { return false; } return true; } return false; } private static bool IsThisParameterModifierContext(CSharpSyntaxContext context) { if (context.SyntaxTree.IsParameterModifierContext( context.Position, context.LeftToken, includeOperators: false, out var parameterIndex, out var previousModifier)) { if (previousModifier == SyntaxKind.None || previousModifier == SyntaxKind.RefKeyword || previousModifier == SyntaxKind.InKeyword) { if (parameterIndex == 0 && context.SyntaxTree.IsPossibleExtensionMethodContext(context.LeftToken)) { return true; } } } return false; } protected override bool ShouldPreselect(CSharpSyntaxContext context, CancellationToken cancellationToken) { var outerType = context.SemanticModel.GetEnclosingNamedType(context.Position, cancellationToken); return context.InferredTypes.Any(t => Equals(t, outerType)); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Workspaces/CSharp/Portable/Workspace/LanguageServices/CSharpSyntaxTreeFactoryService.PositionalSyntaxReference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal partial class CSharpSyntaxTreeFactoryServiceFactory { private partial class CSharpSyntaxTreeFactoryService { /// <summary> /// Represents a syntax reference that doesn't actually hold onto the /// referenced node. Instead, enough data is held onto so that the node /// can be recovered and returned if necessary. /// </summary> private class PositionalSyntaxReference : SyntaxReference { private readonly SyntaxKind _kind; public PositionalSyntaxReference(SyntaxNode node) { SyntaxTree = node.SyntaxTree; Span = node.Span; _kind = node.Kind(); System.Diagnostics.Debug.Assert(Span.Length > 0); } public override SyntaxTree SyntaxTree { get; } public override TextSpan Span { get; } public override SyntaxNode GetSyntax(CancellationToken cancellationToken) { // Find our node going down in the tree. // Try not going deeper than needed. return this.GetNode(SyntaxTree.GetRoot(cancellationToken)); } public override async Task<SyntaxNode> GetSyntaxAsync(CancellationToken cancellationToken = default) { var root = await SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); return this.GetNode(root); } private SyntaxNode GetNode(SyntaxNode root) { var current = root; var spanStart = Span.Start; while (current.FullSpan.Contains(spanStart)) { if (current.Kind() == _kind && current.Span == Span) { return current; } var nodeOrToken = current.ChildThatContainsPosition(spanStart); // we have got a token. It means that the node is in structured trivia if (nodeOrToken.IsToken) { return GetNodeInStructuredTrivia(current); } current = nodeOrToken.AsNode(); } throw new InvalidOperationException("reference to a node that does not exist?"); } private SyntaxNode GetNodeInStructuredTrivia(SyntaxNode parent) { // Syntax references to nonterminals in structured trivia should be uncommon. // Provide more efficient implementation if that is not true var descendantsIntersectingSpan = parent.DescendantNodes(Span, descendIntoTrivia: true); return descendantsIntersectingSpan.First(node => node.IsKind(_kind) && node.Span == Span); } } } } }
// Licensed to the .NET Foundation under one or more 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.Text; namespace Microsoft.CodeAnalysis.CSharp { internal partial class CSharpSyntaxTreeFactoryServiceFactory { private partial class CSharpSyntaxTreeFactoryService { /// <summary> /// Represents a syntax reference that doesn't actually hold onto the /// referenced node. Instead, enough data is held onto so that the node /// can be recovered and returned if necessary. /// </summary> private class PositionalSyntaxReference : SyntaxReference { private readonly SyntaxKind _kind; public PositionalSyntaxReference(SyntaxNode node) { SyntaxTree = node.SyntaxTree; Span = node.Span; _kind = node.Kind(); System.Diagnostics.Debug.Assert(Span.Length > 0); } public override SyntaxTree SyntaxTree { get; } public override TextSpan Span { get; } public override SyntaxNode GetSyntax(CancellationToken cancellationToken) { // Find our node going down in the tree. // Try not going deeper than needed. return this.GetNode(SyntaxTree.GetRoot(cancellationToken)); } public override async Task<SyntaxNode> GetSyntaxAsync(CancellationToken cancellationToken = default) { var root = await SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); return this.GetNode(root); } private SyntaxNode GetNode(SyntaxNode root) { var current = root; var spanStart = Span.Start; while (current.FullSpan.Contains(spanStart)) { if (current.Kind() == _kind && current.Span == Span) { return current; } var nodeOrToken = current.ChildThatContainsPosition(spanStart); // we have got a token. It means that the node is in structured trivia if (nodeOrToken.IsToken) { return GetNodeInStructuredTrivia(current); } current = nodeOrToken.AsNode(); } throw new InvalidOperationException("reference to a node that does not exist?"); } private SyntaxNode GetNodeInStructuredTrivia(SyntaxNode parent) { // Syntax references to nonterminals in structured trivia should be uncommon. // Provide more efficient implementation if that is not true var descendantsIntersectingSpan = parent.DescendantNodes(Span, descendIntoTrivia: true); return descendantsIntersectingSpan.First(node => node.IsKind(_kind) && node.Span == Span); } } } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/EditorFeatures/VisualBasicTest/Recommendations/OptionStatements/OptionNamesRecommenderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.OptionStatements Public Class OptionNamesRecommenderTests Inherits RecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OptionNamesAfterOptionTest() VerifyRecommendationsAreExactly(<File>Option |</File>, "Compare", "Explicit", "Infer", "Strict") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.OptionStatements Public Class OptionNamesRecommenderTests Inherits RecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OptionNamesAfterOptionTest() VerifyRecommendationsAreExactly(<File>Option |</File>, "Compare", "Explicit", "Infer", "Strict") End Sub End Class End Namespace
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Compilers/VisualBasic/Portable/Emit/GenericNestedTypeInstanceReference.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Emit ''' <summary> ''' Represents a reference to a generic type instantiation that is nested in a non-generic type. ''' e.g. A.B{int} ''' </summary> Friend NotInheritable Class GenericNestedTypeInstanceReference Inherits GenericTypeInstanceReference Implements Cci.INestedTypeReference Public Sub New(underlyingNamedType As NamedTypeSymbol) MyBase.New(underlyingNamedType) End Sub Private Function ITypeMemberReferenceGetContainingType(context As EmitContext) As Cci.ITypeReference Implements Cci.ITypeMemberReference.GetContainingType Return (DirectCast(context.Module, PEModuleBuilder)).Translate(m_UnderlyingNamedType.ContainingType, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End Function Public Overrides ReadOnly Property AsGenericTypeInstanceReference As Cci.IGenericTypeInstanceReference Get Return Me End Get End Property Public Overrides ReadOnly Property AsNamespaceTypeReference As Cci.INamespaceTypeReference Get Return Nothing End Get End Property Public Overrides ReadOnly Property AsNestedTypeReference As Cci.INestedTypeReference Get Return Me End Get End Property Public Overrides ReadOnly Property AsSpecializedNestedTypeReference As Cci.ISpecializedNestedTypeReference Get Return Nothing End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Emit ''' <summary> ''' Represents a reference to a generic type instantiation that is nested in a non-generic type. ''' e.g. A.B{int} ''' </summary> Friend NotInheritable Class GenericNestedTypeInstanceReference Inherits GenericTypeInstanceReference Implements Cci.INestedTypeReference Public Sub New(underlyingNamedType As NamedTypeSymbol) MyBase.New(underlyingNamedType) End Sub Private Function ITypeMemberReferenceGetContainingType(context As EmitContext) As Cci.ITypeReference Implements Cci.ITypeMemberReference.GetContainingType Return (DirectCast(context.Module, PEModuleBuilder)).Translate(m_UnderlyingNamedType.ContainingType, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End Function Public Overrides ReadOnly Property AsGenericTypeInstanceReference As Cci.IGenericTypeInstanceReference Get Return Me End Get End Property Public Overrides ReadOnly Property AsNamespaceTypeReference As Cci.INamespaceTypeReference Get Return Nothing End Get End Property Public Overrides ReadOnly Property AsNestedTypeReference As Cci.INestedTypeReference Get Return Me End Get End Property Public Overrides ReadOnly Property AsSpecializedNestedTypeReference As Cci.ISpecializedNestedTypeReference Get Return Nothing End Get End Property End Class End Namespace
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Compilers/VisualBasic/Test/Emit/PDB/VisualBasicDeterministicBuildCompilationTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Reflection.Metadata Imports System.Reflection.PortableExecutable Imports System.Text Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Debugging Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.PDB Public Class VisualBasicDeterministicBuildCompilationTests Inherits BasicTestBase Implements IEnumerable(Of Object()) Private Sub VerifyCompilationOptions(originalOptions As VisualBasicCompilationOptions, compilationOptionsBlobReader As BlobReader, emitOptions As EmitOptions, compilation As VisualBasicCompilation) Dim pdbOptions = DeterministicBuildCompilationTestHelpers.ParseCompilationOptions(compilationOptionsBlobReader) DeterministicBuildCompilationTestHelpers.AssertCommonOptions(emitOptions, originalOptions, compilation, pdbOptions) ' See VisualBasicCompilation.SerializeForPdb for options that are added pdbOptions.VerifyPdbOption("checked", originalOptions.CheckOverflow) pdbOptions.VerifyPdbOption("strict", originalOptions.OptionStrict) Assert.Equal(originalOptions.ParseOptions.LanguageVersion.MapSpecifiedToEffectiveVersion().ToDisplayString(), pdbOptions("language-version")) pdbOptions.VerifyPdbOption( "define", originalOptions.ParseOptions.PreprocessorSymbols, isDefault:=Function(v) v.IsEmpty, toString:=Function(v) String.Join(",", v.Select(Function(p) If(p.Value IsNot Nothing, $"{p.Key}=""{p.Value}""", p.Key)))) End Sub Private Sub TestDeterministicCompilationVB(syntaxTrees As SyntaxTree(), compilationOptions As VisualBasicCompilationOptions, emitOptions As EmitOptions, ParamArray metadataReferences() As TestMetadataReferenceInfo) Dim tf = TargetFramework.NetStandard20 Dim originalCompilation = CreateCompilation( syntaxTrees, references:=metadataReferences.SelectAsArray(Of MetadataReference)(Function(r) r.MetadataReference), options:=compilationOptions, targetFramework:=tf) Dim peBlob = originalCompilation.EmitToArray(emitOptions) Using peReader As PEReader = New PEReader(peBlob) Dim entries = peReader.ReadDebugDirectory() AssertEx.Equal({DebugDirectoryEntryType.CodeView, DebugDirectoryEntryType.PdbChecksum, DebugDirectoryEntryType.Reproducible, DebugDirectoryEntryType.EmbeddedPortablePdb}, entries.Select(Of DebugDirectoryEntryType)(Function(e) e.Type)) Dim codeView = entries(0) Dim checksum = entries(1) Dim reproducible = entries(2) Dim embedded = entries(3) Using embeddedPdb As MetadataReaderProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embedded) Dim pdbReader = embeddedPdb.GetMetadataReader() Dim metadataReferenceReader = DeterministicBuildCompilationTestHelpers.GetSingleBlob(PortableCustomDebugInfoKinds.CompilationMetadataReferences, pdbReader) Dim compilationOptionsReader = DeterministicBuildCompilationTestHelpers.GetSingleBlob(PortableCustomDebugInfoKinds.CompilationOptions, pdbReader) VerifyCompilationOptions(compilationOptions, compilationOptionsReader, emitOptions, originalCompilation) DeterministicBuildCompilationTestHelpers.VerifyReferenceInfo(metadataReferences, tf, metadataReferenceReader) End Using End Using End Sub <Theory> <ClassData(GetType(VisualBasicDeterministicBuildCompilationTests))> Public Sub PortablePdb_DeterministicCompilation(compilationOptions As VisualBasicCompilationOptions, emitOptions As EmitOptions) Dim sourceOne = Parse(" Class C1 End Class", fileName:="one.vb", options:=compilationOptions.ParseOptions, encoding:=Encoding.UTF8) Dim sourceTwo = Parse(" Class C2 End Class", fileName:="two.vb", options:=compilationOptions.ParseOptions, encoding:=New UTF8Encoding(encoderShouldEmitUTF8Identifier:=False)) Dim referenceSourceOne = <compilation> <file name="b.vb"> Public Class SomeClass End Class Public Class SomeOtherClass End Class </file> </compilation> Dim referenceSourceTwo = <compilation> <file name="b.vb"> Public Class SomeClass End Class Public Class SomeOtherClass End Class </file> </compilation> Dim referenceOneCompilation = CreateCompilation(referenceSourceOne, options:=TestOptions.DebugDll) Dim referenceTwoCompilation = CreateCompilation(referenceSourceTwo, options:=TestOptions.DebugDll) Using referenceOne As TestMetadataReferenceInfo = TestMetadataReferenceInfo.Create(referenceOneCompilation, "abcd.dll", EmitOptions.Default) Using referenceTwo As TestMetadataReferenceInfo = TestMetadataReferenceInfo.Create(referenceTwoCompilation, "efgh.dll", EmitOptions.Default) TestDeterministicCompilationVB({sourceOne, sourceTwo}, compilationOptions, emitOptions, referenceOne, referenceTwo) End Using End Using End Sub <ConditionalTheory(GetType(DesktopOnly))> <ClassData(GetType(VisualBasicDeterministicBuildCompilationTests))> Public Sub PortablePdb_DeterministicCompilationWithSJIS(compilationOptions As VisualBasicCompilationOptions, emitOptions As EmitOptions) Dim sourceOne = Parse(" Class C1 End Class", fileName:="one.vb", options:=compilationOptions.ParseOptions, encoding:=Encoding.UTF8) Dim sourceTwo = Parse(" Class C2 End Class", fileName:="two.vb", options:=compilationOptions.ParseOptions, encoding:=New UTF8Encoding(encoderShouldEmitUTF8Identifier:=False)) Dim sourceThree = Parse(" Class C3 End Class", fileName:="three.vb", options:=compilationOptions.ParseOptions, encoding:=Encoding.GetEncoding(932)) ' SJIS encoding Dim referenceSourceOne = <compilation> <file name="b.vb"> Public Class SomeClass End Class Public Class SomeOtherClass End Class </file> </compilation> Dim referenceSourceTwo = <compilation> <file name="b.vb"> Public Class SomeClass End Class Public Class SomeOtherClass End Class </file> </compilation> Dim referenceOneCompilation = CreateCompilation(referenceSourceOne, options:=TestOptions.DebugDll) Dim referenceTwoCompilation = CreateCompilation(referenceSourceTwo, options:=TestOptions.DebugDll) Using referenceOne As TestMetadataReferenceInfo = TestMetadataReferenceInfo.Create(referenceOneCompilation, "abcd.dll", EmitOptions.Default) Using referenceTwo As TestMetadataReferenceInfo = TestMetadataReferenceInfo.Create(referenceTwoCompilation, "efgh.dll", EmitOptions.Default) TestDeterministicCompilationVB({sourceOne, sourceTwo, sourceThree}, compilationOptions, emitOptions, referenceOne, referenceTwo) End Using End Using End Sub Public Iterator Function GetEnumerator() As IEnumerator(Of Object()) Implements IEnumerable(Of Object()).GetEnumerator For Each compilationOptions As VisualBasicCompilationOptions In GetCompilationOptions() For Each emitOptions As EmitOptions In GetEmitOptions() Yield {compilationOptions, emitOptions} Next Next End Function Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return GetEnumerator() End Function Private Iterator Function GetEmitOptions() As IEnumerable(Of EmitOptions) Dim emitOptions = New EmitOptions(debugInformationFormat:=DebugInformationFormat.Embedded) Yield emitOptions Yield emitOptions.WithDefaultSourceFileEncoding(Encoding.UTF8) End Function Private Iterator Function GetCompilationOptions() As IEnumerable(Of VisualBasicCompilationOptions) For Each parseOption As VisualBasicParseOptions In GetParseOptions() ' Provide non default options for to test that they are being serialized ' to the pdb correctly. It needs to produce a compilation to be emitted, but otherwise ' everything should be non-default if possible. Diagnostic settings are ignored ' because they won't be serialized. ' Use constructor that requires all arguments. If New arguments are added, it's possible they need to be ' included in the pdb serialization And added to tests here Dim defaultOptions = New VisualBasicCompilationOptions( OutputKind.DynamicallyLinkedLibrary, moduleName:=Nothing, mainTypeName:=Nothing, scriptClassName:=WellKnownMemberNames.DefaultScriptClassName, globalImports:={GlobalImport.Parse("System")}, rootNamespace:=Nothing, optionStrict:=OptionStrict.Off, optionInfer:=True, optionExplicit:=True, optionCompareText:=False, parseOptions:=parseOption, embedVbCoreRuntime:=False, optimizationLevel:=OptimizationLevel.Debug, checkOverflow:=True, cryptoKeyContainer:=Nothing, cryptoKeyFile:=Nothing, cryptoPublicKey:=Nothing, delaySign:=Nothing, platform:=Platform.AnyCpu, generalDiagnosticOption:=ReportDiagnostic.Default, specificDiagnosticOptions:=Nothing, concurrentBuild:=True, deterministic:=True, xmlReferenceResolver:=Nothing, sourceReferenceResolver:=Nothing, metadataReferenceResolver:=Nothing, assemblyIdentityComparer:=Nothing, strongNameProvider:=Nothing, publicSign:=False, reportSuppressedDiagnostics:=False, metadataImportOptions:=MetadataImportOptions.Public) Yield defaultOptions Yield defaultOptions.WithOptimizationLevel(OptimizationLevel.Release) Yield defaultOptions.WithDebugPlusMode(True) Yield defaultOptions.WithOptimizationLevel(OptimizationLevel.Release).WithDebugPlusMode(True) Next End Function Private Iterator Function GetParseOptions() As IEnumerable(Of VisualBasicParseOptions) Dim parseOptions As New VisualBasicParseOptions() Yield parseOptions Yield parseOptions.WithLanguageVersion(LanguageVersion.VisualBasic15_3) ' https://github.com/dotnet/roslyn/issues/44802 tracks ' enabling preprocessor symbol validation for VB ' Yield parseOptions.WithPreprocessorSymbols({New KeyValuePair(Of String, Object)("TestPre", True), New KeyValuePair(Of String, Object)("TestPreTwo", True)}) End Function End Class
' Licensed to the .NET Foundation under one or more 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.Reflection.Metadata Imports System.Reflection.PortableExecutable Imports System.Text Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Debugging Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.PDB Public Class VisualBasicDeterministicBuildCompilationTests Inherits BasicTestBase Implements IEnumerable(Of Object()) Private Sub VerifyCompilationOptions(originalOptions As VisualBasicCompilationOptions, compilationOptionsBlobReader As BlobReader, emitOptions As EmitOptions, compilation As VisualBasicCompilation) Dim pdbOptions = DeterministicBuildCompilationTestHelpers.ParseCompilationOptions(compilationOptionsBlobReader) DeterministicBuildCompilationTestHelpers.AssertCommonOptions(emitOptions, originalOptions, compilation, pdbOptions) ' See VisualBasicCompilation.SerializeForPdb for options that are added pdbOptions.VerifyPdbOption("checked", originalOptions.CheckOverflow) pdbOptions.VerifyPdbOption("strict", originalOptions.OptionStrict) Assert.Equal(originalOptions.ParseOptions.LanguageVersion.MapSpecifiedToEffectiveVersion().ToDisplayString(), pdbOptions("language-version")) pdbOptions.VerifyPdbOption( "define", originalOptions.ParseOptions.PreprocessorSymbols, isDefault:=Function(v) v.IsEmpty, toString:=Function(v) String.Join(",", v.Select(Function(p) If(p.Value IsNot Nothing, $"{p.Key}=""{p.Value}""", p.Key)))) End Sub Private Sub TestDeterministicCompilationVB(syntaxTrees As SyntaxTree(), compilationOptions As VisualBasicCompilationOptions, emitOptions As EmitOptions, ParamArray metadataReferences() As TestMetadataReferenceInfo) Dim tf = TargetFramework.NetStandard20 Dim originalCompilation = CreateCompilation( syntaxTrees, references:=metadataReferences.SelectAsArray(Of MetadataReference)(Function(r) r.MetadataReference), options:=compilationOptions, targetFramework:=tf) Dim peBlob = originalCompilation.EmitToArray(emitOptions) Using peReader As PEReader = New PEReader(peBlob) Dim entries = peReader.ReadDebugDirectory() AssertEx.Equal({DebugDirectoryEntryType.CodeView, DebugDirectoryEntryType.PdbChecksum, DebugDirectoryEntryType.Reproducible, DebugDirectoryEntryType.EmbeddedPortablePdb}, entries.Select(Of DebugDirectoryEntryType)(Function(e) e.Type)) Dim codeView = entries(0) Dim checksum = entries(1) Dim reproducible = entries(2) Dim embedded = entries(3) Using embeddedPdb As MetadataReaderProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embedded) Dim pdbReader = embeddedPdb.GetMetadataReader() Dim metadataReferenceReader = DeterministicBuildCompilationTestHelpers.GetSingleBlob(PortableCustomDebugInfoKinds.CompilationMetadataReferences, pdbReader) Dim compilationOptionsReader = DeterministicBuildCompilationTestHelpers.GetSingleBlob(PortableCustomDebugInfoKinds.CompilationOptions, pdbReader) VerifyCompilationOptions(compilationOptions, compilationOptionsReader, emitOptions, originalCompilation) DeterministicBuildCompilationTestHelpers.VerifyReferenceInfo(metadataReferences, tf, metadataReferenceReader) End Using End Using End Sub <Theory> <ClassData(GetType(VisualBasicDeterministicBuildCompilationTests))> Public Sub PortablePdb_DeterministicCompilation(compilationOptions As VisualBasicCompilationOptions, emitOptions As EmitOptions) Dim sourceOne = Parse(" Class C1 End Class", fileName:="one.vb", options:=compilationOptions.ParseOptions, encoding:=Encoding.UTF8) Dim sourceTwo = Parse(" Class C2 End Class", fileName:="two.vb", options:=compilationOptions.ParseOptions, encoding:=New UTF8Encoding(encoderShouldEmitUTF8Identifier:=False)) Dim referenceSourceOne = <compilation> <file name="b.vb"> Public Class SomeClass End Class Public Class SomeOtherClass End Class </file> </compilation> Dim referenceSourceTwo = <compilation> <file name="b.vb"> Public Class SomeClass End Class Public Class SomeOtherClass End Class </file> </compilation> Dim referenceOneCompilation = CreateCompilation(referenceSourceOne, options:=TestOptions.DebugDll) Dim referenceTwoCompilation = CreateCompilation(referenceSourceTwo, options:=TestOptions.DebugDll) Using referenceOne As TestMetadataReferenceInfo = TestMetadataReferenceInfo.Create(referenceOneCompilation, "abcd.dll", EmitOptions.Default) Using referenceTwo As TestMetadataReferenceInfo = TestMetadataReferenceInfo.Create(referenceTwoCompilation, "efgh.dll", EmitOptions.Default) TestDeterministicCompilationVB({sourceOne, sourceTwo}, compilationOptions, emitOptions, referenceOne, referenceTwo) End Using End Using End Sub <ConditionalTheory(GetType(DesktopOnly))> <ClassData(GetType(VisualBasicDeterministicBuildCompilationTests))> Public Sub PortablePdb_DeterministicCompilationWithSJIS(compilationOptions As VisualBasicCompilationOptions, emitOptions As EmitOptions) Dim sourceOne = Parse(" Class C1 End Class", fileName:="one.vb", options:=compilationOptions.ParseOptions, encoding:=Encoding.UTF8) Dim sourceTwo = Parse(" Class C2 End Class", fileName:="two.vb", options:=compilationOptions.ParseOptions, encoding:=New UTF8Encoding(encoderShouldEmitUTF8Identifier:=False)) Dim sourceThree = Parse(" Class C3 End Class", fileName:="three.vb", options:=compilationOptions.ParseOptions, encoding:=Encoding.GetEncoding(932)) ' SJIS encoding Dim referenceSourceOne = <compilation> <file name="b.vb"> Public Class SomeClass End Class Public Class SomeOtherClass End Class </file> </compilation> Dim referenceSourceTwo = <compilation> <file name="b.vb"> Public Class SomeClass End Class Public Class SomeOtherClass End Class </file> </compilation> Dim referenceOneCompilation = CreateCompilation(referenceSourceOne, options:=TestOptions.DebugDll) Dim referenceTwoCompilation = CreateCompilation(referenceSourceTwo, options:=TestOptions.DebugDll) Using referenceOne As TestMetadataReferenceInfo = TestMetadataReferenceInfo.Create(referenceOneCompilation, "abcd.dll", EmitOptions.Default) Using referenceTwo As TestMetadataReferenceInfo = TestMetadataReferenceInfo.Create(referenceTwoCompilation, "efgh.dll", EmitOptions.Default) TestDeterministicCompilationVB({sourceOne, sourceTwo, sourceThree}, compilationOptions, emitOptions, referenceOne, referenceTwo) End Using End Using End Sub Public Iterator Function GetEnumerator() As IEnumerator(Of Object()) Implements IEnumerable(Of Object()).GetEnumerator For Each compilationOptions As VisualBasicCompilationOptions In GetCompilationOptions() For Each emitOptions As EmitOptions In GetEmitOptions() Yield {compilationOptions, emitOptions} Next Next End Function Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return GetEnumerator() End Function Private Iterator Function GetEmitOptions() As IEnumerable(Of EmitOptions) Dim emitOptions = New EmitOptions(debugInformationFormat:=DebugInformationFormat.Embedded) Yield emitOptions Yield emitOptions.WithDefaultSourceFileEncoding(Encoding.UTF8) End Function Private Iterator Function GetCompilationOptions() As IEnumerable(Of VisualBasicCompilationOptions) For Each parseOption As VisualBasicParseOptions In GetParseOptions() ' Provide non default options for to test that they are being serialized ' to the pdb correctly. It needs to produce a compilation to be emitted, but otherwise ' everything should be non-default if possible. Diagnostic settings are ignored ' because they won't be serialized. ' Use constructor that requires all arguments. If New arguments are added, it's possible they need to be ' included in the pdb serialization And added to tests here Dim defaultOptions = New VisualBasicCompilationOptions( OutputKind.DynamicallyLinkedLibrary, moduleName:=Nothing, mainTypeName:=Nothing, scriptClassName:=WellKnownMemberNames.DefaultScriptClassName, globalImports:={GlobalImport.Parse("System")}, rootNamespace:=Nothing, optionStrict:=OptionStrict.Off, optionInfer:=True, optionExplicit:=True, optionCompareText:=False, parseOptions:=parseOption, embedVbCoreRuntime:=False, optimizationLevel:=OptimizationLevel.Debug, checkOverflow:=True, cryptoKeyContainer:=Nothing, cryptoKeyFile:=Nothing, cryptoPublicKey:=Nothing, delaySign:=Nothing, platform:=Platform.AnyCpu, generalDiagnosticOption:=ReportDiagnostic.Default, specificDiagnosticOptions:=Nothing, concurrentBuild:=True, deterministic:=True, xmlReferenceResolver:=Nothing, sourceReferenceResolver:=Nothing, metadataReferenceResolver:=Nothing, assemblyIdentityComparer:=Nothing, strongNameProvider:=Nothing, publicSign:=False, reportSuppressedDiagnostics:=False, metadataImportOptions:=MetadataImportOptions.Public) Yield defaultOptions Yield defaultOptions.WithOptimizationLevel(OptimizationLevel.Release) Yield defaultOptions.WithDebugPlusMode(True) Yield defaultOptions.WithOptimizationLevel(OptimizationLevel.Release).WithDebugPlusMode(True) Next End Function Private Iterator Function GetParseOptions() As IEnumerable(Of VisualBasicParseOptions) Dim parseOptions As New VisualBasicParseOptions() Yield parseOptions Yield parseOptions.WithLanguageVersion(LanguageVersion.VisualBasic15_3) ' https://github.com/dotnet/roslyn/issues/44802 tracks ' enabling preprocessor symbol validation for VB ' Yield parseOptions.WithPreprocessorSymbols({New KeyValuePair(Of String, Object)("TestPre", True), New KeyValuePair(Of String, Object)("TestPreTwo", True)}) End Function End Class
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Workspaces/Core/Portable/Workspace/Host/Metadata/IMetadataService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Host { internal interface IMetadataService : IWorkspaceService { PortableExecutableReference GetReference(string resolvedPath, MetadataReferenceProperties properties); } }
// Licensed to the .NET Foundation under one or more 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 namespace Microsoft.CodeAnalysis.Host { internal interface IMetadataService : IWorkspaceService { PortableExecutableReference GetReference(string resolvedPath, MetadataReferenceProperties properties); } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/DkmExceptionUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Debugging { internal static partial class DkmExceptionUtilities { internal const int COR_E_BADIMAGEFORMAT = unchecked((int)0x8007000b); internal const int CORDBG_E_MISSING_METADATA = unchecked((int)0x80131c35); internal static bool IsBadOrMissingMetadataException(Exception e) { return e is ObjectDisposedException || e.HResult == COR_E_BADIMAGEFORMAT || e.HResult == CORDBG_E_MISSING_METADATA; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Debugging { internal static partial class DkmExceptionUtilities { internal const int COR_E_BADIMAGEFORMAT = unchecked((int)0x8007000b); internal const int CORDBG_E_MISSING_METADATA = unchecked((int)0x80131c35); internal static bool IsBadOrMissingMetadataException(Exception e) { return e is ObjectDisposedException || e.HResult == COR_E_BADIMAGEFORMAT || e.HResult == CORDBG_E_MISSING_METADATA; } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Workspaces/Remote/ServiceHub/Host/ChecksumSynchronizer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Serialization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { internal class ChecksumSynchronizer { // make sure there is always only 1 bulk synchronization private static readonly SemaphoreSlim s_gate = new SemaphoreSlim(initialCount: 1); private readonly AssetProvider _assetProvider; public ChecksumSynchronizer(AssetProvider assetProvider) => _assetProvider = assetProvider; public async Task SynchronizeAssetsAsync(IEnumerable<Checksum> checksums, CancellationToken cancellationToken) { using (await s_gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { await SynchronizeAssets_NoLockAsync(checksums, cancellationToken).ConfigureAwait(false); } } public async Task SynchronizeSolutionAssetsAsync(Checksum solutionChecksum, CancellationToken cancellationToken) { using (await s_gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { // this will make 4 round trip to data source (VS) to get all assets that belong to the given solution checksum // first, get solution checksum object for the given solution checksum var solutionChecksumObject = await _assetProvider.GetAssetAsync<SolutionStateChecksums>(solutionChecksum, cancellationToken).ConfigureAwait(false); // second, get direct children of the solution await SynchronizeAssets_NoLockAsync(solutionChecksumObject.Children, cancellationToken).ConfigureAwait(false); // third and last get direct children for all projects and documents in the solution await SynchronizeProjectAssets_NoLockAsync(solutionChecksumObject.Projects, cancellationToken).ConfigureAwait(false); } } public async Task SynchronizeProjectAssetsAsync(IEnumerable<Checksum> projectChecksums, CancellationToken cancellationToken) { using (await s_gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { await SynchronizeProjectAssets_NoLockAsync(projectChecksums, cancellationToken).ConfigureAwait(false); } } private async Task SynchronizeProjectAssets_NoLockAsync(IEnumerable<Checksum> projectChecksums, CancellationToken cancellationToken) { // get children of project checksum objects at once await SynchronizeProjectsAsync(projectChecksums, cancellationToken).ConfigureAwait(false); // get children of document checksum objects at once using var pooledObject = SharedPools.Default<HashSet<Checksum>>().GetPooledObject(); var checksums = pooledObject.Object; foreach (var projectChecksum in projectChecksums) { var projectChecksumObject = await _assetProvider.GetAssetAsync<ProjectStateChecksums>(projectChecksum, cancellationToken).ConfigureAwait(false); await CollectChecksumChildrenAsync(checksums, projectChecksumObject.Documents, cancellationToken).ConfigureAwait(false); await CollectChecksumChildrenAsync(checksums, projectChecksumObject.AdditionalDocuments, cancellationToken).ConfigureAwait(false); await CollectChecksumChildrenAsync(checksums, projectChecksumObject.AnalyzerConfigDocuments, cancellationToken).ConfigureAwait(false); } await _assetProvider.SynchronizeAssetsAsync(checksums, cancellationToken).ConfigureAwait(false); } private async Task SynchronizeProjectsAsync(IEnumerable<Checksum> projectChecksums, CancellationToken cancellationToken) { // get children of project checksum objects at once using var pooledObject = SharedPools.Default<HashSet<Checksum>>().GetPooledObject(); var checksums = pooledObject.Object; await CollectChecksumChildrenAsync(checksums, projectChecksums, cancellationToken).ConfigureAwait(false); await _assetProvider.SynchronizeAssetsAsync(checksums, cancellationToken).ConfigureAwait(false); } private async Task SynchronizeAssets_NoLockAsync(IEnumerable<object> checksumOrCollections, CancellationToken cancellationToken) { // get children of solution checksum object at once using var pooledObject = SharedPools.Default<HashSet<Checksum>>().GetPooledObject(); var checksums = pooledObject.Object; AddIfNeeded(checksums, checksumOrCollections); await _assetProvider.SynchronizeAssetsAsync(checksums, cancellationToken).ConfigureAwait(false); } private async Task CollectChecksumChildrenAsync(HashSet<Checksum> set, IEnumerable<Checksum> checksums, CancellationToken cancellationToken) { foreach (var checksum in checksums) { var checksumObject = await _assetProvider.GetAssetAsync<ChecksumWithChildren>(checksum, cancellationToken).ConfigureAwait(false); AddIfNeeded(set, checksumObject.Children); } } private void AddIfNeeded(HashSet<Checksum> checksums, IEnumerable<object> checksumOrCollections) { foreach (var checksumOrCollection in checksumOrCollections) { switch (checksumOrCollection) { case Checksum checksum: AddIfNeeded(checksums, checksum); continue; case ChecksumCollection checksumCollection: AddIfNeeded(checksums, checksumCollection); continue; } throw ExceptionUtilities.UnexpectedValue(checksumOrCollection); } } private void AddIfNeeded(HashSet<Checksum> checksums, Checksum checksum) { if (checksum != Checksum.Null) { if (!_assetProvider.EnsureCacheEntryIfExists(checksum)) { checksums.Add(checksum); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Serialization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { internal class ChecksumSynchronizer { // make sure there is always only 1 bulk synchronization private static readonly SemaphoreSlim s_gate = new SemaphoreSlim(initialCount: 1); private readonly AssetProvider _assetProvider; public ChecksumSynchronizer(AssetProvider assetProvider) => _assetProvider = assetProvider; public async Task SynchronizeAssetsAsync(IEnumerable<Checksum> checksums, CancellationToken cancellationToken) { using (await s_gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { await SynchronizeAssets_NoLockAsync(checksums, cancellationToken).ConfigureAwait(false); } } public async Task SynchronizeSolutionAssetsAsync(Checksum solutionChecksum, CancellationToken cancellationToken) { using (await s_gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { // this will make 4 round trip to data source (VS) to get all assets that belong to the given solution checksum // first, get solution checksum object for the given solution checksum var solutionChecksumObject = await _assetProvider.GetAssetAsync<SolutionStateChecksums>(solutionChecksum, cancellationToken).ConfigureAwait(false); // second, get direct children of the solution await SynchronizeAssets_NoLockAsync(solutionChecksumObject.Children, cancellationToken).ConfigureAwait(false); // third and last get direct children for all projects and documents in the solution await SynchronizeProjectAssets_NoLockAsync(solutionChecksumObject.Projects, cancellationToken).ConfigureAwait(false); } } public async Task SynchronizeProjectAssetsAsync(IEnumerable<Checksum> projectChecksums, CancellationToken cancellationToken) { using (await s_gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { await SynchronizeProjectAssets_NoLockAsync(projectChecksums, cancellationToken).ConfigureAwait(false); } } private async Task SynchronizeProjectAssets_NoLockAsync(IEnumerable<Checksum> projectChecksums, CancellationToken cancellationToken) { // get children of project checksum objects at once await SynchronizeProjectsAsync(projectChecksums, cancellationToken).ConfigureAwait(false); // get children of document checksum objects at once using var pooledObject = SharedPools.Default<HashSet<Checksum>>().GetPooledObject(); var checksums = pooledObject.Object; foreach (var projectChecksum in projectChecksums) { var projectChecksumObject = await _assetProvider.GetAssetAsync<ProjectStateChecksums>(projectChecksum, cancellationToken).ConfigureAwait(false); await CollectChecksumChildrenAsync(checksums, projectChecksumObject.Documents, cancellationToken).ConfigureAwait(false); await CollectChecksumChildrenAsync(checksums, projectChecksumObject.AdditionalDocuments, cancellationToken).ConfigureAwait(false); await CollectChecksumChildrenAsync(checksums, projectChecksumObject.AnalyzerConfigDocuments, cancellationToken).ConfigureAwait(false); } await _assetProvider.SynchronizeAssetsAsync(checksums, cancellationToken).ConfigureAwait(false); } private async Task SynchronizeProjectsAsync(IEnumerable<Checksum> projectChecksums, CancellationToken cancellationToken) { // get children of project checksum objects at once using var pooledObject = SharedPools.Default<HashSet<Checksum>>().GetPooledObject(); var checksums = pooledObject.Object; await CollectChecksumChildrenAsync(checksums, projectChecksums, cancellationToken).ConfigureAwait(false); await _assetProvider.SynchronizeAssetsAsync(checksums, cancellationToken).ConfigureAwait(false); } private async Task SynchronizeAssets_NoLockAsync(IEnumerable<object> checksumOrCollections, CancellationToken cancellationToken) { // get children of solution checksum object at once using var pooledObject = SharedPools.Default<HashSet<Checksum>>().GetPooledObject(); var checksums = pooledObject.Object; AddIfNeeded(checksums, checksumOrCollections); await _assetProvider.SynchronizeAssetsAsync(checksums, cancellationToken).ConfigureAwait(false); } private async Task CollectChecksumChildrenAsync(HashSet<Checksum> set, IEnumerable<Checksum> checksums, CancellationToken cancellationToken) { foreach (var checksum in checksums) { var checksumObject = await _assetProvider.GetAssetAsync<ChecksumWithChildren>(checksum, cancellationToken).ConfigureAwait(false); AddIfNeeded(set, checksumObject.Children); } } private void AddIfNeeded(HashSet<Checksum> checksums, IEnumerable<object> checksumOrCollections) { foreach (var checksumOrCollection in checksumOrCollections) { switch (checksumOrCollection) { case Checksum checksum: AddIfNeeded(checksums, checksum); continue; case ChecksumCollection checksumCollection: AddIfNeeded(checksums, checksumCollection); continue; } throw ExceptionUtilities.UnexpectedValue(checksumOrCollection); } } private void AddIfNeeded(HashSet<Checksum> checksums, Checksum checksum) { if (checksum != Checksum.Null) { if (!_assetProvider.EnsureCacheEntryIfExists(checksum)) { checksums.Add(checksum); } } } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_Tuples.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests_Tuples : WellKnownAttributesTestBase { private static readonly string s_tuplesTestSource = @" using System; public class Base0 { } public class Base1<T> { } public class Base2<T, U> { } public class Outer<T> : Base1<(int key, int val)> { public class Inner<U, V> : Base2<(int key2, int val2), V> { public class InnerInner<W> : Base1<(int key3, int val3)> { } } } public class Derived<T> : Outer<(int e1, (int e2, int e3) e4)>.Inner< Outer<(int e5, int e6)>.Inner<(int e7, int e8)[], (int e9, int e10)>.InnerInner<int>[], ((int e11, int e12) e13, int e14)> .InnerInner<((int e15, int e16) e17, (int e18, Base1<(int e19, int e20)> e21) e22)> { public static (int e1, int e2) Field1; public static (int e1, int e2) Field2; public static Base1<(int e1, (int e2, int e3) e4)> Field3; public static ValueTuple<Base1<(int e1, (int, (dynamic, dynamic)) e2)>, int> Field4; public static Outer<(object e1, dynamic e2)> .Inner<(dynamic e3, object e4), ValueTuple<dynamic, dynamic>> Field5; // No names public static Base1<(int, ValueTuple<int, ValueTuple>)> Field6; public static ValueTuple Field7; // Long tuples public static (int e1, int e2, int e3, int e4, int e5, int e6, int e7, int e8, int e9) Field8; public static Base1<(int e1, int e2, int e3, int e4, int e5, int e6, int e7, int e8, int e9)> Field9; public static (int e1, int e2) Method1() => (0, 0); public static void Method2((int e1, int e2) x) { } public static (int e1, int e2) Method3((int e3, int e4) x) => (0, 0); public static (int e1, int e2) Method4(ref (int e3, int e4) x) => x; public static ((int, (object, (dynamic, object)), object, int), ValueTuple) Method5(ref (object,dynamic) x) => ((0, (null, (null, null)), null, 0), default(ValueTuple)); public static (int e1, int e2, int e3, int e4, int e5, int e6, int e7, int e8, int e9) Method6() => (0, 0, 0, 0, 0, 0, 0, 0, 0); public static (int e1, int e2) Prop1 => (0, 0); public static (int e1, int e2) Prop2 { get; set; } public (int e1, int e2) this[(int e3, int e4) param] { get { return param; } set {} } public delegate void Delegate1<V>(object sender, ValueTuple<V, ((dynamic e1, dynamic e2, object e3) e4, dynamic e5), (dynamic, object)> args); public static event Delegate1<(dynamic e1, ValueTuple<(dynamic e2, dynamic e3)> e4)> Event1 { add { } remove { } } }"; private static readonly MetadataReference[] s_attributeRefs = { ValueTupleRef, SystemRuntimeFacadeRef, SystemCoreRef, CSharpRef }; [Fact] public void TestCompile() { CompileAndVerifyWithMscorlib40(s_tuplesTestSource, options: TestOptions.ReleaseDll, references: s_attributeRefs); } [Fact] public void TestTupleAttributes() { var comp = CreateCompilationWithMscorlib40(s_tuplesTestSource, options: TestOptions.UnsafeReleaseDll, references: s_attributeRefs); CompileAndVerify(comp, verify: Verification.Passes, symbolValidator: module => { TupleAttributeValidator.ValidateTupleAttributes(module); }); } [Fact] public void TupleAttributeWithOnlyOneConstructor() { var comp = CreateCompilationWithMscorlib40( s_tuplesTestSource + TestResources.NetFX.ValueTuple.tuplelib_cs + @" namespace System.Runtime.CompilerServices { /// <summary> /// Indicates that the use of <see cref=""System.ValueTuple""/> on a member is meant to be treated as a tuple with element names. /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue | AttributeTargets.Class | AttributeTargets.Struct )] public sealed class TupleElementNamesAttribute : Attribute { public TupleElementNamesAttribute(string[] transformNames) { } } }", references: new[] { SystemCoreRef }, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics(); CompileAndVerify(comp, symbolValidator: module => { TupleAttributeValidator.ValidateTupleAttributes(module); }); } [Fact] public void TupleLambdaParametersMissingString() { var source0 = @"namespace System { public class Object { } public class ValueType { } public struct Void { } public struct IntPtr { } public struct Int32 { } public class MulticastDelegate { } }"; var source1 = @"delegate void D<T>(T t); class C { static void Main() { D<(int x, int y)> d = o => { }; d((0, 0)); } }"; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); comp = CreateEmptyCompilation(source1, references: s_attributeRefs.Concat(new[] { ref0 })); comp.VerifyDiagnostics( // (6,11): error CS0518: Predefined type 'System.String' is not defined or imported // D<(int x, int y)> d = o => { }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "(int x, int y)").WithArguments("System.String").WithLocation(6, 11), // (6,11): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. // D<(int x, int y)> d = o => { }; Diagnostic(ErrorCode.ERR_NoTypeDef, "(int x, int y)").WithArguments("System.ValueType", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089").WithLocation(6, 11), // (7,11): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. // d((0, 0)); Diagnostic(ErrorCode.ERR_NoTypeDef, "(0, 0)").WithArguments("System.ValueType", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089").WithLocation(7, 11) ); } [Fact] public void TupleInDeclarationFailureWithoutString() { var source0 = @"namespace System { public class Object { } public class ValueType { } public struct Void { } public struct IntPtr { } public struct Int32 { } }"; var source1 = @" class C { static (int x, int y) M() => (0, 0); }"; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); comp = CreateEmptyCompilation(source1, references: new[] { ref0, ValueTupleRef }); comp.VerifyDiagnostics( // (4,12): error CS0518: Predefined type 'System.String' is not defined or imported // static (int x, int y) M() => (0, 0); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "(int x, int y)").WithArguments("System.String").WithLocation(4, 12), // (4,12): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. // static (int x, int y) M() => (0, 0); Diagnostic(ErrorCode.ERR_NoTypeDef, "(int x, int y)").WithArguments("System.ValueType", "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").WithLocation(4, 12), // (4,34): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. // static (int x, int y) M() => (0, 0); Diagnostic(ErrorCode.ERR_NoTypeDef, "(0, 0)").WithArguments("System.ValueType", "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").WithLocation(4, 34) ); } [Fact] public void RoundTrip() { ModuleSymbol sourceModule = null; ModuleSymbol peModule = null; CompileAndVerifyWithMscorlib40(s_tuplesTestSource, options: TestOptions.UnsafeReleaseDll, references: s_attributeRefs, verify: Verification.Passes, sourceSymbolValidator: m => sourceModule = m, symbolValidator: m => peModule = m); var srcTypes = sourceModule.GlobalNamespace.GetTypeMembers(); var peTypes = peModule.GlobalNamespace.GetTypeMembers() .WhereAsArray(t => t.Name != "<Module>"); Assert.Equal(srcTypes.Length, peTypes.Length); for (int i = 0; i < srcTypes.Length; i++) { var srcType = srcTypes[i]; var peType = peTypes[i]; Assert.Equal(ToTestString(srcType.BaseType()), ToTestString(peType.BaseType())); var srcMembers = srcType.GetMembers() .Where(m => !m.Name.Contains("k__BackingField")) .Select(ToTestString) .ToList(); var peMembers = peType.GetMembers() .Select(ToTestString) .ToList(); srcMembers.Sort(); peMembers.Sort(); AssertEx.Equal(srcMembers, peMembers); } } private static string ToTestString(Symbol symbol) { var typeSymbols = ArrayBuilder<TypeSymbol>.GetInstance(); switch (symbol.Kind) { case SymbolKind.Method: var methodSymbol = (MethodSymbol)symbol; typeSymbols.Add(methodSymbol.ReturnType); foreach (var parameterType in methodSymbol.ParameterTypesWithAnnotations) { typeSymbols.Add(parameterType.Type); } break; case SymbolKind.NamedType: var namedType = (NamedTypeSymbol)symbol; typeSymbols.Add(namedType.BaseType() ?? namedType); break; case SymbolKind.Field: typeSymbols.Add(((FieldSymbol)symbol).Type); break; case SymbolKind.Property: typeSymbols.Add(((PropertySymbol)symbol).Type); break; case SymbolKind.Event: typeSymbols.Add(((EventSymbol)symbol).Type); break; } var symbolString = string.Join(" | ", typeSymbols .Select(s => s.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat))); typeSymbols.Free(); return $"{symbol.Name}: {symbolString}"; } private struct TupleAttributeValidator { private readonly NamedTypeSymbol _base0Class, _base1Class, _base2Class, _outerClass, _derivedClass; private TupleAttributeValidator(ModuleSymbol module) { var globalNs = module.GlobalNamespace; _base0Class = globalNs.GetTypeMember("Base0"); _base1Class = globalNs.GetTypeMember("Base1"); _base2Class = globalNs.GetTypeMember("Base2"); _outerClass = globalNs.GetTypeMember("Outer"); _derivedClass = globalNs.GetTypeMember("Derived"); } internal static void ValidateTupleAttributes(ModuleSymbol module) { var validator = new TupleAttributeValidator(module); validator.ValidateAttributesOnNamedTypes(); validator.ValidateAttributesOnFields(); validator.ValidateAttributesOnMethods(); validator.ValidateAttributesOnProperties(); validator.ValidateAttributesOnEvents(); validator.ValidateAttributesOnDelegates(); } private void ValidateAttributesOnDelegates() { // public delegate void Delegate1<T>(object sender, // ValueTuple<T, // ((dynamic e1, dynamic e2, object e3) e4, dynamic e5), // (dynamic, object)> args); var delegate1 = _derivedClass.GetMember<NamedTypeSymbol>("Delegate1"); Assert.NotNull(delegate1); Assert.True(delegate1.IsDelegateType()); var invokeMethod = delegate1.DelegateInvokeMethod; Assert.NotNull(invokeMethod); ValidateTupleNameAttribute(invokeMethod.GetAttributes(), expectedTupleNamesAttribute: false); Assert.Equal(2, invokeMethod.ParameterCount); var sender = invokeMethod.Parameters[0]; Assert.Equal("sender", sender.Name); Assert.Equal(SpecialType.System_Object, sender.Type.SpecialType); ValidateTupleNameAttribute(sender.GetAttributes(), expectedTupleNamesAttribute: false); var args = invokeMethod.Parameters[1]; Assert.Equal("args", args.Name); var expectedElementNames = new[] { null, null, null, "e4", "e5", "e1", "e2", "e3", null, null }; ValidateTupleNameAttribute(args.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); AttributeTests_Dynamic.DynamicAttributeValidator.ValidateDynamicAttribute( args.GetAttributes(), expectedDynamicAttribute: true, expectedTransformFlags: new[] { false, false, false, false, true, true, false, true, false, true, false }); } private void ValidateAttributesOnEvents() { // public static event Delegate1<(dynamic e1, // ValueTuple<(dynamic e2, dynamic e3)> e4)> Event1; var event1 = _derivedClass.GetMember<EventSymbol>("Event1"); Assert.NotNull(event1); ValidateTupleNameAttribute(event1.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: new[] { "e1", "e4", null, "e2", "e3" }); AttributeTests_Dynamic.DynamicAttributeValidator.ValidateDynamicAttribute( event1.GetAttributes(), expectedDynamicAttribute: true, expectedTransformFlags: new[] { false, false, false, true, false, false, true, true }); } private void ValidateAttributesOnNamedTypes() { // public class Base0 { } ValidateTupleNameAttribute(_base0Class.GetAttributes(), expectedTupleNamesAttribute: false); // public class Base1<T> { } ValidateTupleNameAttribute(_base1Class.GetAttributes(), expectedTupleNamesAttribute: false); // public class Base2<T, U> { } ValidateTupleNameAttribute(_base2Class.GetAttributes(), expectedTupleNamesAttribute: false); // public class Outer<T> : Base1<(int key, int val)> Assert.True(_outerClass.BaseType().ContainsTuple()); var expectedElementNames = new[] { "key", "val" }; ValidateTupleNameAttribute(_outerClass.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); // public class Derived<T> : Outer<(int e1, (int e2, int e3) e4)>.Inner< // Outer<(int e5, int e6)>.Inner<(int e7, int e8)[], (int e9, int e10)>.InnerInner<int>[], // ((int e11, int e12) e13, int e14)> // .InnerInner<((int e15, int e16) e17, (int e18, Base1<(int e19, int e20)> e21) e22)> expectedElementNames = new[] { "e1", "e4", "e2", "e3", "e5", "e6", "e7", "e8", "e9", "e10", "e13", "e14", "e11", "e12", "e17", "e22", "e15", "e16", "e18", "e21", "e19", "e20" }; ValidateTupleNameAttribute(_derivedClass.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); } private void ValidateAttributesOnFields() { // public static (int e1, int e2) Field1; var field1 = _derivedClass.GetMember<FieldSymbol>("Field1"); var expectedElementNames = new[] { "e1", "e2" }; ValidateTupleNameAttribute(field1.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); // public static (int e1, int e2) Field2; var field2 = _derivedClass.GetMember<FieldSymbol>("Field2"); expectedElementNames = new[] { "e1", "e2" }; ValidateTupleNameAttribute(field2.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); // public static Base1<(int e1, (int e2, int e3) e4)> Field3; var field3 = _derivedClass.GetMember<FieldSymbol>("Field3"); expectedElementNames = new[] { "e1", "e4", "e2", "e3" }; ValidateTupleNameAttribute(field3.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); // public static ValueTuple<Base1<(int e1, (int, (dynamic, dynamic)) e2)>, int> Field4; var field4 = _derivedClass.GetMember<FieldSymbol>("Field4"); expectedElementNames = new[] { null, null, "e1", "e2", null, null, null, null }; ValidateTupleNameAttribute(field4.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); AttributeTests_Dynamic.DynamicAttributeValidator.ValidateDynamicAttribute( field4.GetAttributes(), expectedDynamicAttribute: true, expectedTransformFlags: new[] { false, false, false, false, false, false, false, true, true, false }); // public static Outer<(object e1, dynamic e2)> // .Inner<(dynamic e3, object e4), // ValueTuple<dynamic, dynamic>> Field5; var field5 = _derivedClass.GetMember<FieldSymbol>("Field5"); expectedElementNames = new[] { "e1", "e2", "e3", "e4", null, null }; ValidateTupleNameAttribute(field5.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); AttributeTests_Dynamic.DynamicAttributeValidator.ValidateDynamicAttribute( field5.GetAttributes(), expectedDynamicAttribute: true, expectedTransformFlags: new[] { false, false, false, true, false, true, false, false, true, true }); // public static Base1<(int, ValueTuple<int, ValueTuple>)> Field6; var field6 = _derivedClass.GetMember<FieldSymbol>("Field6"); ValidateTupleNameAttribute(field6.GetAttributes(), expectedTupleNamesAttribute: false); var field6Type = Assert.IsType<ConstructedNamedTypeSymbol>(field6.Type); Assert.Equal("Base1", field6Type.Name); Assert.Equal(1, field6Type.TypeParameters.Length); var firstTuple = field6Type.TypeArguments().Single(); Assert.True(firstTuple.IsTupleType); Assert.True(firstTuple.TupleElementNames.IsDefault); Assert.Equal(2, firstTuple.TupleElementTypesWithAnnotations.Length); var secondTuple = firstTuple.TupleElementTypesWithAnnotations[1].Type; Assert.True(secondTuple.IsTupleType); Assert.True(secondTuple.TupleElementNames.IsDefault); Assert.Equal(2, secondTuple.TupleElementTypesWithAnnotations.Length); // public static ValueTuple Field7; var field7 = _derivedClass.GetMember<FieldSymbol>("Field7"); ValidateTupleNameAttribute(field7.GetAttributes(), expectedTupleNamesAttribute: false); Assert.True(field7.Type.IsTupleType); Assert.Empty(field7.Type.TupleElementTypesWithAnnotations); // public static (int e1, int e2, int e3, int e4, int e5, int e6, int e7, int e8, int e9) Field8; var field8 = _derivedClass.GetMember<FieldSymbol>("Field8"); expectedElementNames = new[] { "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", null, null }; ValidateTupleNameAttribute(field8.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); // public static Base<(int e1, int e2, int e3, int e4, int e5, int e6, int e7, int e8, int e9)> Field9; var field9 = _derivedClass.GetMember<FieldSymbol>("Field9"); expectedElementNames = new[] { "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", null, null }; ValidateTupleNameAttribute(field9.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); } private void ValidateAttributesOnMethods() { // public static (int e1, int e2) Method1() => (0, 0); var method1 = _derivedClass.GetMember<MethodSymbol>("Method1"); var expectedElementNames = new[] { "e1", "e2" }; ValidateTupleNameAttribute(method1.GetReturnTypeAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); // public static void Method2((int e1, int e2) x) { } var method2 = _derivedClass.GetMember<MethodSymbol>("Method2"); expectedElementNames = new[] { "e1", "e2" }; ValidateTupleNameAttribute(method2.Parameters.Single().GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); // public static (int e1, int e2) Method3((int e3, int e4) x) => (0, 0); var method3 = _derivedClass.GetMember<MethodSymbol>("Method3"); expectedElementNames = new[] { "e1", "e2" }; ValidateTupleNameAttribute(method3.GetReturnTypeAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); expectedElementNames = new[] { "e3", "e4" }; ValidateTupleNameAttribute(method3.Parameters.Single().GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); // public static (int e1, int e2) Method4(ref (int e3, int e4) x) => x; var method4 = _derivedClass.GetMember<MethodSymbol>("Method4"); expectedElementNames = new[] { "e1", "e2" }; ValidateTupleNameAttribute(method4.GetReturnTypeAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); expectedElementNames = new[] { "e3", "e4" }; ValidateTupleNameAttribute(method4.Parameters.Single().GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); // public static ((int, // (object, (dynamic, object)), // object, // int), // ValueTuple) Method5(ref (object,dynamic) x) => // ((0, (null, (null, null)), null, 0), default(ValueTuple)); var method5 = _derivedClass.GetMember<MethodSymbol>("Method5"); ValidateTupleNameAttribute(method5.GetReturnTypeAttributes(), expectedTupleNamesAttribute: false); ValidateTupleNameAttribute(method5.Parameters.Single().GetAttributes(), expectedTupleNamesAttribute: false); // public static (int e1, int e2, int e3, int e4, int e5, // int e6, int e7, int e8, int e9) Method6() => (0, 0, 0, 0, // 0, 0, 0, 0, 0); var method6 = _derivedClass.GetMember<MethodSymbol>("Method6"); expectedElementNames = new[] { "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", null, null }; ValidateTupleNameAttribute(method6.GetReturnTypeAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); } private void ValidateAttributesOnProperties() { // public static (int e1, int e2) Prop1 => (0, 0); var prop1 = _derivedClass.GetMember("Prop1"); var expectedTupleNames = new[] { "e1", "e2" }; ValidateTupleNameAttribute(prop1.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedTupleNames); // public static (int e1, int e2) Prop2 { get; set; } var prop2 = _derivedClass.GetMember("Prop2"); expectedTupleNames = new[] { "e1", "e2" }; ValidateTupleNameAttribute(prop2.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedTupleNames); // public (int e1, int e2) this[(int e3, int e4) param] var indexer = (PropertySymbol)_derivedClass.GetMember("this[]"); expectedTupleNames = new[] { "e1", "e2" }; ValidateTupleNameAttribute(indexer.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedTupleNames); expectedTupleNames = new[] { "e3", "e4" }; ValidateTupleNameAttribute(indexer.Parameters.Single().GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedTupleNames); } private void ValidateTupleNameAttribute( ImmutableArray<CSharpAttributeData> attributes, bool expectedTupleNamesAttribute, string[] expectedElementNames = null) { var synthesizedTupleElementNamesAttr = attributes.Where(attr => string.Equals(attr.AttributeClass.Name, "TupleElementNamesAttribute", StringComparison.Ordinal)); if (!expectedTupleNamesAttribute) { Assert.Empty(synthesizedTupleElementNamesAttr); Assert.Null(expectedElementNames); } else { var tupleAttr = synthesizedTupleElementNamesAttr.Single(); Assert.Equal("System.Runtime.CompilerServices.TupleElementNamesAttribute", tupleAttr.AttributeClass.ToTestDisplayString()); Assert.Equal("System.String[]", tupleAttr.AttributeConstructor.Parameters.Single().TypeWithAnnotations.ToTestDisplayString()); if (expectedElementNames == null) { Assert.True(tupleAttr.CommonConstructorArguments.IsEmpty); } else { var arg = tupleAttr.CommonConstructorArguments.Single(); Assert.Equal(TypedConstantKind.Array, arg.Kind); var actualElementNames = arg.Values.SelectAsArray(TypedConstantString); AssertEx.Equal(expectedElementNames, actualElementNames); } } } private static string TypedConstantString(TypedConstant constant) { Assert.True(constant.Type.SpecialType == SpecialType.System_String); return (string)constant.Value; } } [Fact] public void TupleAttributeMissing() { var comp = CreateCompilationWithMscorlib40( s_tuplesTestSource + TestResources.NetFX.ValueTuple.tuplelib_cs, references: new[] { SystemCoreRef }, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (8,31): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public class Outer<T> : Base1<(int key, int val)> Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int key, int val)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(8, 31), // (16,42): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public class Derived<T> : Outer<(int e1, (int e2, int e3) e4)>.Inner< Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e2, int e3)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(16, 42), // (16,33): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public class Derived<T> : Outer<(int e1, (int e2, int e3) e4)>.Inner< Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e1, (int e2, int e3) e4)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(16, 33), // (17,11): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // Outer<(int e5, int e6)>.Inner<(int e7, int e8)[], (int e9, int e10)>.InnerInner<int>[], Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e5, int e6)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(17, 11), // (17,35): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // Outer<(int e5, int e6)>.Inner<(int e7, int e8)[], (int e9, int e10)>.InnerInner<int>[], Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e7, int e8)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(17, 35), // (17,55): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // Outer<(int e5, int e6)>.Inner<(int e7, int e8)[], (int e9, int e10)>.InnerInner<int>[], Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e9, int e10)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(17, 55), // (18,6): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // ((int e11, int e12) e13, int e14)> Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e11, int e12)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(18, 6), // (18,5): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // ((int e11, int e12) e13, int e14)> Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "((int e11, int e12) e13, int e14)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(18, 5), // (19,18): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // .InnerInner<((int e15, int e16) e17, (int e18, Base1<(int e19, int e20)> e21) e22)> Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e15, int e16)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(19, 18), // (19,58): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // .InnerInner<((int e15, int e16) e17, (int e18, Base1<(int e19, int e20)> e21) e22)> Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e19, int e20)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(19, 58), // (19,42): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // .InnerInner<((int e15, int e16) e17, (int e18, Base1<(int e19, int e20)> e21) e22)> Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e18, Base1<(int e19, int e20)> e21)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(19, 42), // (19,17): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // .InnerInner<((int e15, int e16) e17, (int e18, Base1<(int e19, int e20)> e21) e22)> Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "((int e15, int e16) e17, (int e18, Base1<(int e19, int e20)> e21) e22)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(19, 17), // (10,38): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public class Inner<U, V> : Base2<(int key2, int val2), V> Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int key2, int val2)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(10, 38), // (12,44): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public class InnerInner<W> : Base1<(int key3, int val3)> { } Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int key3, int val3)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(12, 44), // (72,47): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // ValueTuple<(dynamic e2, dynamic e3)> e4)> Event1 Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(dynamic e2, dynamic e3)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(72, 47), // (71,35): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static event Delegate1<(dynamic e1, Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, @"(dynamic e1, ValueTuple<(dynamic e2, dynamic e3)> e4)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(71, 35), // (41,19): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static (int e1, int e2) Method1() => (0, 0); Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e1, int e2)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(41, 19), // (42,32): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static void Method2((int e1, int e2) x) { } Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e1, int e2)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(42, 32), // (43,44): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static (int e1, int e2) Method3((int e3, int e4) x) => (0, 0); Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e3, int e4)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(43, 44), // (43,19): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static (int e1, int e2) Method3((int e3, int e4) x) => (0, 0); Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e1, int e2)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(43, 19), // (44,48): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static (int e1, int e2) Method4(ref (int e3, int e4) x) => x; Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e3, int e4)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(44, 48), // (44,19): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static (int e1, int e2) Method4(ref (int e3, int e4) x) => x; Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e1, int e2)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(44, 19), // (53,19): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static (int e1, int e2, int e3, int e4, int e5, Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, @"(int e1, int e2, int e3, int e4, int e5, int e6, int e7, int e8, int e9)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(53, 19), // (57,19): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static (int e1, int e2) Prop1 => (0, 0); Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e1, int e2)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(57, 19), // (58,19): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static (int e1, int e2) Prop2 { get; set; } Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e1, int e2)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(58, 19), // (60,34): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public (int e1, int e2) this[(int e3, int e4) param] Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e3, int e4)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(60, 34), // (60,12): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public (int e1, int e2) this[(int e3, int e4) param] Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e1, int e2)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(60, 12), // (68,14): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // ((dynamic e1, dynamic e2, object e3) e4, dynamic e5), Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(dynamic e1, dynamic e2, object e3)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(68, 14), // (68,13): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // ((dynamic e1, dynamic e2, object e3) e4, dynamic e5), Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "((dynamic e1, dynamic e2, object e3) e4, dynamic e5)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(68, 13), // (22,19): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static (int e1, int e2) Field2; Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e1, int e2)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(22, 19), // (23,34): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static Base1<(int e1, (int e2, int e3) e4)> Field3; Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e2, int e3)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(23, 34), // (23,25): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static Base1<(int e1, (int e2, int e3) e4)> Field3; Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e1, (int e2, int e3) e4)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(23, 25), // (25,36): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static ValueTuple<Base1<(int e1, (int, (dynamic, dynamic)) e2)>, int> Field4; Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e1, (int, (dynamic, dynamic)) e2)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(25, 36), // (27,25): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static Outer<(object e1, dynamic e2)> Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(object e1, dynamic e2)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(27, 25), // (28,16): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // .Inner<(dynamic e3, object e4), Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(dynamic e3, object e4)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(28, 16), // (36,19): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static (int e1, int e2, int e3, int e4, int e5, Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, @"(int e1, int e2, int e3, int e4, int e5, int e6, int e7, int e8, int e9)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(36, 19), // (38,25): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static Base1<(int e1, int e2, int e3, int e4, int e5, Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, @"(int e1, int e2, int e3, int e4, int e5, int e6, int e7, int e8, int e9)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(38, 25), // (21,19): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static (int e1, int e2) Field1; Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e1, int e2)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(21, 19)); } [Fact] public void ExplicitTupleNamesAttribute() { var text = @" using System; using System.Runtime.CompilerServices; [TupleElementNames(new[] { ""a"", ""b"" })] public class C { [TupleElementNames(new string[] { null, null })] public ValueTuple<int, int> Field1; [TupleElementNames(new[] { ""x"", ""y"" })] public ValueTuple<int, int> Prop1; [return: TupleElementNames(new string[] { null, null })] public ValueTuple<int, int> M([TupleElementNames(new string[] { null})] ValueTuple x) => (0, 0); public delegate void Delegate1<T>(object sender, [TupleElementNames(new[] { ""x"" })]ValueTuple<T> args); [TupleElementNames(new[] { ""y"" })] public event Delegate1<ValueTuple<int>> Event1 { add { } remove { } } [TupleElementNames(new[] { ""a"", ""b"" })] public (int x, int y) this[[TupleElementNames](int a, int b) t] => t; } [TupleElementNames(new[] { ""a"", ""b"" })] public struct S { }"; var comp = CreateCompilationWithMscorlib40(text, references: s_attributeRefs); comp.VerifyDiagnostics( // (31,2): error CS8331: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. // [TupleElementNames(new[] { "a", "b" })] Diagnostic(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, @"TupleElementNames(new[] { ""a"", ""b"" })").WithLocation(31, 2), // (5,2): error CS8331: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. // [TupleElementNames(new[] { "a", "b" })] Diagnostic(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, @"TupleElementNames(new[] { ""a"", ""b"" })").WithLocation(5, 2), // (18,10): error CS8331: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. // [TupleElementNames(new[] { "x" })]ValueTuple<T> args); Diagnostic(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, @"TupleElementNames(new[] { ""x"" })").WithLocation(18, 10), // (11,6): error CS8331: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. // [TupleElementNames(new[] { "x", "y" })] Diagnostic(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, @"TupleElementNames(new[] { ""x"", ""y"" })").WithLocation(11, 6), // (14,14): error CS8331: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. // [return: TupleElementNames(new string[] { null, null })] Diagnostic(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, "TupleElementNames(new string[] { null, null })").WithLocation(14, 14), // (15,36): error CS8331: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. // public ValueTuple<int, int> M([TupleElementNames(new string[] { null})] ValueTuple x) => (0, 0); Diagnostic(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, "TupleElementNames(new string[] { null})").WithLocation(15, 36), // (20,6): error CS0592: Attribute 'TupleElementNames' is not valid on this declaration type. It is only valid on 'class, struct, property, indexer, field, parameter, return' declarations. // [TupleElementNames(new[] { "y" })] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "TupleElementNames").WithArguments("TupleElementNames", "class, struct, property, indexer, field, parameter, return").WithLocation(20, 6), // (27,6): error CS8331: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. // [TupleElementNames(new[] { "a", "b" })] Diagnostic(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, @"TupleElementNames(new[] { ""a"", ""b"" })").WithLocation(27, 6), // (28,33): error CS8331: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. // public (int x, int y) this[[TupleElementNames](int a, int b) t] => t; Diagnostic(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, "TupleElementNames").WithLocation(28, 33), // (8,6): error CS8331: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. // [TupleElementNames(new string[] { null, null })] Diagnostic(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, "TupleElementNames(new string[] { null, null })").WithLocation(8, 6)); } [Fact] [WorkItem(14844, "https://github.com/dotnet/roslyn/issues/14844")] public void AttributesOnTypeConstraints() { var src = @" public interface I1<T> {} public interface I2<T> where T : I1<(int a, int b)> {} public interface I3<T> where T : I1<(int c, int d)> {}"; Action<PEAssembly> validator = assembly => { var reader = assembly.GetMetadataReader(); Action<TypeDefinition, string[]> verifyTupleConstraint = (def, tupleNames) => { var typeParams = def.GetGenericParameters(); Assert.Equal(1, typeParams.Count); var typeParam = reader.GetGenericParameter(typeParams[0]); var constraintHandles = typeParam.GetConstraints(); Assert.Equal(1, constraintHandles.Count); var constraint = reader.GetGenericParameterConstraint(constraintHandles[0]); var attributes = constraint.GetCustomAttributes(); Assert.Equal(1, attributes.Count); var attr = reader.GetCustomAttribute(attributes.Single()); // Verify that the attribute contains an array of matching tuple names var argsReader = reader.GetBlobReader(attr.Value); // Prolog Assert.Equal(1, argsReader.ReadUInt16()); // Array size Assert.Equal(tupleNames.Length, argsReader.ReadInt32()); foreach (var name in tupleNames) { Assert.Equal(name, argsReader.ReadSerializedString()); } }; foreach (var typeHandle in reader.TypeDefinitions) { var def = reader.GetTypeDefinition(typeHandle); var name = reader.GetString(def.Name); switch (name) { case "I1`1": case "<Module>": continue; case "I2`1": verifyTupleConstraint(def, new[] { "a", "b" }); break; case "I3`1": verifyTupleConstraint(def, new[] { "c", "d" }); break; default: throw TestExceptionUtilities.UnexpectedValue(name); } } }; void symbolValidator(ModuleSymbol m) { foreach (var t in m.GlobalNamespace.GetTypeMembers()) { switch (t.Name) { case "I1": case "<Module>": continue; case "I2": verifyTupleImpls(t, new[] { "a", "b" }); break; case "I3": verifyTupleImpls(t, new[] { "c", "d" }); break; } } void verifyTupleImpls(NamedTypeSymbol t, string[] tupleNames) { var typeParam = t.TypeParameters.Single(); var constraint = (NamedTypeSymbol)typeParam.ConstraintTypes().Single(); var typeArg = constraint.TypeArguments().Single(); Assert.True(typeArg.IsTupleType); Assert.Equal(tupleNames, typeArg.TupleElementNames); } } CompileAndVerifyWithMscorlib40(src, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, assemblyValidator: validator, symbolValidator: symbolValidator); } [Fact] [WorkItem(14844, "https://github.com/dotnet/roslyn/issues/14844")] public void AttributesOnInterfaceImplementations() { var src = @" public interface I1<T> {} public interface I2 : I1<(int a, int b)> {} public interface I3 : I1<(int c, int d)> {}"; Action<PEAssembly> validator = (assembly) => { var reader = assembly.GetMetadataReader(); Action<TypeDefinition, string[]> verifyTupleImpls = (def, tupleNames) => { var interfaceImpls = def.GetInterfaceImplementations(); Assert.Equal(1, interfaceImpls.Count); var interfaceImpl = reader.GetInterfaceImplementation(interfaceImpls.Single()); var attributes = interfaceImpl.GetCustomAttributes(); Assert.Equal(1, attributes.Count); var attr = reader.GetCustomAttribute(attributes.Single()); // Verify that the attribute contains an array of matching tuple names var argsReader = reader.GetBlobReader(attr.Value); // Prolog Assert.Equal(1, argsReader.ReadUInt16()); // Array size Assert.Equal(tupleNames.Length, argsReader.ReadInt32()); foreach (var name in tupleNames) { Assert.Equal(name, argsReader.ReadSerializedString()); } }; foreach (var typeHandle in reader.TypeDefinitions) { var def = reader.GetTypeDefinition(typeHandle); var name = reader.GetString(def.Name); switch (name) { case "I1`1": case "<Module>": continue; case "I2": verifyTupleImpls(def, new[] { "a", "b" }); break; case "I3": verifyTupleImpls(def, new[] { "c", "d" }); break; default: throw TestExceptionUtilities.UnexpectedValue(name); } } }; void symbolValidator(ModuleSymbol m) { foreach (var t in m.GlobalNamespace.GetTypeMembers()) { switch (t.Name) { case "I1": case "<Module>": continue; case "I2": VerifyTupleImpls(t, new[] { "a", "b" }); break; case "I3": VerifyTupleImpls(t, new[] { "c", "d" }); break; default: throw TestExceptionUtilities.UnexpectedValue(t.Name); } } void VerifyTupleImpls(NamedTypeSymbol t, string[] tupleNames) { var interfaceImpl = t.Interfaces().Single(); var typeArg = interfaceImpl.TypeArguments().Single(); Assert.True(typeArg.IsTupleType); Assert.Equal(tupleNames, typeArg.TupleElementNames); } } CompileAndVerifyWithMscorlib40(src, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, assemblyValidator: validator, symbolValidator: symbolValidator); } } }
// Licensed to the .NET Foundation under one or more 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.Reflection.Metadata; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests_Tuples : WellKnownAttributesTestBase { private static readonly string s_tuplesTestSource = @" using System; public class Base0 { } public class Base1<T> { } public class Base2<T, U> { } public class Outer<T> : Base1<(int key, int val)> { public class Inner<U, V> : Base2<(int key2, int val2), V> { public class InnerInner<W> : Base1<(int key3, int val3)> { } } } public class Derived<T> : Outer<(int e1, (int e2, int e3) e4)>.Inner< Outer<(int e5, int e6)>.Inner<(int e7, int e8)[], (int e9, int e10)>.InnerInner<int>[], ((int e11, int e12) e13, int e14)> .InnerInner<((int e15, int e16) e17, (int e18, Base1<(int e19, int e20)> e21) e22)> { public static (int e1, int e2) Field1; public static (int e1, int e2) Field2; public static Base1<(int e1, (int e2, int e3) e4)> Field3; public static ValueTuple<Base1<(int e1, (int, (dynamic, dynamic)) e2)>, int> Field4; public static Outer<(object e1, dynamic e2)> .Inner<(dynamic e3, object e4), ValueTuple<dynamic, dynamic>> Field5; // No names public static Base1<(int, ValueTuple<int, ValueTuple>)> Field6; public static ValueTuple Field7; // Long tuples public static (int e1, int e2, int e3, int e4, int e5, int e6, int e7, int e8, int e9) Field8; public static Base1<(int e1, int e2, int e3, int e4, int e5, int e6, int e7, int e8, int e9)> Field9; public static (int e1, int e2) Method1() => (0, 0); public static void Method2((int e1, int e2) x) { } public static (int e1, int e2) Method3((int e3, int e4) x) => (0, 0); public static (int e1, int e2) Method4(ref (int e3, int e4) x) => x; public static ((int, (object, (dynamic, object)), object, int), ValueTuple) Method5(ref (object,dynamic) x) => ((0, (null, (null, null)), null, 0), default(ValueTuple)); public static (int e1, int e2, int e3, int e4, int e5, int e6, int e7, int e8, int e9) Method6() => (0, 0, 0, 0, 0, 0, 0, 0, 0); public static (int e1, int e2) Prop1 => (0, 0); public static (int e1, int e2) Prop2 { get; set; } public (int e1, int e2) this[(int e3, int e4) param] { get { return param; } set {} } public delegate void Delegate1<V>(object sender, ValueTuple<V, ((dynamic e1, dynamic e2, object e3) e4, dynamic e5), (dynamic, object)> args); public static event Delegate1<(dynamic e1, ValueTuple<(dynamic e2, dynamic e3)> e4)> Event1 { add { } remove { } } }"; private static readonly MetadataReference[] s_attributeRefs = { ValueTupleRef, SystemRuntimeFacadeRef, SystemCoreRef, CSharpRef }; [Fact] public void TestCompile() { CompileAndVerifyWithMscorlib40(s_tuplesTestSource, options: TestOptions.ReleaseDll, references: s_attributeRefs); } [Fact] public void TestTupleAttributes() { var comp = CreateCompilationWithMscorlib40(s_tuplesTestSource, options: TestOptions.UnsafeReleaseDll, references: s_attributeRefs); CompileAndVerify(comp, verify: Verification.Passes, symbolValidator: module => { TupleAttributeValidator.ValidateTupleAttributes(module); }); } [Fact] public void TupleAttributeWithOnlyOneConstructor() { var comp = CreateCompilationWithMscorlib40( s_tuplesTestSource + TestResources.NetFX.ValueTuple.tuplelib_cs + @" namespace System.Runtime.CompilerServices { /// <summary> /// Indicates that the use of <see cref=""System.ValueTuple""/> on a member is meant to be treated as a tuple with element names. /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue | AttributeTargets.Class | AttributeTargets.Struct )] public sealed class TupleElementNamesAttribute : Attribute { public TupleElementNamesAttribute(string[] transformNames) { } } }", references: new[] { SystemCoreRef }, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics(); CompileAndVerify(comp, symbolValidator: module => { TupleAttributeValidator.ValidateTupleAttributes(module); }); } [Fact] public void TupleLambdaParametersMissingString() { var source0 = @"namespace System { public class Object { } public class ValueType { } public struct Void { } public struct IntPtr { } public struct Int32 { } public class MulticastDelegate { } }"; var source1 = @"delegate void D<T>(T t); class C { static void Main() { D<(int x, int y)> d = o => { }; d((0, 0)); } }"; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); comp = CreateEmptyCompilation(source1, references: s_attributeRefs.Concat(new[] { ref0 })); comp.VerifyDiagnostics( // (6,11): error CS0518: Predefined type 'System.String' is not defined or imported // D<(int x, int y)> d = o => { }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "(int x, int y)").WithArguments("System.String").WithLocation(6, 11), // (6,11): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. // D<(int x, int y)> d = o => { }; Diagnostic(ErrorCode.ERR_NoTypeDef, "(int x, int y)").WithArguments("System.ValueType", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089").WithLocation(6, 11), // (7,11): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. // d((0, 0)); Diagnostic(ErrorCode.ERR_NoTypeDef, "(0, 0)").WithArguments("System.ValueType", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089").WithLocation(7, 11) ); } [Fact] public void TupleInDeclarationFailureWithoutString() { var source0 = @"namespace System { public class Object { } public class ValueType { } public struct Void { } public struct IntPtr { } public struct Int32 { } }"; var source1 = @" class C { static (int x, int y) M() => (0, 0); }"; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); comp = CreateEmptyCompilation(source1, references: new[] { ref0, ValueTupleRef }); comp.VerifyDiagnostics( // (4,12): error CS0518: Predefined type 'System.String' is not defined or imported // static (int x, int y) M() => (0, 0); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "(int x, int y)").WithArguments("System.String").WithLocation(4, 12), // (4,12): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. // static (int x, int y) M() => (0, 0); Diagnostic(ErrorCode.ERR_NoTypeDef, "(int x, int y)").WithArguments("System.ValueType", "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").WithLocation(4, 12), // (4,34): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. // static (int x, int y) M() => (0, 0); Diagnostic(ErrorCode.ERR_NoTypeDef, "(0, 0)").WithArguments("System.ValueType", "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").WithLocation(4, 34) ); } [Fact] public void RoundTrip() { ModuleSymbol sourceModule = null; ModuleSymbol peModule = null; CompileAndVerifyWithMscorlib40(s_tuplesTestSource, options: TestOptions.UnsafeReleaseDll, references: s_attributeRefs, verify: Verification.Passes, sourceSymbolValidator: m => sourceModule = m, symbolValidator: m => peModule = m); var srcTypes = sourceModule.GlobalNamespace.GetTypeMembers(); var peTypes = peModule.GlobalNamespace.GetTypeMembers() .WhereAsArray(t => t.Name != "<Module>"); Assert.Equal(srcTypes.Length, peTypes.Length); for (int i = 0; i < srcTypes.Length; i++) { var srcType = srcTypes[i]; var peType = peTypes[i]; Assert.Equal(ToTestString(srcType.BaseType()), ToTestString(peType.BaseType())); var srcMembers = srcType.GetMembers() .Where(m => !m.Name.Contains("k__BackingField")) .Select(ToTestString) .ToList(); var peMembers = peType.GetMembers() .Select(ToTestString) .ToList(); srcMembers.Sort(); peMembers.Sort(); AssertEx.Equal(srcMembers, peMembers); } } private static string ToTestString(Symbol symbol) { var typeSymbols = ArrayBuilder<TypeSymbol>.GetInstance(); switch (symbol.Kind) { case SymbolKind.Method: var methodSymbol = (MethodSymbol)symbol; typeSymbols.Add(methodSymbol.ReturnType); foreach (var parameterType in methodSymbol.ParameterTypesWithAnnotations) { typeSymbols.Add(parameterType.Type); } break; case SymbolKind.NamedType: var namedType = (NamedTypeSymbol)symbol; typeSymbols.Add(namedType.BaseType() ?? namedType); break; case SymbolKind.Field: typeSymbols.Add(((FieldSymbol)symbol).Type); break; case SymbolKind.Property: typeSymbols.Add(((PropertySymbol)symbol).Type); break; case SymbolKind.Event: typeSymbols.Add(((EventSymbol)symbol).Type); break; } var symbolString = string.Join(" | ", typeSymbols .Select(s => s.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat))); typeSymbols.Free(); return $"{symbol.Name}: {symbolString}"; } private struct TupleAttributeValidator { private readonly NamedTypeSymbol _base0Class, _base1Class, _base2Class, _outerClass, _derivedClass; private TupleAttributeValidator(ModuleSymbol module) { var globalNs = module.GlobalNamespace; _base0Class = globalNs.GetTypeMember("Base0"); _base1Class = globalNs.GetTypeMember("Base1"); _base2Class = globalNs.GetTypeMember("Base2"); _outerClass = globalNs.GetTypeMember("Outer"); _derivedClass = globalNs.GetTypeMember("Derived"); } internal static void ValidateTupleAttributes(ModuleSymbol module) { var validator = new TupleAttributeValidator(module); validator.ValidateAttributesOnNamedTypes(); validator.ValidateAttributesOnFields(); validator.ValidateAttributesOnMethods(); validator.ValidateAttributesOnProperties(); validator.ValidateAttributesOnEvents(); validator.ValidateAttributesOnDelegates(); } private void ValidateAttributesOnDelegates() { // public delegate void Delegate1<T>(object sender, // ValueTuple<T, // ((dynamic e1, dynamic e2, object e3) e4, dynamic e5), // (dynamic, object)> args); var delegate1 = _derivedClass.GetMember<NamedTypeSymbol>("Delegate1"); Assert.NotNull(delegate1); Assert.True(delegate1.IsDelegateType()); var invokeMethod = delegate1.DelegateInvokeMethod; Assert.NotNull(invokeMethod); ValidateTupleNameAttribute(invokeMethod.GetAttributes(), expectedTupleNamesAttribute: false); Assert.Equal(2, invokeMethod.ParameterCount); var sender = invokeMethod.Parameters[0]; Assert.Equal("sender", sender.Name); Assert.Equal(SpecialType.System_Object, sender.Type.SpecialType); ValidateTupleNameAttribute(sender.GetAttributes(), expectedTupleNamesAttribute: false); var args = invokeMethod.Parameters[1]; Assert.Equal("args", args.Name); var expectedElementNames = new[] { null, null, null, "e4", "e5", "e1", "e2", "e3", null, null }; ValidateTupleNameAttribute(args.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); AttributeTests_Dynamic.DynamicAttributeValidator.ValidateDynamicAttribute( args.GetAttributes(), expectedDynamicAttribute: true, expectedTransformFlags: new[] { false, false, false, false, true, true, false, true, false, true, false }); } private void ValidateAttributesOnEvents() { // public static event Delegate1<(dynamic e1, // ValueTuple<(dynamic e2, dynamic e3)> e4)> Event1; var event1 = _derivedClass.GetMember<EventSymbol>("Event1"); Assert.NotNull(event1); ValidateTupleNameAttribute(event1.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: new[] { "e1", "e4", null, "e2", "e3" }); AttributeTests_Dynamic.DynamicAttributeValidator.ValidateDynamicAttribute( event1.GetAttributes(), expectedDynamicAttribute: true, expectedTransformFlags: new[] { false, false, false, true, false, false, true, true }); } private void ValidateAttributesOnNamedTypes() { // public class Base0 { } ValidateTupleNameAttribute(_base0Class.GetAttributes(), expectedTupleNamesAttribute: false); // public class Base1<T> { } ValidateTupleNameAttribute(_base1Class.GetAttributes(), expectedTupleNamesAttribute: false); // public class Base2<T, U> { } ValidateTupleNameAttribute(_base2Class.GetAttributes(), expectedTupleNamesAttribute: false); // public class Outer<T> : Base1<(int key, int val)> Assert.True(_outerClass.BaseType().ContainsTuple()); var expectedElementNames = new[] { "key", "val" }; ValidateTupleNameAttribute(_outerClass.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); // public class Derived<T> : Outer<(int e1, (int e2, int e3) e4)>.Inner< // Outer<(int e5, int e6)>.Inner<(int e7, int e8)[], (int e9, int e10)>.InnerInner<int>[], // ((int e11, int e12) e13, int e14)> // .InnerInner<((int e15, int e16) e17, (int e18, Base1<(int e19, int e20)> e21) e22)> expectedElementNames = new[] { "e1", "e4", "e2", "e3", "e5", "e6", "e7", "e8", "e9", "e10", "e13", "e14", "e11", "e12", "e17", "e22", "e15", "e16", "e18", "e21", "e19", "e20" }; ValidateTupleNameAttribute(_derivedClass.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); } private void ValidateAttributesOnFields() { // public static (int e1, int e2) Field1; var field1 = _derivedClass.GetMember<FieldSymbol>("Field1"); var expectedElementNames = new[] { "e1", "e2" }; ValidateTupleNameAttribute(field1.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); // public static (int e1, int e2) Field2; var field2 = _derivedClass.GetMember<FieldSymbol>("Field2"); expectedElementNames = new[] { "e1", "e2" }; ValidateTupleNameAttribute(field2.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); // public static Base1<(int e1, (int e2, int e3) e4)> Field3; var field3 = _derivedClass.GetMember<FieldSymbol>("Field3"); expectedElementNames = new[] { "e1", "e4", "e2", "e3" }; ValidateTupleNameAttribute(field3.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); // public static ValueTuple<Base1<(int e1, (int, (dynamic, dynamic)) e2)>, int> Field4; var field4 = _derivedClass.GetMember<FieldSymbol>("Field4"); expectedElementNames = new[] { null, null, "e1", "e2", null, null, null, null }; ValidateTupleNameAttribute(field4.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); AttributeTests_Dynamic.DynamicAttributeValidator.ValidateDynamicAttribute( field4.GetAttributes(), expectedDynamicAttribute: true, expectedTransformFlags: new[] { false, false, false, false, false, false, false, true, true, false }); // public static Outer<(object e1, dynamic e2)> // .Inner<(dynamic e3, object e4), // ValueTuple<dynamic, dynamic>> Field5; var field5 = _derivedClass.GetMember<FieldSymbol>("Field5"); expectedElementNames = new[] { "e1", "e2", "e3", "e4", null, null }; ValidateTupleNameAttribute(field5.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); AttributeTests_Dynamic.DynamicAttributeValidator.ValidateDynamicAttribute( field5.GetAttributes(), expectedDynamicAttribute: true, expectedTransformFlags: new[] { false, false, false, true, false, true, false, false, true, true }); // public static Base1<(int, ValueTuple<int, ValueTuple>)> Field6; var field6 = _derivedClass.GetMember<FieldSymbol>("Field6"); ValidateTupleNameAttribute(field6.GetAttributes(), expectedTupleNamesAttribute: false); var field6Type = Assert.IsType<ConstructedNamedTypeSymbol>(field6.Type); Assert.Equal("Base1", field6Type.Name); Assert.Equal(1, field6Type.TypeParameters.Length); var firstTuple = field6Type.TypeArguments().Single(); Assert.True(firstTuple.IsTupleType); Assert.True(firstTuple.TupleElementNames.IsDefault); Assert.Equal(2, firstTuple.TupleElementTypesWithAnnotations.Length); var secondTuple = firstTuple.TupleElementTypesWithAnnotations[1].Type; Assert.True(secondTuple.IsTupleType); Assert.True(secondTuple.TupleElementNames.IsDefault); Assert.Equal(2, secondTuple.TupleElementTypesWithAnnotations.Length); // public static ValueTuple Field7; var field7 = _derivedClass.GetMember<FieldSymbol>("Field7"); ValidateTupleNameAttribute(field7.GetAttributes(), expectedTupleNamesAttribute: false); Assert.True(field7.Type.IsTupleType); Assert.Empty(field7.Type.TupleElementTypesWithAnnotations); // public static (int e1, int e2, int e3, int e4, int e5, int e6, int e7, int e8, int e9) Field8; var field8 = _derivedClass.GetMember<FieldSymbol>("Field8"); expectedElementNames = new[] { "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", null, null }; ValidateTupleNameAttribute(field8.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); // public static Base<(int e1, int e2, int e3, int e4, int e5, int e6, int e7, int e8, int e9)> Field9; var field9 = _derivedClass.GetMember<FieldSymbol>("Field9"); expectedElementNames = new[] { "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", null, null }; ValidateTupleNameAttribute(field9.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); } private void ValidateAttributesOnMethods() { // public static (int e1, int e2) Method1() => (0, 0); var method1 = _derivedClass.GetMember<MethodSymbol>("Method1"); var expectedElementNames = new[] { "e1", "e2" }; ValidateTupleNameAttribute(method1.GetReturnTypeAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); // public static void Method2((int e1, int e2) x) { } var method2 = _derivedClass.GetMember<MethodSymbol>("Method2"); expectedElementNames = new[] { "e1", "e2" }; ValidateTupleNameAttribute(method2.Parameters.Single().GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); // public static (int e1, int e2) Method3((int e3, int e4) x) => (0, 0); var method3 = _derivedClass.GetMember<MethodSymbol>("Method3"); expectedElementNames = new[] { "e1", "e2" }; ValidateTupleNameAttribute(method3.GetReturnTypeAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); expectedElementNames = new[] { "e3", "e4" }; ValidateTupleNameAttribute(method3.Parameters.Single().GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); // public static (int e1, int e2) Method4(ref (int e3, int e4) x) => x; var method4 = _derivedClass.GetMember<MethodSymbol>("Method4"); expectedElementNames = new[] { "e1", "e2" }; ValidateTupleNameAttribute(method4.GetReturnTypeAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); expectedElementNames = new[] { "e3", "e4" }; ValidateTupleNameAttribute(method4.Parameters.Single().GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); // public static ((int, // (object, (dynamic, object)), // object, // int), // ValueTuple) Method5(ref (object,dynamic) x) => // ((0, (null, (null, null)), null, 0), default(ValueTuple)); var method5 = _derivedClass.GetMember<MethodSymbol>("Method5"); ValidateTupleNameAttribute(method5.GetReturnTypeAttributes(), expectedTupleNamesAttribute: false); ValidateTupleNameAttribute(method5.Parameters.Single().GetAttributes(), expectedTupleNamesAttribute: false); // public static (int e1, int e2, int e3, int e4, int e5, // int e6, int e7, int e8, int e9) Method6() => (0, 0, 0, 0, // 0, 0, 0, 0, 0); var method6 = _derivedClass.GetMember<MethodSymbol>("Method6"); expectedElementNames = new[] { "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", null, null }; ValidateTupleNameAttribute(method6.GetReturnTypeAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedElementNames); } private void ValidateAttributesOnProperties() { // public static (int e1, int e2) Prop1 => (0, 0); var prop1 = _derivedClass.GetMember("Prop1"); var expectedTupleNames = new[] { "e1", "e2" }; ValidateTupleNameAttribute(prop1.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedTupleNames); // public static (int e1, int e2) Prop2 { get; set; } var prop2 = _derivedClass.GetMember("Prop2"); expectedTupleNames = new[] { "e1", "e2" }; ValidateTupleNameAttribute(prop2.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedTupleNames); // public (int e1, int e2) this[(int e3, int e4) param] var indexer = (PropertySymbol)_derivedClass.GetMember("this[]"); expectedTupleNames = new[] { "e1", "e2" }; ValidateTupleNameAttribute(indexer.GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedTupleNames); expectedTupleNames = new[] { "e3", "e4" }; ValidateTupleNameAttribute(indexer.Parameters.Single().GetAttributes(), expectedTupleNamesAttribute: true, expectedElementNames: expectedTupleNames); } private void ValidateTupleNameAttribute( ImmutableArray<CSharpAttributeData> attributes, bool expectedTupleNamesAttribute, string[] expectedElementNames = null) { var synthesizedTupleElementNamesAttr = attributes.Where(attr => string.Equals(attr.AttributeClass.Name, "TupleElementNamesAttribute", StringComparison.Ordinal)); if (!expectedTupleNamesAttribute) { Assert.Empty(synthesizedTupleElementNamesAttr); Assert.Null(expectedElementNames); } else { var tupleAttr = synthesizedTupleElementNamesAttr.Single(); Assert.Equal("System.Runtime.CompilerServices.TupleElementNamesAttribute", tupleAttr.AttributeClass.ToTestDisplayString()); Assert.Equal("System.String[]", tupleAttr.AttributeConstructor.Parameters.Single().TypeWithAnnotations.ToTestDisplayString()); if (expectedElementNames == null) { Assert.True(tupleAttr.CommonConstructorArguments.IsEmpty); } else { var arg = tupleAttr.CommonConstructorArguments.Single(); Assert.Equal(TypedConstantKind.Array, arg.Kind); var actualElementNames = arg.Values.SelectAsArray(TypedConstantString); AssertEx.Equal(expectedElementNames, actualElementNames); } } } private static string TypedConstantString(TypedConstant constant) { Assert.True(constant.Type.SpecialType == SpecialType.System_String); return (string)constant.Value; } } [Fact] public void TupleAttributeMissing() { var comp = CreateCompilationWithMscorlib40( s_tuplesTestSource + TestResources.NetFX.ValueTuple.tuplelib_cs, references: new[] { SystemCoreRef }, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (8,31): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public class Outer<T> : Base1<(int key, int val)> Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int key, int val)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(8, 31), // (16,42): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public class Derived<T> : Outer<(int e1, (int e2, int e3) e4)>.Inner< Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e2, int e3)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(16, 42), // (16,33): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public class Derived<T> : Outer<(int e1, (int e2, int e3) e4)>.Inner< Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e1, (int e2, int e3) e4)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(16, 33), // (17,11): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // Outer<(int e5, int e6)>.Inner<(int e7, int e8)[], (int e9, int e10)>.InnerInner<int>[], Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e5, int e6)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(17, 11), // (17,35): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // Outer<(int e5, int e6)>.Inner<(int e7, int e8)[], (int e9, int e10)>.InnerInner<int>[], Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e7, int e8)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(17, 35), // (17,55): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // Outer<(int e5, int e6)>.Inner<(int e7, int e8)[], (int e9, int e10)>.InnerInner<int>[], Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e9, int e10)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(17, 55), // (18,6): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // ((int e11, int e12) e13, int e14)> Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e11, int e12)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(18, 6), // (18,5): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // ((int e11, int e12) e13, int e14)> Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "((int e11, int e12) e13, int e14)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(18, 5), // (19,18): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // .InnerInner<((int e15, int e16) e17, (int e18, Base1<(int e19, int e20)> e21) e22)> Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e15, int e16)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(19, 18), // (19,58): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // .InnerInner<((int e15, int e16) e17, (int e18, Base1<(int e19, int e20)> e21) e22)> Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e19, int e20)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(19, 58), // (19,42): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // .InnerInner<((int e15, int e16) e17, (int e18, Base1<(int e19, int e20)> e21) e22)> Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e18, Base1<(int e19, int e20)> e21)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(19, 42), // (19,17): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // .InnerInner<((int e15, int e16) e17, (int e18, Base1<(int e19, int e20)> e21) e22)> Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "((int e15, int e16) e17, (int e18, Base1<(int e19, int e20)> e21) e22)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(19, 17), // (10,38): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public class Inner<U, V> : Base2<(int key2, int val2), V> Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int key2, int val2)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(10, 38), // (12,44): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public class InnerInner<W> : Base1<(int key3, int val3)> { } Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int key3, int val3)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(12, 44), // (72,47): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // ValueTuple<(dynamic e2, dynamic e3)> e4)> Event1 Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(dynamic e2, dynamic e3)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(72, 47), // (71,35): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static event Delegate1<(dynamic e1, Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, @"(dynamic e1, ValueTuple<(dynamic e2, dynamic e3)> e4)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(71, 35), // (41,19): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static (int e1, int e2) Method1() => (0, 0); Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e1, int e2)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(41, 19), // (42,32): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static void Method2((int e1, int e2) x) { } Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e1, int e2)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(42, 32), // (43,44): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static (int e1, int e2) Method3((int e3, int e4) x) => (0, 0); Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e3, int e4)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(43, 44), // (43,19): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static (int e1, int e2) Method3((int e3, int e4) x) => (0, 0); Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e1, int e2)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(43, 19), // (44,48): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static (int e1, int e2) Method4(ref (int e3, int e4) x) => x; Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e3, int e4)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(44, 48), // (44,19): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static (int e1, int e2) Method4(ref (int e3, int e4) x) => x; Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e1, int e2)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(44, 19), // (53,19): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static (int e1, int e2, int e3, int e4, int e5, Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, @"(int e1, int e2, int e3, int e4, int e5, int e6, int e7, int e8, int e9)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(53, 19), // (57,19): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static (int e1, int e2) Prop1 => (0, 0); Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e1, int e2)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(57, 19), // (58,19): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static (int e1, int e2) Prop2 { get; set; } Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e1, int e2)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(58, 19), // (60,34): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public (int e1, int e2) this[(int e3, int e4) param] Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e3, int e4)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(60, 34), // (60,12): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public (int e1, int e2) this[(int e3, int e4) param] Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e1, int e2)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(60, 12), // (68,14): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // ((dynamic e1, dynamic e2, object e3) e4, dynamic e5), Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(dynamic e1, dynamic e2, object e3)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(68, 14), // (68,13): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // ((dynamic e1, dynamic e2, object e3) e4, dynamic e5), Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "((dynamic e1, dynamic e2, object e3) e4, dynamic e5)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(68, 13), // (22,19): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static (int e1, int e2) Field2; Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e1, int e2)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(22, 19), // (23,34): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static Base1<(int e1, (int e2, int e3) e4)> Field3; Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e2, int e3)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(23, 34), // (23,25): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static Base1<(int e1, (int e2, int e3) e4)> Field3; Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e1, (int e2, int e3) e4)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(23, 25), // (25,36): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static ValueTuple<Base1<(int e1, (int, (dynamic, dynamic)) e2)>, int> Field4; Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e1, (int, (dynamic, dynamic)) e2)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(25, 36), // (27,25): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static Outer<(object e1, dynamic e2)> Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(object e1, dynamic e2)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(27, 25), // (28,16): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // .Inner<(dynamic e3, object e4), Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(dynamic e3, object e4)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(28, 16), // (36,19): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static (int e1, int e2, int e3, int e4, int e5, Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, @"(int e1, int e2, int e3, int e4, int e5, int e6, int e7, int e8, int e9)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(36, 19), // (38,25): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static Base1<(int e1, int e2, int e3, int e4, int e5, Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, @"(int e1, int e2, int e3, int e4, int e5, int e6, int e7, int e8, int e9)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(38, 25), // (21,19): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // public static (int e1, int e2) Field1; Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int e1, int e2)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(21, 19)); } [Fact] public void ExplicitTupleNamesAttribute() { var text = @" using System; using System.Runtime.CompilerServices; [TupleElementNames(new[] { ""a"", ""b"" })] public class C { [TupleElementNames(new string[] { null, null })] public ValueTuple<int, int> Field1; [TupleElementNames(new[] { ""x"", ""y"" })] public ValueTuple<int, int> Prop1; [return: TupleElementNames(new string[] { null, null })] public ValueTuple<int, int> M([TupleElementNames(new string[] { null})] ValueTuple x) => (0, 0); public delegate void Delegate1<T>(object sender, [TupleElementNames(new[] { ""x"" })]ValueTuple<T> args); [TupleElementNames(new[] { ""y"" })] public event Delegate1<ValueTuple<int>> Event1 { add { } remove { } } [TupleElementNames(new[] { ""a"", ""b"" })] public (int x, int y) this[[TupleElementNames](int a, int b) t] => t; } [TupleElementNames(new[] { ""a"", ""b"" })] public struct S { }"; var comp = CreateCompilationWithMscorlib40(text, references: s_attributeRefs); comp.VerifyDiagnostics( // (31,2): error CS8331: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. // [TupleElementNames(new[] { "a", "b" })] Diagnostic(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, @"TupleElementNames(new[] { ""a"", ""b"" })").WithLocation(31, 2), // (5,2): error CS8331: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. // [TupleElementNames(new[] { "a", "b" })] Diagnostic(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, @"TupleElementNames(new[] { ""a"", ""b"" })").WithLocation(5, 2), // (18,10): error CS8331: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. // [TupleElementNames(new[] { "x" })]ValueTuple<T> args); Diagnostic(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, @"TupleElementNames(new[] { ""x"" })").WithLocation(18, 10), // (11,6): error CS8331: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. // [TupleElementNames(new[] { "x", "y" })] Diagnostic(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, @"TupleElementNames(new[] { ""x"", ""y"" })").WithLocation(11, 6), // (14,14): error CS8331: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. // [return: TupleElementNames(new string[] { null, null })] Diagnostic(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, "TupleElementNames(new string[] { null, null })").WithLocation(14, 14), // (15,36): error CS8331: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. // public ValueTuple<int, int> M([TupleElementNames(new string[] { null})] ValueTuple x) => (0, 0); Diagnostic(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, "TupleElementNames(new string[] { null})").WithLocation(15, 36), // (20,6): error CS0592: Attribute 'TupleElementNames' is not valid on this declaration type. It is only valid on 'class, struct, property, indexer, field, parameter, return' declarations. // [TupleElementNames(new[] { "y" })] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "TupleElementNames").WithArguments("TupleElementNames", "class, struct, property, indexer, field, parameter, return").WithLocation(20, 6), // (27,6): error CS8331: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. // [TupleElementNames(new[] { "a", "b" })] Diagnostic(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, @"TupleElementNames(new[] { ""a"", ""b"" })").WithLocation(27, 6), // (28,33): error CS8331: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. // public (int x, int y) this[[TupleElementNames](int a, int b) t] => t; Diagnostic(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, "TupleElementNames").WithLocation(28, 33), // (8,6): error CS8331: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. // [TupleElementNames(new string[] { null, null })] Diagnostic(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, "TupleElementNames(new string[] { null, null })").WithLocation(8, 6)); } [Fact] [WorkItem(14844, "https://github.com/dotnet/roslyn/issues/14844")] public void AttributesOnTypeConstraints() { var src = @" public interface I1<T> {} public interface I2<T> where T : I1<(int a, int b)> {} public interface I3<T> where T : I1<(int c, int d)> {}"; Action<PEAssembly> validator = assembly => { var reader = assembly.GetMetadataReader(); Action<TypeDefinition, string[]> verifyTupleConstraint = (def, tupleNames) => { var typeParams = def.GetGenericParameters(); Assert.Equal(1, typeParams.Count); var typeParam = reader.GetGenericParameter(typeParams[0]); var constraintHandles = typeParam.GetConstraints(); Assert.Equal(1, constraintHandles.Count); var constraint = reader.GetGenericParameterConstraint(constraintHandles[0]); var attributes = constraint.GetCustomAttributes(); Assert.Equal(1, attributes.Count); var attr = reader.GetCustomAttribute(attributes.Single()); // Verify that the attribute contains an array of matching tuple names var argsReader = reader.GetBlobReader(attr.Value); // Prolog Assert.Equal(1, argsReader.ReadUInt16()); // Array size Assert.Equal(tupleNames.Length, argsReader.ReadInt32()); foreach (var name in tupleNames) { Assert.Equal(name, argsReader.ReadSerializedString()); } }; foreach (var typeHandle in reader.TypeDefinitions) { var def = reader.GetTypeDefinition(typeHandle); var name = reader.GetString(def.Name); switch (name) { case "I1`1": case "<Module>": continue; case "I2`1": verifyTupleConstraint(def, new[] { "a", "b" }); break; case "I3`1": verifyTupleConstraint(def, new[] { "c", "d" }); break; default: throw TestExceptionUtilities.UnexpectedValue(name); } } }; void symbolValidator(ModuleSymbol m) { foreach (var t in m.GlobalNamespace.GetTypeMembers()) { switch (t.Name) { case "I1": case "<Module>": continue; case "I2": verifyTupleImpls(t, new[] { "a", "b" }); break; case "I3": verifyTupleImpls(t, new[] { "c", "d" }); break; } } void verifyTupleImpls(NamedTypeSymbol t, string[] tupleNames) { var typeParam = t.TypeParameters.Single(); var constraint = (NamedTypeSymbol)typeParam.ConstraintTypes().Single(); var typeArg = constraint.TypeArguments().Single(); Assert.True(typeArg.IsTupleType); Assert.Equal(tupleNames, typeArg.TupleElementNames); } } CompileAndVerifyWithMscorlib40(src, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, assemblyValidator: validator, symbolValidator: symbolValidator); } [Fact] [WorkItem(14844, "https://github.com/dotnet/roslyn/issues/14844")] public void AttributesOnInterfaceImplementations() { var src = @" public interface I1<T> {} public interface I2 : I1<(int a, int b)> {} public interface I3 : I1<(int c, int d)> {}"; Action<PEAssembly> validator = (assembly) => { var reader = assembly.GetMetadataReader(); Action<TypeDefinition, string[]> verifyTupleImpls = (def, tupleNames) => { var interfaceImpls = def.GetInterfaceImplementations(); Assert.Equal(1, interfaceImpls.Count); var interfaceImpl = reader.GetInterfaceImplementation(interfaceImpls.Single()); var attributes = interfaceImpl.GetCustomAttributes(); Assert.Equal(1, attributes.Count); var attr = reader.GetCustomAttribute(attributes.Single()); // Verify that the attribute contains an array of matching tuple names var argsReader = reader.GetBlobReader(attr.Value); // Prolog Assert.Equal(1, argsReader.ReadUInt16()); // Array size Assert.Equal(tupleNames.Length, argsReader.ReadInt32()); foreach (var name in tupleNames) { Assert.Equal(name, argsReader.ReadSerializedString()); } }; foreach (var typeHandle in reader.TypeDefinitions) { var def = reader.GetTypeDefinition(typeHandle); var name = reader.GetString(def.Name); switch (name) { case "I1`1": case "<Module>": continue; case "I2": verifyTupleImpls(def, new[] { "a", "b" }); break; case "I3": verifyTupleImpls(def, new[] { "c", "d" }); break; default: throw TestExceptionUtilities.UnexpectedValue(name); } } }; void symbolValidator(ModuleSymbol m) { foreach (var t in m.GlobalNamespace.GetTypeMembers()) { switch (t.Name) { case "I1": case "<Module>": continue; case "I2": VerifyTupleImpls(t, new[] { "a", "b" }); break; case "I3": VerifyTupleImpls(t, new[] { "c", "d" }); break; default: throw TestExceptionUtilities.UnexpectedValue(t.Name); } } void VerifyTupleImpls(NamedTypeSymbol t, string[] tupleNames) { var interfaceImpl = t.Interfaces().Single(); var typeArg = interfaceImpl.TypeArguments().Single(); Assert.True(typeArg.IsTupleType); Assert.Equal(tupleNames, typeArg.TupleElementNames); } } CompileAndVerifyWithMscorlib40(src, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, assemblyValidator: validator, symbolValidator: symbolValidator); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Compilers/Core/Portable/CryptographicHashProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Security.Cryptography; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal abstract class CryptographicHashProvider { private ImmutableArray<byte> _lazySHA1Hash; private ImmutableArray<byte> _lazySHA256Hash; private ImmutableArray<byte> _lazySHA384Hash; private ImmutableArray<byte> _lazySHA512Hash; private ImmutableArray<byte> _lazyMD5Hash; internal abstract ImmutableArray<byte> ComputeHash(HashAlgorithm algorithm); internal ImmutableArray<byte> GetHash(AssemblyHashAlgorithm algorithmId) { using (HashAlgorithm? algorithm = TryGetAlgorithm(algorithmId)) { // ERR_CryptoHashFailed has already been reported: if (algorithm == null) { return ImmutableArray.Create<byte>(); } switch (algorithmId) { case AssemblyHashAlgorithm.None: case AssemblyHashAlgorithm.Sha1: return GetHash(ref _lazySHA1Hash, algorithm); case AssemblyHashAlgorithm.Sha256: return GetHash(ref _lazySHA256Hash, algorithm); case AssemblyHashAlgorithm.Sha384: return GetHash(ref _lazySHA384Hash, algorithm); case AssemblyHashAlgorithm.Sha512: return GetHash(ref _lazySHA512Hash, algorithm); case AssemblyHashAlgorithm.MD5: return GetHash(ref _lazyMD5Hash, algorithm); default: throw ExceptionUtilities.UnexpectedValue(algorithmId); } } } internal static int GetHashSize(SourceHashAlgorithm algorithmId) { switch (algorithmId) { case SourceHashAlgorithm.Sha1: return 160 / 8; case SourceHashAlgorithm.Sha256: return 256 / 8; default: throw ExceptionUtilities.UnexpectedValue(algorithmId); } } internal static HashAlgorithm? TryGetAlgorithm(SourceHashAlgorithm algorithmId) { switch (algorithmId) { case SourceHashAlgorithm.Sha1: return SHA1.Create(); case SourceHashAlgorithm.Sha256: return SHA256.Create(); default: return null; } } internal static HashAlgorithmName GetAlgorithmName(SourceHashAlgorithm algorithmId) { switch (algorithmId) { case SourceHashAlgorithm.Sha1: return HashAlgorithmName.SHA1; case SourceHashAlgorithm.Sha256: return HashAlgorithmName.SHA256; default: throw ExceptionUtilities.UnexpectedValue(algorithmId); } } internal static HashAlgorithm? TryGetAlgorithm(AssemblyHashAlgorithm algorithmId) { switch (algorithmId) { case AssemblyHashAlgorithm.None: case AssemblyHashAlgorithm.Sha1: return SHA1.Create(); case AssemblyHashAlgorithm.Sha256: return SHA256.Create(); case AssemblyHashAlgorithm.Sha384: return SHA384.Create(); case AssemblyHashAlgorithm.Sha512: return SHA512.Create(); case AssemblyHashAlgorithm.MD5: return MD5.Create(); default: return null; } } internal static bool IsSupportedAlgorithm(AssemblyHashAlgorithm algorithmId) { switch (algorithmId) { case AssemblyHashAlgorithm.None: case AssemblyHashAlgorithm.Sha1: case AssemblyHashAlgorithm.Sha256: case AssemblyHashAlgorithm.Sha384: case AssemblyHashAlgorithm.Sha512: case AssemblyHashAlgorithm.MD5: return true; default: return false; } } private ImmutableArray<byte> GetHash(ref ImmutableArray<byte> lazyHash, HashAlgorithm algorithm) { if (lazyHash.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref lazyHash, ComputeHash(algorithm), default(ImmutableArray<byte>)); } return lazyHash; } internal const int Sha1HashSize = 20; internal static ImmutableArray<byte> ComputeSha1(Stream stream) { if (stream != null) { stream.Seek(0, SeekOrigin.Begin); using (var hashProvider = SHA1.Create()) { return ImmutableArray.Create(hashProvider.ComputeHash(stream)); } } return ImmutableArray<byte>.Empty; } internal static ImmutableArray<byte> ComputeSha1(ImmutableArray<byte> bytes) { return ComputeSha1(bytes.ToArray()); } internal static ImmutableArray<byte> ComputeSha1(byte[] bytes) { using (var hashProvider = SHA1.Create()) { return ImmutableArray.Create(hashProvider.ComputeHash(bytes)); } } internal static ImmutableArray<byte> ComputeHash(HashAlgorithmName algorithmName, IEnumerable<Blob> bytes) { using (var incrementalHash = IncrementalHash.CreateHash(algorithmName)) { incrementalHash.AppendData(bytes); return ImmutableArray.Create(incrementalHash.GetHashAndReset()); } } internal static ImmutableArray<byte> ComputeHash(HashAlgorithmName algorithmName, IEnumerable<ArraySegment<byte>> bytes) { using (var incrementalHash = IncrementalHash.CreateHash(algorithmName)) { incrementalHash.AppendData(bytes); return ImmutableArray.Create(incrementalHash.GetHashAndReset()); } } internal static ImmutableArray<byte> ComputeSourceHash(ImmutableArray<byte> bytes, SourceHashAlgorithm hashAlgorithm = SourceHashAlgorithmUtils.DefaultContentHashAlgorithm) { var algorithmName = GetAlgorithmName(hashAlgorithm); using (var incrementalHash = IncrementalHash.CreateHash(algorithmName)) { incrementalHash.AppendData(bytes.ToArray()); return ImmutableArray.Create(incrementalHash.GetHashAndReset()); } } internal static ImmutableArray<byte> ComputeSourceHash(IEnumerable<Blob> bytes, SourceHashAlgorithm hashAlgorithm = SourceHashAlgorithmUtils.DefaultContentHashAlgorithm) { return ComputeHash(GetAlgorithmName(hashAlgorithm), bytes); } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Security.Cryptography; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal abstract class CryptographicHashProvider { private ImmutableArray<byte> _lazySHA1Hash; private ImmutableArray<byte> _lazySHA256Hash; private ImmutableArray<byte> _lazySHA384Hash; private ImmutableArray<byte> _lazySHA512Hash; private ImmutableArray<byte> _lazyMD5Hash; internal abstract ImmutableArray<byte> ComputeHash(HashAlgorithm algorithm); internal ImmutableArray<byte> GetHash(AssemblyHashAlgorithm algorithmId) { using (HashAlgorithm? algorithm = TryGetAlgorithm(algorithmId)) { // ERR_CryptoHashFailed has already been reported: if (algorithm == null) { return ImmutableArray.Create<byte>(); } switch (algorithmId) { case AssemblyHashAlgorithm.None: case AssemblyHashAlgorithm.Sha1: return GetHash(ref _lazySHA1Hash, algorithm); case AssemblyHashAlgorithm.Sha256: return GetHash(ref _lazySHA256Hash, algorithm); case AssemblyHashAlgorithm.Sha384: return GetHash(ref _lazySHA384Hash, algorithm); case AssemblyHashAlgorithm.Sha512: return GetHash(ref _lazySHA512Hash, algorithm); case AssemblyHashAlgorithm.MD5: return GetHash(ref _lazyMD5Hash, algorithm); default: throw ExceptionUtilities.UnexpectedValue(algorithmId); } } } internal static int GetHashSize(SourceHashAlgorithm algorithmId) { switch (algorithmId) { case SourceHashAlgorithm.Sha1: return 160 / 8; case SourceHashAlgorithm.Sha256: return 256 / 8; default: throw ExceptionUtilities.UnexpectedValue(algorithmId); } } internal static HashAlgorithm? TryGetAlgorithm(SourceHashAlgorithm algorithmId) { switch (algorithmId) { case SourceHashAlgorithm.Sha1: return SHA1.Create(); case SourceHashAlgorithm.Sha256: return SHA256.Create(); default: return null; } } internal static HashAlgorithmName GetAlgorithmName(SourceHashAlgorithm algorithmId) { switch (algorithmId) { case SourceHashAlgorithm.Sha1: return HashAlgorithmName.SHA1; case SourceHashAlgorithm.Sha256: return HashAlgorithmName.SHA256; default: throw ExceptionUtilities.UnexpectedValue(algorithmId); } } internal static HashAlgorithm? TryGetAlgorithm(AssemblyHashAlgorithm algorithmId) { switch (algorithmId) { case AssemblyHashAlgorithm.None: case AssemblyHashAlgorithm.Sha1: return SHA1.Create(); case AssemblyHashAlgorithm.Sha256: return SHA256.Create(); case AssemblyHashAlgorithm.Sha384: return SHA384.Create(); case AssemblyHashAlgorithm.Sha512: return SHA512.Create(); case AssemblyHashAlgorithm.MD5: return MD5.Create(); default: return null; } } internal static bool IsSupportedAlgorithm(AssemblyHashAlgorithm algorithmId) { switch (algorithmId) { case AssemblyHashAlgorithm.None: case AssemblyHashAlgorithm.Sha1: case AssemblyHashAlgorithm.Sha256: case AssemblyHashAlgorithm.Sha384: case AssemblyHashAlgorithm.Sha512: case AssemblyHashAlgorithm.MD5: return true; default: return false; } } private ImmutableArray<byte> GetHash(ref ImmutableArray<byte> lazyHash, HashAlgorithm algorithm) { if (lazyHash.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref lazyHash, ComputeHash(algorithm), default(ImmutableArray<byte>)); } return lazyHash; } internal const int Sha1HashSize = 20; internal static ImmutableArray<byte> ComputeSha1(Stream stream) { if (stream != null) { stream.Seek(0, SeekOrigin.Begin); using (var hashProvider = SHA1.Create()) { return ImmutableArray.Create(hashProvider.ComputeHash(stream)); } } return ImmutableArray<byte>.Empty; } internal static ImmutableArray<byte> ComputeSha1(ImmutableArray<byte> bytes) { return ComputeSha1(bytes.ToArray()); } internal static ImmutableArray<byte> ComputeSha1(byte[] bytes) { using (var hashProvider = SHA1.Create()) { return ImmutableArray.Create(hashProvider.ComputeHash(bytes)); } } internal static ImmutableArray<byte> ComputeHash(HashAlgorithmName algorithmName, IEnumerable<Blob> bytes) { using (var incrementalHash = IncrementalHash.CreateHash(algorithmName)) { incrementalHash.AppendData(bytes); return ImmutableArray.Create(incrementalHash.GetHashAndReset()); } } internal static ImmutableArray<byte> ComputeHash(HashAlgorithmName algorithmName, IEnumerable<ArraySegment<byte>> bytes) { using (var incrementalHash = IncrementalHash.CreateHash(algorithmName)) { incrementalHash.AppendData(bytes); return ImmutableArray.Create(incrementalHash.GetHashAndReset()); } } internal static ImmutableArray<byte> ComputeSourceHash(ImmutableArray<byte> bytes, SourceHashAlgorithm hashAlgorithm = SourceHashAlgorithmUtils.DefaultContentHashAlgorithm) { var algorithmName = GetAlgorithmName(hashAlgorithm); using (var incrementalHash = IncrementalHash.CreateHash(algorithmName)) { incrementalHash.AppendData(bytes.ToArray()); return ImmutableArray.Create(incrementalHash.GetHashAndReset()); } } internal static ImmutableArray<byte> ComputeSourceHash(IEnumerable<Blob> bytes, SourceHashAlgorithm hashAlgorithm = SourceHashAlgorithmUtils.DefaultContentHashAlgorithm) { return ComputeHash(GetAlgorithmName(hashAlgorithm), bytes); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/MetadataDecoder.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Concurrent Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Reflection.Metadata Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE ''' <summary> ''' Helper class to resolve metadata tokens and signatures. ''' </summary> Friend Class MetadataDecoder Inherits MetadataDecoder(Of PEModuleSymbol, TypeSymbol, MethodSymbol, FieldSymbol, Symbol) ''' <summary> ''' Type context for resolving generic type arguments. ''' </summary> Private ReadOnly _typeContextOpt As PENamedTypeSymbol ''' <summary> ''' Method context for resolving generic method type arguments. ''' </summary> Private ReadOnly _methodContextOpt As PEMethodSymbol Public Sub New( moduleSymbol As PEModuleSymbol, context As PENamedTypeSymbol ) Me.New(moduleSymbol, context, Nothing) End Sub Public Sub New( moduleSymbol As PEModuleSymbol, context As PEMethodSymbol ) Me.New(moduleSymbol, DirectCast(context.ContainingType, PENamedTypeSymbol), context) End Sub Public Sub New( moduleSymbol As PEModuleSymbol ) Me.New(moduleSymbol, Nothing, Nothing) End Sub Private Sub New( moduleSymbol As PEModuleSymbol, typeContextOpt As PENamedTypeSymbol, methodContextOpt As PEMethodSymbol ) ' TODO (tomat): if the containing assembly is a source assembly and we are about to decode assembly level attributes, we run into a cycle, ' so for now ignore the assembly identity. MyBase.New(moduleSymbol.Module, If(TypeOf moduleSymbol.ContainingAssembly Is PEAssemblySymbol, moduleSymbol.ContainingAssembly.Identity, Nothing), SymbolFactory.Instance, moduleSymbol) Debug.Assert(moduleSymbol IsNot Nothing) _typeContextOpt = typeContextOpt _methodContextOpt = methodContextOpt End Sub Friend Shadows ReadOnly Property ModuleSymbol As PEModuleSymbol Get Return MyBase.moduleSymbol End Get End Property Protected Overrides Function GetGenericMethodTypeParamSymbol(position As Integer) As TypeSymbol If _methodContextOpt Is Nothing Then Return New UnsupportedMetadataTypeSymbol() End If Dim typeParameters = _methodContextOpt.TypeParameters If typeParameters.Length <= position Then Return New UnsupportedMetadataTypeSymbol() End If Return typeParameters(position) End Function Protected Overrides Function GetGenericTypeParamSymbol(position As Integer) As TypeSymbol Dim type As PENamedTypeSymbol = _typeContextOpt While type IsNot Nothing AndAlso (type.MetadataArity - type.Arity) > position type = TryCast(type.ContainingSymbol, PENamedTypeSymbol) End While If type Is Nothing OrElse type.MetadataArity <= position Then Return New UnsupportedMetadataTypeSymbol() End If position -= (type.MetadataArity - type.Arity) Debug.Assert(position >= 0 AndAlso position < type.Arity) Return type.TypeParameters(position) End Function Protected Overrides Function GetTypeHandleToTypeMap() As ConcurrentDictionary(Of TypeDefinitionHandle, TypeSymbol) Return moduleSymbol.TypeHandleToTypeMap End Function Protected Overrides Function GetTypeRefHandleToTypeMap() As ConcurrentDictionary(Of TypeReferenceHandle, TypeSymbol) Return moduleSymbol.TypeRefHandleToTypeMap End Function Protected Overrides Function LookupNestedTypeDefSymbol( container As TypeSymbol, ByRef emittedName As MetadataTypeName ) As TypeSymbol Dim result = container.LookupMetadataType(emittedName) Debug.Assert(result IsNot Nothing) Return result End Function ''' <summary> ''' Lookup a type defined in referenced assembly. ''' </summary> Protected Overloads Overrides Function LookupTopLevelTypeDefSymbol( referencedAssemblyIndex As Integer, ByRef emittedName As MetadataTypeName ) As TypeSymbol Dim assembly As AssemblySymbol = ModuleSymbol.GetReferencedAssemblySymbol(referencedAssemblyIndex) If assembly Is Nothing Then Return New UnsupportedMetadataTypeSymbol() End If Try Return assembly.LookupTopLevelMetadataType(emittedName, digThroughForwardedTypes:=True) Catch e As Exception When FatalError.ReportAndPropagate(e) ' Trying to get more useful Watson dumps. Throw ExceptionUtilities.Unreachable End Try End Function ''' <summary> ''' Lookup a type defined in a module of a multi-module assembly. ''' </summary> Protected Overrides Function LookupTopLevelTypeDefSymbol(moduleName As String, ByRef emittedName As MetadataTypeName, <Out> ByRef isNoPiaLocalType As Boolean) As TypeSymbol For Each m As ModuleSymbol In moduleSymbol.ContainingAssembly.Modules If String.Equals(m.Name, moduleName, StringComparison.OrdinalIgnoreCase) Then If m Is moduleSymbol Then Return moduleSymbol.LookupTopLevelMetadataType(emittedName, isNoPiaLocalType) Else isNoPiaLocalType = False Return m.LookupTopLevelMetadataType(emittedName) End If End If Next isNoPiaLocalType = False Return New MissingMetadataTypeSymbol.TopLevel(New MissingModuleSymbolWithName(moduleSymbol.ContainingAssembly, moduleName), emittedName, SpecialType.None) End Function ''' <summary> ''' Lookup a type defined in this module. ''' This method will be called only if the type we are ''' looking for hasn't been loaded yet. Otherwise, MetadataDecoder ''' would have found the type in TypeDefRowIdToTypeMap based on its ''' TypeDef row id. ''' </summary> Protected Overloads Overrides Function LookupTopLevelTypeDefSymbol(ByRef emittedName As MetadataTypeName, <Out> ByRef isNoPiaLocalType As Boolean) As TypeSymbol Return moduleSymbol.LookupTopLevelMetadataType(emittedName, isNoPiaLocalType) End Function Protected Overrides Function GetIndexOfReferencedAssembly(identity As AssemblyIdentity) As Integer ' Go through all assemblies referenced by the current module And ' find the one which *exactly* matches the given identity. ' No unification will be performed Dim assemblies = ModuleSymbol.GetReferencedAssemblies() For i = 0 To assemblies.Length - 1 If identity.Equals(assemblies(i)) Then Return i End If Next Return -1 End Function ''' <summary> ''' Perform a check whether the type or at least one of its generic arguments ''' is defined in the specified assemblies. The check is performed recursively. ''' </summary> Public Shared Function IsOrClosedOverATypeFromAssemblies(this As TypeSymbol, assemblies As ImmutableArray(Of AssemblySymbol)) As Boolean Select Case this.Kind Case SymbolKind.TypeParameter Return False Case SymbolKind.ArrayType Return IsOrClosedOverATypeFromAssemblies(DirectCast(this, ArrayTypeSymbol).ElementType, assemblies) Case SymbolKind.NamedType, SymbolKind.ErrorType Dim symbol = DirectCast(this, NamedTypeSymbol) Dim containingAssembly As AssemblySymbol = symbol.OriginalDefinition.ContainingAssembly If containingAssembly IsNot Nothing Then For i = 0 To assemblies.Length - 1 Step 1 If containingAssembly Is assemblies(i) Then Return True End If Next End If Do If symbol.IsTupleType Then Return IsOrClosedOverATypeFromAssemblies(symbol.TupleUnderlyingType, assemblies) End If For Each typeArgument In symbol.TypeArgumentsNoUseSiteDiagnostics If IsOrClosedOverATypeFromAssemblies(typeArgument, assemblies) Then Return True End If Next symbol = symbol.ContainingType Loop While symbol IsNot Nothing Return False Case Else Throw ExceptionUtilities.UnexpectedValue(this.Kind) End Select End Function Protected Overrides Function SubstituteNoPiaLocalType( typeDef As TypeDefinitionHandle, ByRef name As MetadataTypeName, interfaceGuid As String, scope As String, identifier As String ) As TypeSymbol Dim result As TypeSymbol Try Dim isInterface As Boolean = Me.Module.IsInterfaceOrThrow(typeDef) Dim baseType As TypeSymbol = Nothing If Not isInterface Then Dim baseToken As EntityHandle = Me.Module.GetBaseTypeOfTypeOrThrow(typeDef) If Not baseToken.IsNil() Then baseType = GetTypeOfToken(baseToken) End If End If result = SubstituteNoPiaLocalType( name, isInterface, baseType, interfaceGuid, scope, identifier, moduleSymbol.ContainingAssembly) Catch mrEx As BadImageFormatException result = GetUnsupportedMetadataTypeSymbol(mrEx) End Try Debug.Assert(result IsNot Nothing) Dim cache As ConcurrentDictionary(Of TypeDefinitionHandle, TypeSymbol) = GetTypeHandleToTypeMap() Debug.Assert(cache IsNot Nothing) Dim newresult As TypeSymbol = cache.GetOrAdd(typeDef, result) Debug.Assert(newresult Is result OrElse (newresult.Kind = SymbolKind.ErrorType)) Return newresult End Function ''' <summary> ''' Find canonical type for NoPia embedded type. ''' </summary> ''' <returns> ''' Symbol for the canonical type or an ErrorTypeSymbol. Never returns null. ''' </returns> Friend Overloads Shared Function SubstituteNoPiaLocalType( ByRef fullEmittedName As MetadataTypeName, isInterface As Boolean, baseType As TypeSymbol, interfaceGuid As String, scope As String, identifier As String, referringAssembly As AssemblySymbol ) As NamedTypeSymbol Dim result As NamedTypeSymbol = Nothing Dim interfaceGuidValue As Guid = New Guid() Dim haveInterfaceGuidValue As Boolean = False Dim scopeGuidValue As Guid = New Guid() Dim haveScopeGuidValue As Boolean = False If isInterface AndAlso interfaceGuid IsNot Nothing Then haveInterfaceGuidValue = Guid.TryParse(interfaceGuid, interfaceGuidValue) If haveInterfaceGuidValue Then ' To have consistent errors. scope = Nothing identifier = Nothing End If End If If scope IsNot Nothing Then haveScopeGuidValue = Guid.TryParse(scope, scopeGuidValue) End If For Each assembly As AssemblySymbol In referringAssembly.GetNoPiaResolutionAssemblies() Debug.Assert(assembly IsNot Nothing) If assembly Is referringAssembly Then Continue For End If Dim candidate As NamedTypeSymbol = assembly.LookupTopLevelMetadataType(fullEmittedName, digThroughForwardedTypes:=False) Debug.Assert(Not candidate.IsGenericType) ' Ignore type forwarders, error symbols and non-public types If candidate.Kind = SymbolKind.ErrorType OrElse candidate.ContainingAssembly IsNot assembly OrElse candidate.DeclaredAccessibility <> Accessibility.Public Then Continue For End If ' Ignore NoPia local types. ' If candidate is coming from metadata, we don't need to do any special check, ' because we do not create symbols for local types. However, local types defined in source ' is another story. However, if compilation explicitly defines a local type, it should be ' represented by a retargeting assembly, which is supposed to hide the local type. Debug.Assert((Not TypeOf assembly Is SourceAssemblySymbol) OrElse Not DirectCast(assembly, SourceAssemblySymbol).SourceModule.MightContainNoPiaLocalTypes()) Dim candidateGuid As String = Nothing Dim haveCandidateGuidValue As Boolean = False Dim candidateGuidValue As Guid = New Guid() ' The type must be of the same kind (interface, struct, delegate or enum). Select Case candidate.TypeKind Case TypeKind.Interface If Not isInterface Then Continue For End If ' Get candidate's Guid If candidate.GetGuidString(candidateGuid) AndAlso candidateGuid IsNot Nothing Then haveCandidateGuidValue = Guid.TryParse(candidateGuid, candidateGuidValue) End If Case TypeKind.Delegate, TypeKind.Enum, TypeKind.Structure If isInterface Then Continue For End If ' Let's use a trick. To make sure the kind is the same, make sure ' base type is the same. Dim baseSpecialType As SpecialType = If(candidate.BaseTypeNoUseSiteDiagnostics?.SpecialType, SpecialType.None) If baseSpecialType = SpecialType.None OrElse baseSpecialType <> If(baseType?.SpecialType, SpecialType.None) Then Continue For End If Case Else Continue For End Select If haveInterfaceGuidValue OrElse haveCandidateGuidValue Then If Not haveInterfaceGuidValue OrElse Not haveCandidateGuidValue OrElse candidateGuidValue <> interfaceGuidValue Then Continue For End If Else If Not haveScopeGuidValue OrElse identifier Is Nothing OrElse Not String.Equals(identifier, fullEmittedName.FullName, StringComparison.Ordinal) Then Continue For End If ' Scope guid must match candidate's assembly guid. haveCandidateGuidValue = False If assembly.GetGuidString(candidateGuid) AndAlso candidateGuid IsNot Nothing Then haveCandidateGuidValue = Guid.TryParse(candidateGuid, candidateGuidValue) End If If Not haveCandidateGuidValue OrElse scopeGuidValue <> candidateGuidValue Then Continue For End If End If ' OK. It looks like we found canonical type definition. If result IsNot Nothing Then ' Ambiguity result = New NoPiaAmbiguousCanonicalTypeSymbol(referringAssembly, result, candidate) Exit For End If result = candidate Next If result Is Nothing Then result = New NoPiaMissingCanonicalTypeSymbol( referringAssembly, fullEmittedName.FullName, interfaceGuid, scope, identifier) End If Return result End Function Protected Overrides Function FindMethodSymbolInType(typeSymbol As TypeSymbol, targetMethodDef As MethodDefinitionHandle) As MethodSymbol Debug.Assert(TypeOf typeSymbol Is PENamedTypeSymbol OrElse TypeOf typeSymbol Is ErrorTypeSymbol) For Each member In typeSymbol.GetMembersUnordered() Dim method As PEMethodSymbol = TryCast(member, PEMethodSymbol) If method IsNot Nothing AndAlso method.Handle = targetMethodDef Then Return method End If Next Return Nothing End Function Protected Overrides Function FindFieldSymbolInType(typeSymbol As TypeSymbol, fieldDef As FieldDefinitionHandle) As FieldSymbol Debug.Assert(TypeOf typeSymbol Is PENamedTypeSymbol OrElse TypeOf typeSymbol Is ErrorTypeSymbol) For Each member In typeSymbol.GetMembersUnordered() Dim field As PEFieldSymbol = TryCast(member, PEFieldSymbol) If field IsNot Nothing AndAlso field.Handle = fieldDef Then Return field End If Next Return Nothing End Function Friend Overrides Function GetSymbolForMemberRef(memberRef As MemberReferenceHandle, Optional scope As TypeSymbol = Nothing, Optional methodsOnly As Boolean = False) As Symbol Dim targetTypeSymbol As TypeSymbol = GetMemberRefTypeSymbol(memberRef) If targetTypeSymbol Is Nothing Then Return Nothing End If Debug.Assert(Not targetTypeSymbol.IsTupleType) If scope IsNot Nothing AndAlso Not TypeSymbol.Equals(targetTypeSymbol, scope, TypeCompareKind.ConsiderEverything) AndAlso Not targetTypeSymbol.IsBaseTypeOrInterfaceOf(scope, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then Return Nothing End If If Not targetTypeSymbol.IsTupleCompatible() Then targetTypeSymbol = TupleTypeDecoder.DecodeTupleTypesIfApplicable(targetTypeSymbol, elementNames:=Nothing) End If ' We're going to use a special decoder that can generate usable symbols for type parameters without full context. ' (We're not just using a different type - we're also changing the type context.) Dim memberRefDecoder = New MemberRefMetadataDecoder(moduleSymbol, targetTypeSymbol.OriginalDefinition) Dim definition = memberRefDecoder.FindMember(memberRef, methodsOnly) If definition IsNot Nothing AndAlso Not targetTypeSymbol.IsDefinition Then Return definition.AsMember(DirectCast(targetTypeSymbol, NamedTypeSymbol)) End If Return definition End Function Protected Overrides Sub EnqueueTypeSymbolInterfacesAndBaseTypes(typeDefsToSearch As Queue(Of TypeDefinitionHandle), typeSymbolsToSearch As Queue(Of TypeSymbol), typeSymbol As TypeSymbol) For Each iface In typeSymbol.InterfacesNoUseSiteDiagnostics EnqueueTypeSymbol(typeDefsToSearch, typeSymbolsToSearch, iface) Next EnqueueTypeSymbol(typeDefsToSearch, typeSymbolsToSearch, typeSymbol.BaseTypeNoUseSiteDiagnostics) End Sub Protected Overrides Sub EnqueueTypeSymbol(typeDefsToSearch As Queue(Of TypeDefinitionHandle), typeSymbolsToSearch As Queue(Of TypeSymbol), typeSymbol As TypeSymbol) If typeSymbol IsNot Nothing Then Dim peTypeSymbol As PENamedTypeSymbol = TryCast(typeSymbol, PENamedTypeSymbol) If peTypeSymbol IsNot Nothing AndAlso peTypeSymbol.ContainingPEModule Is moduleSymbol Then typeDefsToSearch.Enqueue(peTypeSymbol.Handle) Else typeSymbolsToSearch.Enqueue(typeSymbol) End If End If End Sub Protected Overrides Function GetMethodHandle(method As MethodSymbol) As MethodDefinitionHandle Dim peMethod As PEMethodSymbol = TryCast(method, PEMethodSymbol) If peMethod IsNot Nothing AndAlso peMethod.ContainingModule Is moduleSymbol Then Return peMethod.Handle End If Return Nothing End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Concurrent Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Reflection.Metadata Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE ''' <summary> ''' Helper class to resolve metadata tokens and signatures. ''' </summary> Friend Class MetadataDecoder Inherits MetadataDecoder(Of PEModuleSymbol, TypeSymbol, MethodSymbol, FieldSymbol, Symbol) ''' <summary> ''' Type context for resolving generic type arguments. ''' </summary> Private ReadOnly _typeContextOpt As PENamedTypeSymbol ''' <summary> ''' Method context for resolving generic method type arguments. ''' </summary> Private ReadOnly _methodContextOpt As PEMethodSymbol Public Sub New( moduleSymbol As PEModuleSymbol, context As PENamedTypeSymbol ) Me.New(moduleSymbol, context, Nothing) End Sub Public Sub New( moduleSymbol As PEModuleSymbol, context As PEMethodSymbol ) Me.New(moduleSymbol, DirectCast(context.ContainingType, PENamedTypeSymbol), context) End Sub Public Sub New( moduleSymbol As PEModuleSymbol ) Me.New(moduleSymbol, Nothing, Nothing) End Sub Private Sub New( moduleSymbol As PEModuleSymbol, typeContextOpt As PENamedTypeSymbol, methodContextOpt As PEMethodSymbol ) ' TODO (tomat): if the containing assembly is a source assembly and we are about to decode assembly level attributes, we run into a cycle, ' so for now ignore the assembly identity. MyBase.New(moduleSymbol.Module, If(TypeOf moduleSymbol.ContainingAssembly Is PEAssemblySymbol, moduleSymbol.ContainingAssembly.Identity, Nothing), SymbolFactory.Instance, moduleSymbol) Debug.Assert(moduleSymbol IsNot Nothing) _typeContextOpt = typeContextOpt _methodContextOpt = methodContextOpt End Sub Friend Shadows ReadOnly Property ModuleSymbol As PEModuleSymbol Get Return MyBase.moduleSymbol End Get End Property Protected Overrides Function GetGenericMethodTypeParamSymbol(position As Integer) As TypeSymbol If _methodContextOpt Is Nothing Then Return New UnsupportedMetadataTypeSymbol() End If Dim typeParameters = _methodContextOpt.TypeParameters If typeParameters.Length <= position Then Return New UnsupportedMetadataTypeSymbol() End If Return typeParameters(position) End Function Protected Overrides Function GetGenericTypeParamSymbol(position As Integer) As TypeSymbol Dim type As PENamedTypeSymbol = _typeContextOpt While type IsNot Nothing AndAlso (type.MetadataArity - type.Arity) > position type = TryCast(type.ContainingSymbol, PENamedTypeSymbol) End While If type Is Nothing OrElse type.MetadataArity <= position Then Return New UnsupportedMetadataTypeSymbol() End If position -= (type.MetadataArity - type.Arity) Debug.Assert(position >= 0 AndAlso position < type.Arity) Return type.TypeParameters(position) End Function Protected Overrides Function GetTypeHandleToTypeMap() As ConcurrentDictionary(Of TypeDefinitionHandle, TypeSymbol) Return moduleSymbol.TypeHandleToTypeMap End Function Protected Overrides Function GetTypeRefHandleToTypeMap() As ConcurrentDictionary(Of TypeReferenceHandle, TypeSymbol) Return moduleSymbol.TypeRefHandleToTypeMap End Function Protected Overrides Function LookupNestedTypeDefSymbol( container As TypeSymbol, ByRef emittedName As MetadataTypeName ) As TypeSymbol Dim result = container.LookupMetadataType(emittedName) Debug.Assert(result IsNot Nothing) Return result End Function ''' <summary> ''' Lookup a type defined in referenced assembly. ''' </summary> Protected Overloads Overrides Function LookupTopLevelTypeDefSymbol( referencedAssemblyIndex As Integer, ByRef emittedName As MetadataTypeName ) As TypeSymbol Dim assembly As AssemblySymbol = ModuleSymbol.GetReferencedAssemblySymbol(referencedAssemblyIndex) If assembly Is Nothing Then Return New UnsupportedMetadataTypeSymbol() End If Try Return assembly.LookupTopLevelMetadataType(emittedName, digThroughForwardedTypes:=True) Catch e As Exception When FatalError.ReportAndPropagate(e) ' Trying to get more useful Watson dumps. Throw ExceptionUtilities.Unreachable End Try End Function ''' <summary> ''' Lookup a type defined in a module of a multi-module assembly. ''' </summary> Protected Overrides Function LookupTopLevelTypeDefSymbol(moduleName As String, ByRef emittedName As MetadataTypeName, <Out> ByRef isNoPiaLocalType As Boolean) As TypeSymbol For Each m As ModuleSymbol In moduleSymbol.ContainingAssembly.Modules If String.Equals(m.Name, moduleName, StringComparison.OrdinalIgnoreCase) Then If m Is moduleSymbol Then Return moduleSymbol.LookupTopLevelMetadataType(emittedName, isNoPiaLocalType) Else isNoPiaLocalType = False Return m.LookupTopLevelMetadataType(emittedName) End If End If Next isNoPiaLocalType = False Return New MissingMetadataTypeSymbol.TopLevel(New MissingModuleSymbolWithName(moduleSymbol.ContainingAssembly, moduleName), emittedName, SpecialType.None) End Function ''' <summary> ''' Lookup a type defined in this module. ''' This method will be called only if the type we are ''' looking for hasn't been loaded yet. Otherwise, MetadataDecoder ''' would have found the type in TypeDefRowIdToTypeMap based on its ''' TypeDef row id. ''' </summary> Protected Overloads Overrides Function LookupTopLevelTypeDefSymbol(ByRef emittedName As MetadataTypeName, <Out> ByRef isNoPiaLocalType As Boolean) As TypeSymbol Return moduleSymbol.LookupTopLevelMetadataType(emittedName, isNoPiaLocalType) End Function Protected Overrides Function GetIndexOfReferencedAssembly(identity As AssemblyIdentity) As Integer ' Go through all assemblies referenced by the current module And ' find the one which *exactly* matches the given identity. ' No unification will be performed Dim assemblies = ModuleSymbol.GetReferencedAssemblies() For i = 0 To assemblies.Length - 1 If identity.Equals(assemblies(i)) Then Return i End If Next Return -1 End Function ''' <summary> ''' Perform a check whether the type or at least one of its generic arguments ''' is defined in the specified assemblies. The check is performed recursively. ''' </summary> Public Shared Function IsOrClosedOverATypeFromAssemblies(this As TypeSymbol, assemblies As ImmutableArray(Of AssemblySymbol)) As Boolean Select Case this.Kind Case SymbolKind.TypeParameter Return False Case SymbolKind.ArrayType Return IsOrClosedOverATypeFromAssemblies(DirectCast(this, ArrayTypeSymbol).ElementType, assemblies) Case SymbolKind.NamedType, SymbolKind.ErrorType Dim symbol = DirectCast(this, NamedTypeSymbol) Dim containingAssembly As AssemblySymbol = symbol.OriginalDefinition.ContainingAssembly If containingAssembly IsNot Nothing Then For i = 0 To assemblies.Length - 1 Step 1 If containingAssembly Is assemblies(i) Then Return True End If Next End If Do If symbol.IsTupleType Then Return IsOrClosedOverATypeFromAssemblies(symbol.TupleUnderlyingType, assemblies) End If For Each typeArgument In symbol.TypeArgumentsNoUseSiteDiagnostics If IsOrClosedOverATypeFromAssemblies(typeArgument, assemblies) Then Return True End If Next symbol = symbol.ContainingType Loop While symbol IsNot Nothing Return False Case Else Throw ExceptionUtilities.UnexpectedValue(this.Kind) End Select End Function Protected Overrides Function SubstituteNoPiaLocalType( typeDef As TypeDefinitionHandle, ByRef name As MetadataTypeName, interfaceGuid As String, scope As String, identifier As String ) As TypeSymbol Dim result As TypeSymbol Try Dim isInterface As Boolean = Me.Module.IsInterfaceOrThrow(typeDef) Dim baseType As TypeSymbol = Nothing If Not isInterface Then Dim baseToken As EntityHandle = Me.Module.GetBaseTypeOfTypeOrThrow(typeDef) If Not baseToken.IsNil() Then baseType = GetTypeOfToken(baseToken) End If End If result = SubstituteNoPiaLocalType( name, isInterface, baseType, interfaceGuid, scope, identifier, moduleSymbol.ContainingAssembly) Catch mrEx As BadImageFormatException result = GetUnsupportedMetadataTypeSymbol(mrEx) End Try Debug.Assert(result IsNot Nothing) Dim cache As ConcurrentDictionary(Of TypeDefinitionHandle, TypeSymbol) = GetTypeHandleToTypeMap() Debug.Assert(cache IsNot Nothing) Dim newresult As TypeSymbol = cache.GetOrAdd(typeDef, result) Debug.Assert(newresult Is result OrElse (newresult.Kind = SymbolKind.ErrorType)) Return newresult End Function ''' <summary> ''' Find canonical type for NoPia embedded type. ''' </summary> ''' <returns> ''' Symbol for the canonical type or an ErrorTypeSymbol. Never returns null. ''' </returns> Friend Overloads Shared Function SubstituteNoPiaLocalType( ByRef fullEmittedName As MetadataTypeName, isInterface As Boolean, baseType As TypeSymbol, interfaceGuid As String, scope As String, identifier As String, referringAssembly As AssemblySymbol ) As NamedTypeSymbol Dim result As NamedTypeSymbol = Nothing Dim interfaceGuidValue As Guid = New Guid() Dim haveInterfaceGuidValue As Boolean = False Dim scopeGuidValue As Guid = New Guid() Dim haveScopeGuidValue As Boolean = False If isInterface AndAlso interfaceGuid IsNot Nothing Then haveInterfaceGuidValue = Guid.TryParse(interfaceGuid, interfaceGuidValue) If haveInterfaceGuidValue Then ' To have consistent errors. scope = Nothing identifier = Nothing End If End If If scope IsNot Nothing Then haveScopeGuidValue = Guid.TryParse(scope, scopeGuidValue) End If For Each assembly As AssemblySymbol In referringAssembly.GetNoPiaResolutionAssemblies() Debug.Assert(assembly IsNot Nothing) If assembly Is referringAssembly Then Continue For End If Dim candidate As NamedTypeSymbol = assembly.LookupTopLevelMetadataType(fullEmittedName, digThroughForwardedTypes:=False) Debug.Assert(Not candidate.IsGenericType) ' Ignore type forwarders, error symbols and non-public types If candidate.Kind = SymbolKind.ErrorType OrElse candidate.ContainingAssembly IsNot assembly OrElse candidate.DeclaredAccessibility <> Accessibility.Public Then Continue For End If ' Ignore NoPia local types. ' If candidate is coming from metadata, we don't need to do any special check, ' because we do not create symbols for local types. However, local types defined in source ' is another story. However, if compilation explicitly defines a local type, it should be ' represented by a retargeting assembly, which is supposed to hide the local type. Debug.Assert((Not TypeOf assembly Is SourceAssemblySymbol) OrElse Not DirectCast(assembly, SourceAssemblySymbol).SourceModule.MightContainNoPiaLocalTypes()) Dim candidateGuid As String = Nothing Dim haveCandidateGuidValue As Boolean = False Dim candidateGuidValue As Guid = New Guid() ' The type must be of the same kind (interface, struct, delegate or enum). Select Case candidate.TypeKind Case TypeKind.Interface If Not isInterface Then Continue For End If ' Get candidate's Guid If candidate.GetGuidString(candidateGuid) AndAlso candidateGuid IsNot Nothing Then haveCandidateGuidValue = Guid.TryParse(candidateGuid, candidateGuidValue) End If Case TypeKind.Delegate, TypeKind.Enum, TypeKind.Structure If isInterface Then Continue For End If ' Let's use a trick. To make sure the kind is the same, make sure ' base type is the same. Dim baseSpecialType As SpecialType = If(candidate.BaseTypeNoUseSiteDiagnostics?.SpecialType, SpecialType.None) If baseSpecialType = SpecialType.None OrElse baseSpecialType <> If(baseType?.SpecialType, SpecialType.None) Then Continue For End If Case Else Continue For End Select If haveInterfaceGuidValue OrElse haveCandidateGuidValue Then If Not haveInterfaceGuidValue OrElse Not haveCandidateGuidValue OrElse candidateGuidValue <> interfaceGuidValue Then Continue For End If Else If Not haveScopeGuidValue OrElse identifier Is Nothing OrElse Not String.Equals(identifier, fullEmittedName.FullName, StringComparison.Ordinal) Then Continue For End If ' Scope guid must match candidate's assembly guid. haveCandidateGuidValue = False If assembly.GetGuidString(candidateGuid) AndAlso candidateGuid IsNot Nothing Then haveCandidateGuidValue = Guid.TryParse(candidateGuid, candidateGuidValue) End If If Not haveCandidateGuidValue OrElse scopeGuidValue <> candidateGuidValue Then Continue For End If End If ' OK. It looks like we found canonical type definition. If result IsNot Nothing Then ' Ambiguity result = New NoPiaAmbiguousCanonicalTypeSymbol(referringAssembly, result, candidate) Exit For End If result = candidate Next If result Is Nothing Then result = New NoPiaMissingCanonicalTypeSymbol( referringAssembly, fullEmittedName.FullName, interfaceGuid, scope, identifier) End If Return result End Function Protected Overrides Function FindMethodSymbolInType(typeSymbol As TypeSymbol, targetMethodDef As MethodDefinitionHandle) As MethodSymbol Debug.Assert(TypeOf typeSymbol Is PENamedTypeSymbol OrElse TypeOf typeSymbol Is ErrorTypeSymbol) For Each member In typeSymbol.GetMembersUnordered() Dim method As PEMethodSymbol = TryCast(member, PEMethodSymbol) If method IsNot Nothing AndAlso method.Handle = targetMethodDef Then Return method End If Next Return Nothing End Function Protected Overrides Function FindFieldSymbolInType(typeSymbol As TypeSymbol, fieldDef As FieldDefinitionHandle) As FieldSymbol Debug.Assert(TypeOf typeSymbol Is PENamedTypeSymbol OrElse TypeOf typeSymbol Is ErrorTypeSymbol) For Each member In typeSymbol.GetMembersUnordered() Dim field As PEFieldSymbol = TryCast(member, PEFieldSymbol) If field IsNot Nothing AndAlso field.Handle = fieldDef Then Return field End If Next Return Nothing End Function Friend Overrides Function GetSymbolForMemberRef(memberRef As MemberReferenceHandle, Optional scope As TypeSymbol = Nothing, Optional methodsOnly As Boolean = False) As Symbol Dim targetTypeSymbol As TypeSymbol = GetMemberRefTypeSymbol(memberRef) If targetTypeSymbol Is Nothing Then Return Nothing End If Debug.Assert(Not targetTypeSymbol.IsTupleType) If scope IsNot Nothing AndAlso Not TypeSymbol.Equals(targetTypeSymbol, scope, TypeCompareKind.ConsiderEverything) AndAlso Not targetTypeSymbol.IsBaseTypeOrInterfaceOf(scope, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then Return Nothing End If If Not targetTypeSymbol.IsTupleCompatible() Then targetTypeSymbol = TupleTypeDecoder.DecodeTupleTypesIfApplicable(targetTypeSymbol, elementNames:=Nothing) End If ' We're going to use a special decoder that can generate usable symbols for type parameters without full context. ' (We're not just using a different type - we're also changing the type context.) Dim memberRefDecoder = New MemberRefMetadataDecoder(moduleSymbol, targetTypeSymbol.OriginalDefinition) Dim definition = memberRefDecoder.FindMember(memberRef, methodsOnly) If definition IsNot Nothing AndAlso Not targetTypeSymbol.IsDefinition Then Return definition.AsMember(DirectCast(targetTypeSymbol, NamedTypeSymbol)) End If Return definition End Function Protected Overrides Sub EnqueueTypeSymbolInterfacesAndBaseTypes(typeDefsToSearch As Queue(Of TypeDefinitionHandle), typeSymbolsToSearch As Queue(Of TypeSymbol), typeSymbol As TypeSymbol) For Each iface In typeSymbol.InterfacesNoUseSiteDiagnostics EnqueueTypeSymbol(typeDefsToSearch, typeSymbolsToSearch, iface) Next EnqueueTypeSymbol(typeDefsToSearch, typeSymbolsToSearch, typeSymbol.BaseTypeNoUseSiteDiagnostics) End Sub Protected Overrides Sub EnqueueTypeSymbol(typeDefsToSearch As Queue(Of TypeDefinitionHandle), typeSymbolsToSearch As Queue(Of TypeSymbol), typeSymbol As TypeSymbol) If typeSymbol IsNot Nothing Then Dim peTypeSymbol As PENamedTypeSymbol = TryCast(typeSymbol, PENamedTypeSymbol) If peTypeSymbol IsNot Nothing AndAlso peTypeSymbol.ContainingPEModule Is moduleSymbol Then typeDefsToSearch.Enqueue(peTypeSymbol.Handle) Else typeSymbolsToSearch.Enqueue(typeSymbol) End If End If End Sub Protected Overrides Function GetMethodHandle(method As MethodSymbol) As MethodDefinitionHandle Dim peMethod As PEMethodSymbol = TryCast(method, PEMethodSymbol) If peMethod IsNot Nothing AndAlso peMethod.ContainingModule Is moduleSymbol Then Return peMethod.Handle End If Return Nothing End Function End Class End Namespace
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Compilers/VisualBasic/Portable/Declarations/DeclarationTable.Cache.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend Class DeclarationTable ' The structure of the DeclarationTable provides us with a set of 'old' declarations that ' stay relatively unchanged and a 'new' declaration that is repeatedly added and removed. ' This mimics the expected usage pattern of a user repeatedly typing in a single file. ' Because of this usage pattern, we can cache information about these 'old' declarations and ' keep that around as long as they do not change. For example, we keep a single 'merged ' declaration' for all those root declarations as well as sets of interesting information ' (like the type names in those decls). Private Class Cache ' The merged root declaration for all the 'old' declarations. Friend ReadOnly MergedRoot As Lazy(Of MergedNamespaceDeclaration) ' All the simple type names for all the types in the 'old' declarations. Friend ReadOnly TypeNames As Lazy(Of ICollection(Of String)) Friend ReadOnly NamespaceNames As Lazy(Of ICollection(Of String)) Friend ReadOnly ReferenceDirectives As Lazy(Of ImmutableArray(Of ReferenceDirective)) Public Sub New(table As DeclarationTable) Me.MergedRoot = New Lazy(Of MergedNamespaceDeclaration)(AddressOf table.MergeOlderNamespaces) Me.TypeNames = New Lazy(Of ICollection(Of String))(Function() GetTypeNames(Me.MergedRoot.Value)) Me.NamespaceNames = New Lazy(Of ICollection(Of String))(Function() GetNamespaceNames(Me.MergedRoot.Value)) Me.ReferenceDirectives = New Lazy(Of ImmutableArray(Of ReferenceDirective))( Function() table.SelectManyFromOlderDeclarationsNoEmbedded(Function(r) r.ReferenceDirectives)) End Sub End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend Class DeclarationTable ' The structure of the DeclarationTable provides us with a set of 'old' declarations that ' stay relatively unchanged and a 'new' declaration that is repeatedly added and removed. ' This mimics the expected usage pattern of a user repeatedly typing in a single file. ' Because of this usage pattern, we can cache information about these 'old' declarations and ' keep that around as long as they do not change. For example, we keep a single 'merged ' declaration' for all those root declarations as well as sets of interesting information ' (like the type names in those decls). Private Class Cache ' The merged root declaration for all the 'old' declarations. Friend ReadOnly MergedRoot As Lazy(Of MergedNamespaceDeclaration) ' All the simple type names for all the types in the 'old' declarations. Friend ReadOnly TypeNames As Lazy(Of ICollection(Of String)) Friend ReadOnly NamespaceNames As Lazy(Of ICollection(Of String)) Friend ReadOnly ReferenceDirectives As Lazy(Of ImmutableArray(Of ReferenceDirective)) Public Sub New(table As DeclarationTable) Me.MergedRoot = New Lazy(Of MergedNamespaceDeclaration)(AddressOf table.MergeOlderNamespaces) Me.TypeNames = New Lazy(Of ICollection(Of String))(Function() GetTypeNames(Me.MergedRoot.Value)) Me.NamespaceNames = New Lazy(Of ICollection(Of String))(Function() GetNamespaceNames(Me.MergedRoot.Value)) Me.ReferenceDirectives = New Lazy(Of ImmutableArray(Of ReferenceDirective))( Function() table.SelectManyFromOlderDeclarationsNoEmbedded(Function(r) r.ReferenceDirectives)) End Sub End Class End Class End Namespace
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/EditorFeatures/VisualBasicTest/CodeActions/IntroduceVariable/IntroduceVariableTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.IntroduceVariable Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings.IntroduceVariable Public Class IntroduceVariableTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New IntroduceVariableCodeRefactoringProvider() End Function Protected Overrides Function MassageActions(actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction) Return GetNestedActions(actions) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function Test1() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Console.WriteLine([|1 + 1|]) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Const {|Rename:Value|} As Integer = 1 + 1 Console.WriteLine(Value) End Sub End Module", index:=2) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function Test2() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Console.WriteLine([|1 + 1|]) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Const {|Rename:Value|} As Integer = 1 + 1 Console.WriteLine(Value) End Sub End Module", index:=3) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInSingleLineIfExpression1() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If goo([|1 + 1|]) Then bar(1 + 1) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Const {|Rename:V|} As Integer = 1 + 1 If goo(V) Then bar(1 + 1) End Sub End Module", index:=2) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInSingleLineIfExpression2() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If goo([|1 + 1|]) Then bar(1 + 1) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Const {|Rename:V|} As Integer = 1 + 1 If goo(V) Then bar(V) End Sub End Module", index:=3) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInSingleLineIfStatement1() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If goo(1 + 1) Then bar([|1 + 1|]) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If goo(1 + 1) Then Const {|Rename:V|} As Integer = 1 + 1 bar(V) End If End Sub End Module", index:=2) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInSingleLineIfStatement2() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If goo(1 + 1) Then bar([|1 + 1|]) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Const {|Rename:V|} As Integer = 1 + 1 If goo(V) Then bar(V) End Sub End Module", index:=3) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNoIntroduceFieldOnMethodTypeParameter() As Task Dim source = "Module Program Sub Main(Of T)() Goo([|CType(2.ToString(), T)|]) End Sub End Module" Await TestExactActionSetOfferedAsync( source, expectedActionSet:={ String.Format(FeaturesResources.Introduce_local_for_0, "CType(2.ToString(), T)"), String.Format(FeaturesResources.Introduce_local_for_all_occurrences_of_0, "CType(2.ToString(), T)")}) ' Verifies "Introduce field ..." is missing End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNoIntroduceFieldOnMethodParameter() As Task Dim source = "Module Program Sub Main(x As Integer) Goo([|x.ToString()|]) End Sub End Module" Await TestExactActionSetOfferedAsync( source, expectedActionSet:={ String.Format(FeaturesResources.Introduce_local_for_0, "x.ToString()"), String.Format(FeaturesResources.Introduce_local_for_all_occurrences_of_0, "x.ToString()")}) ' Verifies "Introduce field ..." is missing End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNoRefactoringOnExpressionInAssignmentStatement() As Task Dim source = "Module Program Sub Main(x As Integer) Dim r = [|x.ToString()|] End Sub End Module" Await TestMissingInRegularAndScriptAsync(source) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestLocalGeneratedInInnerBlock1() As Task Dim source = "Module Program Sub Main(x As Integer) If True Then Goo([|x.ToString()|]) End If End Sub End Module" Dim expected = "Module Program Sub Main(x As Integer) If True Then Dim {|Rename:v|} As String = x.ToString() Goo(v) End If End Sub End Module" Await TestInRegularAndScriptAsync(source, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestLocalGeneratedInInnerBlock2() As Task Dim source = "Module Program Sub Main(x As Integer) If True Then Goo([|x.ToString()|]) End If End Sub End Module" Dim expected = "Module Program Sub Main(x As Integer) If True Then Dim {|Rename:v|} As String = x.ToString() Goo(v) End If End Sub End Module" Await TestInRegularAndScriptAsync(source, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestLocalFromSingleExpressionInAnonType() As Task Dim source = "Module Program Sub Main(x As Integer) Dim f1 = New With {.SomeString = [|x.ToString()|]} End Sub End Module" Dim expected = "Module Program Sub Main(x As Integer) Dim {|Rename:v|} As String = x.ToString() Dim f1 = New With {.SomeString = v} End Sub End Module" Await TestInRegularAndScriptAsync(source, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestLocalFromMultipleExpressionsInAnonType() As Task Dim source = "Module Program Sub Main(x As Integer) Dim f1 = New With {.SomeString = [|x.ToString()|], .SomeOtherString = x.ToString()} Dim f2 = New With {.SomeString = x.ToString(), .SomeOtherString = x.ToString()} Dim str As String = x.ToString() End Sub End Module" Dim expected = "Module Program Sub Main(x As Integer) Dim {|Rename:v|} As String = x.ToString() Dim f1 = New With {.SomeString = v, .SomeOtherString = v} Dim f2 = New With {.SomeString = v, .SomeOtherString = v} Dim str As String = v End Sub End Module" Await TestInRegularAndScriptAsync(source, expected, index:=1) End Function <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestLocalFromInferredFieldInitializer() As Task Dim source = "Imports System Class C Sub M() Dim a As New With {[|Environment.TickCount|]} End Sub End Class" Dim expected = "Imports System Class C Sub M() Dim {|Rename:tickCount|} As Integer = Environment.TickCount Dim a As New With {tickCount} End Sub End Class" Await TestInRegularAndScriptAsync(source, expected, index:=1) End Function <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestLocalFromYieldStatement() As Task Dim source = "Imports System Class C Iterator Function F() As IEnumerable(Of Integer) Yield [|Environment.TickCount * 2|] End Function End Class" Dim expected = "Imports System Class C Iterator Function F() As IEnumerable(Of Integer) Dim {|Rename:v|} As Integer = Environment.TickCount * 2 Yield v End Function End Class" Await TestInRegularAndScriptAsync(source, expected, index:=1) End Function <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestLocalFromWhileStatement() As Task Dim source = "Class C Sub M() Dim x = 1 While [|x = 1|] End While End Sub End Class" Dim expected = "Class C Sub M() Dim x = 1 Dim {|Rename:v|} As Boolean = x = 1 While v End While End Sub End Class" Await TestInRegularAndScriptAsync(source, expected, index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestLocalFromSingleExpressionInObjectInitializer() As Task Dim source = "Module Program Structure GooStruct Dim GooMember1 As String End Structure Sub Main(x As Integer) Dim f1 = New GooStruct With {.GooMember1 = [|""t"" + ""test""|]} End Sub End Module" Dim expected = "Module Program Structure GooStruct Dim GooMember1 As String End Structure Sub Main(x As Integer) Const {|Rename:V|} As String = ""t"" + ""test"" Dim f1 = New GooStruct With {.GooMember1 = V} End Sub End Module" Await TestInRegularAndScriptAsync(source, expected, index:=2) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestLocalFromMultipleExpressionsInObjectInitializer() As Task Dim code = " Module Program Structure GooStruct Dim GooMember1 As String Dim GooMember2 As String End Structure Sub Main(x As Integer) Dim f1 = New GooStruct With {.GooMember1 = [|""t"" + ""test""|], .GooMember2 = ""t"" + ""test""} Dim f2 = New GooStruct With {.GooMember1 = ""t"" + ""test"", .GooMember2 = ""t"" + ""test""} Dim str As String = ""t"" + ""test"" End Sub End Module " Dim expected = " Module Program Structure GooStruct Dim GooMember1 As String Dim GooMember2 As String End Structure Sub Main(x As Integer) Const {|Rename:V|} As String = ""t"" + ""test"" Dim f1 = New GooStruct With {.GooMember1 = V, .GooMember2 = V} Dim f2 = New GooStruct With {.GooMember1 = V, .GooMember2 = V} Dim str As String = V End Sub End Module " Await TestInRegularAndScriptAsync(code, expected, index:=3) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestFieldFromMultipleExpressionsInAnonType() As Task Dim source = "Class Program Dim q = New With {.str = [|""t"" + ""test""|]} Dim r = New With {.str = ""t"" + ""test""} Sub Goo() Dim x = ""t"" + ""test"" End Sub End Class" Dim expected = "Class Program Private Const {|Rename:V|} As String = ""t"" + ""test"" Dim q = New With {.str = V} Dim r = New With {.str = V} Sub Goo() Dim x = V End Sub End Class" Await TestInRegularAndScriptAsync(source, expected, index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestPrivateFieldFromExpressionInField() As Task Dim source = "Class Program Dim x = Goo([|2 + 2|]) End Class" Dim expected = "Class Program Private Const {|Rename:V|} As Integer = 2 + 2 Dim x = Goo(V) End Class" Await TestInRegularAndScriptAsync(source, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNoLocalFromExpressionInField() As Task Dim source = "Class Program Dim x = Goo([|2 + 2|]) End Class" Await TestExactActionSetOfferedAsync(source, {String.Format(FeaturesResources.Introduce_constant_for_0, "2 + 2"), String.Format(FeaturesResources.Introduce_constant_for_all_occurrences_of_0, "2 + 2")}) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestSharedModifierAbsentInGeneratedModuleFields() As Task Dim source = "Module Program Private ReadOnly y As Integer = 1 Dim x = Goo([|2 + y|]) End Module" Dim expected = "Module Program Private ReadOnly y As Integer = 1 Private ReadOnly {|Rename:v|} As Integer = 2 + y Dim x = Goo(v) End Module" Await TestInRegularAndScriptAsync(source, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestSingleLocalInsertLocation() As Task Dim source = "Class Program Sub Method1() Dim v1 As String = ""TEST"" Dim v2 As Integer = 2 + 2 Goo([|2 + 2|]) End Sub End Class" Dim expected = "Class Program Sub Method1() Dim v1 As String = ""TEST"" Dim v2 As Integer = 2 + 2 Const {|Rename:V|} As Integer = 2 + 2 Goo(V) End Sub End Class" Await TestInRegularAndScriptAsync(source, expected, index:=2) End Function #Region "Parameter context" <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestConstantFieldGenerationForParameterSingleOccurrence() As Task ' This is incorrect: the field type should be Integer, not Object Dim source = "Module Module1 Sub Goo(Optional x As Integer = [|42|]) End Sub End Module" Dim expected = "Module Module1 Private Const {|Rename:V|} As Integer = 42 Sub Goo(Optional x As Integer = V) End Sub End Module" Await TestInRegularAndScriptAsync(source, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestConstantFieldGenerationForParameterAllOccurrences() As Task ' This is incorrect: the field type should be Integer, not Object Dim source = "Module Module1 Sub Bar(Optional x As Integer = 42) End Sub Sub Goo(Optional x As Integer = [|42|]) End Sub End Module" Dim expected = "Module Module1 Private Const {|Rename:V|} As Integer = 42 Sub Bar(Optional x As Integer = V) End Sub Sub Goo(Optional x As Integer = V) End Sub End Module" Await TestInRegularAndScriptAsync(source, expected, index:=1) End Function #End Region <WorkItem(540269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540269")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestReplaceDottedExpression() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Console.WriteLine([|Goo.someVariable|]) Console.WriteLine(Goo.someVariable) End Sub End Module Friend Class Goo Shared Public someVariable As Integer End Class", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim {|Rename:someVariable|} As Integer = Goo.someVariable Console.WriteLine(someVariable) Console.WriteLine(someVariable) End Sub End Module Friend Class Goo Shared Public someVariable As Integer End Class", index:=1) End Function <WorkItem(540457, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540457")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestReplaceSingleLineIfWithMultiLine1() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Goo([|2 + 2|]) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Const {|Rename:V|} As Integer = 2 + 2 Goo(V) End If End Sub End Module", index:=2) End Function <WorkItem(540457, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540457")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestReplaceSingleLineIfWithMultiLine2() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Goo([|1 + 1|]) Else Bar(1 + 1) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Const {|Rename:V|} As Integer = 1 + 1 Goo(V) Else Bar(1 + 1) End If End Sub End Module", index:=2) End Function <WorkItem(540457, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540457")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestReplaceSingleLineIfWithMultiLine3() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Goo([|1 + 1|]) Else Bar(1 + 1) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Const {|Rename:V|} As Integer = 1 + 1 If True Then Goo(V) Else Bar(V) End Sub End Module", index:=3) End Function <WorkItem(540457, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540457")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestReplaceSingleLineIfWithMultiLine4() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Goo(1 + 1) Else Bar([|1 + 1|]) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Goo(1 + 1) Else Const {|Rename:V|} As Integer = 1 + 1 Bar(V) End If End Sub End Module", index:=2) End Function <WorkItem(540468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540468")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestCantExtractMethodTypeParameterToFieldCount() As Task Await TestActionCountAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(Of T)(x As Integer) Goo([|CType(2.ToString(), T)|]) End Sub End Module", count:=2) End Function <WorkItem(540468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540468")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestCantExtractMethodTypeParameterToField() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(Of T)(x As Integer) Goo([|CType(2.ToString(), T)|]) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(Of T)(x As Integer) Dim {|Rename:t|} As T = CType(2.ToString(), T) Goo(t) End Sub End Module") End Function <WorkItem(540489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540489")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestOnlyFieldsInsideConstructorInitializer() As Task Await TestActionCountAsync( "Class Goo Sub New() Me.New([|2 + 2|]) End Sub Sub New(v As Integer) End Sub End Class", count:=2) Await TestInRegularAndScriptAsync( "Class Goo Sub New() Me.New([|2 + 2|]) End Sub Sub New(v As Integer) End Sub End Class", "Class Goo Private Const {|Rename:V|} As Integer = 2 + 2 Sub New() Me.New(V) End Sub Sub New(v As Integer) End Sub End Class") End Function <WorkItem(540485, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540485")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestIntroduceLocalForConstantExpression() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Dim s As String() = New String([|10|]) {} End Sub End Module", "Module Program Sub Main(args As String()) Const {|Rename:V|} As Integer = 10 Dim s As String() = New String(V) {} End Sub End Module", index:=3) End Function <WorkItem(1065689, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1065689")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestIntroduceLocalForConstantExpressionWithTrailingTrivia() As Task Await TestInRegularAndScriptAsync( " Class C Private Function GetX() As Object Return [|""c d "" + ' comment 1 ""a b"" ' comment 2|] End Function End Class ", " Class C Private Function GetX() As Object Const {|Rename:V|} As String = ""c d "" + ' comment 1 ""a b"" Return V ' comment 2 End Function End Class ", index:=3) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestIntroduceFieldWithTrailingTrivia() As Task Await TestInRegularAndScriptAsync( " Class C Private Sub S() Dim x = 1 + [|2|] ' comment End Sub End Class ", " Class C Private Const {|Rename:V|} As Integer = 2 Private Sub S() Dim x = 1 + V ' comment End Sub End Class ", index:=1) End Function <WorkItem(540487, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540487")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestFormattingForPartialExpression() As Task Dim code = " Module Program Sub Main() Dim i = [|1 + 2|] + 3 End Sub End Module " Dim expected = " Module Program Sub Main() Const {|Rename:V|} As Integer = 1 + 2 Dim i = V + 3 End Sub End Module " Await TestInRegularAndScriptAsync(code, expected, index:=2) End Function <WorkItem(540491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540491")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInAttribute1() As Task Await TestInRegularAndScriptAsync( "<Attr([|2 + 2|])> Class Goo End Class Friend Class AttrAttribute Inherits Attribute End Class", "<Attr(Goo.V)> Class Goo Friend Const {|Rename:V|} As Integer = 2 + 2 End Class Friend Class AttrAttribute Inherits Attribute End Class") End Function <WorkItem(540490, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540490")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInMyClassNew() As Task Await TestInRegularAndScriptAsync( "Class Goo Sub New() MyClass.New([|42|]) End Sub Sub New(x As Integer) End Sub End Class", "Class Goo Private Const {|Rename:X|} As Integer = 42 Sub New() MyClass.New(X) End Sub Sub New(x As Integer) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestSingleToMultiLineIf1() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Goo([|2 + 2|]) Else Bar(2 + 2) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Const {|Rename:V|} As Integer = 2 + 2 Goo(V) Else Bar(2 + 2) End If End Sub End Module", index:=2) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestSingleToMultiLineIf2() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Goo([|2 + 2|]) Else Bar(2 + 2) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Const {|Rename:V|} As Integer = 2 + 2 If True Then Goo(V) Else Bar(V) End Sub End Module", index:=3) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestSingleToMultiLineIf3() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Goo(2 + 2) Else Bar([|2 + 2|]) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Goo(2 + 2) Else Const {|Rename:V|} As Integer = 2 + 2 Bar(V) End If End Sub End Module", index:=2) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestSingleToMultiLineIf4() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Goo(2 + 2) Else Bar([|2 + 2|]) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Const {|Rename:V|} As Integer = 2 + 2 If True Then Goo(V) Else Bar(V) End Sub End Module", index:=3) End Function <WorkItem(541604, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541604")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestAttribute() As Task Await TestInRegularAndScriptAsync( "<Attr([|2 + 2|])> Class Goo End Class Friend Class AttrAttribute Inherits System.Attribute End Class", "<Attr(Goo.V)> Class Goo Friend Const {|Rename:V|} As Integer = 2 + 2 End Class Friend Class AttrAttribute Inherits System.Attribute End Class") End Function <WorkItem(542092, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542092")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestRangeArgumentLowerBound1() As Task Await TestMissingInRegularAndScriptAsync("Module M Sub Main() Dim x() As Integer ReDim x([|0|] To 5) End Sub End Module") End Function <WorkItem(542092, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542092")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestRangeArgumentLowerBound2() As Task Dim code = " Module M Sub Main() Dim x() As Integer ReDim x(0 To 5) Dim a = [|0|] + 1 End Sub End Module " Dim expected = " Module M Sub Main() Dim x() As Integer ReDim x(0 To 5) Const {|Rename:V|} As Integer = 0 Dim a = V + 1 End Sub End Module " Await TestInRegularAndScriptAsync(code, expected, index:=3) End Function <WorkItem(543029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543029"), WorkItem(542963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542963"), WorkItem(542295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542295")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestUntypedExpression() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim q As Object If True Then q = [|Sub() End Sub|] End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim q As Object If True Then Dim {|Rename:p|} As Object = Sub() End Sub q = p End If End Sub End Module") End Function <WorkItem(542374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542374")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestFieldConstantInAttribute1() As Task Await TestInRegularAndScriptAsync( "<Goo(2 + 3 + 4)> Module Program Dim x = [|2 + 3|] + 4 End Module Friend Class GooAttribute Inherits Attribute Sub New(x As Integer) End Sub End Class", "<Goo(2 + 3 + 4)> Module Program Private Const {|Rename:V|} As Integer = 2 + 3 Dim x = V + 4 End Module Friend Class GooAttribute Inherits Attribute Sub New(x As Integer) End Sub End Class") End Function <WorkItem(542374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542374")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestFieldConstantInAttribute2() As Task Await TestAsync( "<Goo(2 + 3 + 4)> Module Program Dim x = [|2 + 3|] + 4 End Module Friend Class GooAttribute Inherits Attribute Sub New(x As Integer) End Sub End Class", "<Goo(V + 4)> Module Program Friend Const {|Rename:V|} As Integer = 2 + 3 Dim x = V + 4 End Module Friend Class GooAttribute Inherits Attribute Sub New(x As Integer) End Sub End Class", index:=1, parseOptions:=Nothing) End Function <WorkItem(542783, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542783")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestMissingOnAttributeName() As Task Await TestMissingInRegularAndScriptAsync( "<[|Obsolete|]> Class C End Class") End Function <WorkItem(542811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542811")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestMissingOnFilterClause() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub Main() Try Catch ex As Exception When [|+|] End Try End Sub End Module") End Function <WorkItem(542906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542906")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNoIntroduceLocalInAttribute() As Task Dim input = "Module Program \n <Obsolete([|""""|])> \n Sub Main(args As String()) \n End Sub \n End Module" Await TestActionCountAsync( NewLines(input), count:=2) Await TestInRegularAndScriptAsync( NewLines(input), "Module Program Private Const {|Rename:V|} As String = """" <Obsolete(V)> Sub Main(args As String()) End Sub End Module") End Function <WorkItem(542947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542947")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNotOnMyBase() As Task Await TestMissingInRegularAndScriptAsync( "Class c1 Public res As String Sub Goo() res = ""1"" End Sub End Class Class c2 Inherits c1 Sub scen1() [|MyBase|].Goo() End Sub End Class") End Function <WorkItem(541966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541966")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNestedMultiLineIf1() As Task Dim code = " Imports System Module Program Sub Main() If True Then If True Then Console.WriteLine([|1|]) Else Console.WriteLine(2) Else Console.WriteLine(3) End Sub End Module " Dim expected = " Imports System Module Program Sub Main() If True Then If True Then Const {|Rename:Value|} As Integer = 1 Console.WriteLine(Value) Else Console.WriteLine(2) End If Else Console.WriteLine(3) End If End Sub End Module " Await TestInRegularAndScriptAsync(code, expected, index:=3) End Function <WorkItem(541966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541966")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNestedMultiLineIf2() As Task Dim code = " Imports System Module Program Sub Main() If True Then If True Then Console.WriteLine(1) Else Console.WriteLine([|2|]) Else Console.WriteLine(3) End Sub End Module " Dim expected = " Imports System Module Program Sub Main() If True Then If True Then Console.WriteLine(1) Else Const {|Rename:Value|} As Integer = 2 Console.WriteLine(Value) End If Else Console.WriteLine(3) End If End Sub End Module " Await TestInRegularAndScriptAsync(code, expected, index:=3) End Function <WorkItem(541966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541966")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNestedMultiLineIf3() As Task Dim code = " Imports System Module Program Sub Main() If True Then If True Then Console.WriteLine(1) Else Console.WriteLine(2) Else Console.WriteLine([|3|]) End Sub End Module " Dim expected = " Imports System Module Program Sub Main() If True Then If True Then Console.WriteLine(1) Else Console.WriteLine(2) Else Const {|Rename:Value|} As Integer = 3 Console.WriteLine(Value) End If End Sub End Module " Await TestInRegularAndScriptAsync(code, expected, index:=3) End Function <WorkItem(543273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543273")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestSingleLineLambda1() As Task Await TestInRegularAndScriptAsync( "Imports System Module Program Sub Main Dim a = Sub(x As Integer) Console.WriteLine([|x + 1|]) ' Introduce local End Sub End Module", "Imports System Module Program Sub Main Dim a = Sub(x As Integer) Dim {|Rename:value|} As Integer = x + 1 Console.WriteLine(value) End Sub ' Introduce local End Sub End Module") End Function <WorkItem(543273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543273")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestSingleLineLambda2() As Task Await TestInRegularAndScriptAsync( "Imports System Module Program Sub Main Dim a = Sub(x As Integer) If True Then Console.WriteLine([|x + 1|]) Else Console.WriteLine() End Sub End Module", "Imports System Module Program Sub Main Dim a = Sub(x As Integer) If True Then Dim {|Rename:value|} As Integer = x + 1 Console.WriteLine(value) Else Console.WriteLine() End If End Sub End Sub End Module") End Function <WorkItem(543273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543273")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestSingleLineLambda3() As Task Await TestInRegularAndScriptAsync( "Imports System Module Program Sub Main Dim a = Sub(x As Integer) If True Then Console.WriteLine() Else Console.WriteLine([|x + 1|]) End Sub End Module", "Imports System Module Program Sub Main Dim a = Sub(x As Integer) If True Then Console.WriteLine() Else Dim {|Rename:value|} As Integer = x + 1 Console.WriteLine(value) End If End Sub End Sub End Module") End Function <WorkItem(543273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543273")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestSingleLineLambda4() As Task Await TestInRegularAndScriptAsync( "Imports System Module Program Sub Main Dim a = Sub(x As Integer) If True Then Console.WriteLine([|x + 1|]) Else Console.WriteLine(x + 1) End Sub End Module", "Imports System Module Program Sub Main Dim a = Sub(x As Integer) Dim {|Rename:value|} As Integer = x + 1 If True Then Console.WriteLine(value) Else Console.WriteLine(value) End Sub End Sub End Module", index:=1) End Function <WorkItem(543299, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543299")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestSingleLineLambda5() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Dim query = Sub(a) a = New With {Key .Key = Function(ByVal arg As Integer) As Integer Return arg End Function}.Key.Invoke([|a Or a|]) End Sub End Module", "Module Program Sub Main(args As String()) Dim query = Sub(a) Dim {|Rename:arg1|} As Object = a Or a a = New With {Key .Key = Function(ByVal arg As Integer) As Integer Return arg End Function}.Key.Invoke(arg1) End Sub End Sub End Module") End Function <WorkItem(542762, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542762")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNotInIntoClause() As Task Await TestMissingInRegularAndScriptAsync( "Imports System.Linq Module Sub Main() Dim x = Aggregate y In New Integer() {1} Into [|Count()|] End Sub End Module") End Function <WorkItem(543289, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543289")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNotOnAttribute1() As Task Await TestMissingInRegularAndScriptAsync( "Option Explicit Off Module Program <Runtime.CompilerServices.[|Extension|]()> _ Function Extension(ByVal x As Integer) As Integer Return x End Function End Module") End Function <WorkItem(543289, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543289")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNotOnAttribute1CommentsAfterLineContinuation() As Task Await TestMissingInRegularAndScriptAsync( "Option Explicit Off Module Program <Runtime.CompilerServices.[|Extension|]()> _ ' Test Function Extension(ByVal x As Integer) As Integer Return x End Function End Module") End Function <WorkItem(543289, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543289")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNotOnAttribute2() As Task Await TestMissingInRegularAndScriptAsync( "Option Explicit Off Module Program <Runtime.CompilerServices.[|Extension()|]> _ Function Extension(ByVal x As Integer) As Integer Return x End Function End Module") End Function <WorkItem(543289, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543289")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNotOnAttribute2CommentsAfterLineContinuation() As Task Await TestMissingInRegularAndScriptAsync( "Option Explicit Off Module Program <Runtime.CompilerServices.[|Extension()|]> _ ' Test Function Extension(ByVal x As Integer) As Integer Return x End Function End Module") End Function <WorkItem(543461, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543461")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestCollectionInitializer() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Dim i1 = New Integer() [|{4, 5}|] End Sub End Module") End Function <WorkItem(543573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543573")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestCaseInsensitiveNameConflict() As Task Await TestInRegularAndScriptAsync( "Class M Public Function Goo() Return [|Me.Goo|] * 0 End Function End Class", "Class M Public Function Goo() Dim {|Rename:goo1|} As Object = Me.Goo Return goo1 * 0 End Function End Class") End Function <WorkItem(543590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543590")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestQuery1() As Task Await TestInRegularAndScriptAsync( "Imports System.Linq Public Class Base Public Function Sample(ByVal arg As Integer) As Integer Dim results = From s In New Integer() {1} Select [|Sample(s)|] Return 0 End Function End Class", "Imports System.Linq Public Class Base Public Function Sample(ByVal arg As Integer) As Integer Dim results = From s In New Integer() {1} Let {|Rename:v|} = Sample(s) Select v Return 0 End Function End Class") End Function <WorkItem(543590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543590")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestQueryCount1() As Task Await TestActionCountAsync( "Imports System.Linq Public Class Base Public Function Sample(ByVal arg As Integer) As Integer Dim results = From s In New Integer() {1} Select [|Sample(s)|] Return 0 End Function End Class", count:=2) End Function <WorkItem(543590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543590")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestQuery2() As Task Await TestInRegularAndScriptAsync( "Imports System.Linq Public Class Base Public Function Sample(ByVal arg As Integer) As Integer Dim results = From s In New Integer() {1} Where [|Sample(s)|] > 21 Select Sample(s) Return 0 End Function End Class", "Imports System.Linq Public Class Base Public Function Sample(ByVal arg As Integer) As Integer Dim results = From s In New Integer() {1} Let {|Rename:v|} = Sample(s) Where v > 21 Select Sample(s) Return 0 End Function End Class") End Function <WorkItem(543590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543590")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestQuery3() As Task Await TestInRegularAndScriptAsync( "Imports System.Linq Public Class Base Public Function Sample(ByVal arg As Integer) As Integer Dim results = From s In New Integer() {1} Where [|Sample(s)|] > 21 Select Sample(s) Return 0 End Function End Class", "Imports System.Linq Public Class Base Public Function Sample(ByVal arg As Integer) As Integer Dim results = From s In New Integer() {1} Let {|Rename:v|} = Sample(s) Where v > 21 Select v Return 0 End Function End Class", index:=1) End Function <WorkItem(543590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543590")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestQuery4() As Task Await TestInRegularAndScriptAsync( "Imports System.Linq Public Class Base Public Function Sample(ByVal arg As Integer) As Integer Dim results = From s In New Integer() {1} Where Sample(s) > 21 Select [|Sample(s)|] Return 0 End Function End Class", "Imports System.Linq Public Class Base Public Function Sample(ByVal arg As Integer) As Integer Dim results = From s In New Integer() {1} Where Sample(s) > 21 Let {|Rename:v|} = Sample(s) Select v Return 0 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestQuery5() As Task Await TestInRegularAndScriptAsync( "Imports System.Linq Public Class Base Public Function Sample(ByVal arg As Integer) As Integer Dim results = From s In New Integer() {1} Where Sample(s) > 21 Select [|Sample(s)|] Return 0 End Function End Class", "Imports System.Linq Public Class Base Public Function Sample(ByVal arg As Integer) As Integer Dim results = From s In New Integer() {1} Let {|Rename:v|} = Sample(s) Where v > 21 Select v Return 0 End Function End Class", index:=1) End Function <WorkItem(543529, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543529")> <WorkItem(909152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/909152")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInStatementlessConstructorParameter() As Task Await TestMissingInRegularAndScriptAsync("Class C1 Sub New(Optional ByRef x As String = [|Nothing|]) End Sub End Class") End Function <WorkItem(543650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543650")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestReferenceToAnonymousTypeProperty() As Task Await TestMissingInRegularAndScriptAsync( "Class AM Sub M(args As String()) Dim var1 As New AM Dim at1 As New With {var1, .friend = [|.var1|]} End Sub End Class") End Function <WorkItem(543698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543698")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestIntegerArrayExpression() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main() Return [|New Integer() {}|] End Sub End Module", "Module Program Sub Main() Dim {|Rename:vs|} As Integer() = New Integer() {} Return vs End Sub End Module") End Function <WorkItem(544273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544273")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestAttributeNamedParameter() As Task Await TestMissingInRegularAndScriptAsync( "Class TestAttribute Inherits Attribute Public Sub New(Optional a As Integer = 42) End Sub End Class <Test([|a|]:=5)> Class Goo End Class") End Function <WorkItem(544265, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544265")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestMissingOnWrittenToExpression() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub Main() Dim x = New Integer() {1, 2} [|x(1)|] = 2 End Sub End Module") End Function <WorkItem(543824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543824")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestImplicitMemberAccess1() As Task Await TestMissingInRegularAndScriptAsync( "Imports System Public Class C1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Class Public Class C2 Public Shared Sub Main() Dim x = 1 + New C1() With {.FieldStr = [|.FieldInt|].ToString()} End Sub End Class") End Function <WorkItem(543824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543824")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestImplicitMemberAccess2() As Task Await TestMissingInRegularAndScriptAsync( "Imports System Public Class C1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Class Public Class C2 Public Shared Sub Main() Dim x = 1 + New C1() With {.FieldStr = [|.FieldInt.ToString|]()} End Sub End Class") End Function <WorkItem(543824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543824")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestImplicitMemberAccess3() As Task Await TestMissingInRegularAndScriptAsync( "Imports System Public Class C1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Class Public Class C2 Public Shared Sub Main() Dim x = 1 + New C1() With {.FieldStr = [|.FieldInt.ToString()|]} End Sub End Class") End Function <WorkItem(543824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543824")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestImplicitMemberAccess4() As Task Dim code = " Imports System Public Class C1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Class Public Class C2 Public Shared Sub Main() Dim x = 1 + [|New C1() With {.FieldStr = .FieldInt.ToString()}|] End Sub End Class " Dim expected = " Imports System Public Class C1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Class Public Class C2 Public Shared Sub Main() Dim {|Rename:c1|} As C1 = New C1() With {.FieldStr = .FieldInt.ToString()} Dim x = 1 + c1 End Sub End Class " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(529510, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529510")> <WpfFact(Skip:="529510"), Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNoRefactoringOnAddressOfExpression() As Task Dim source = "Imports System Module Module1 Public Sub Goo(ByVal a1 As Exception) End Sub Public Sub goo(ByVal a1 As Action(Of ArgumentException)) End Sub Sub Main() Goo(New Action(Of Exception)([|AddressOf Goo|])) End Sub End Module" Await TestMissingInRegularAndScriptAsync(source) End Function <WorkItem(529510, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529510")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)> Public Async Function TestMissingOnAddressOfInDelegate() As Task Await TestMissingInRegularAndScriptAsync( "Module Module1 Public Sub Goo(ByVal a1 As Exception) End Sub Public Sub goo(ByVal a1 As Action(Of ArgumentException)) End Sub Sub Main() goo(New Action(Of Exception)([|AddressOf Goo|])) End Sub End Module") End Function <WorkItem(545168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545168")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)> Public Async Function TestMissingOnXmlName() As Task Await TestMissingInRegularAndScriptAsync( "Module M Sub Main() Dim x = <[|x|]/> End Sub End Module") End Function <WorkItem(545262, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545262")> <WorkItem(909152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/909152")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInTernaryConditional() As Task Await TestMissingInRegularAndScriptAsync("Module Program Sub Main(args As String()) Dim p As Object = Nothing Dim Obj1 = If(New With {.a = True}.a, p, [|Nothing|]) End Sub End Module") End Function <WorkItem(545316, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545316")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInPropertyInitializer() As Task Await TestInRegularAndScriptAsync( "Module Module1 Property Prop As New List(Of String) From {[|""One""|], ""two""} End Module", "Module Module1 Private Const {|Rename:V|} As String = ""One"" Property Prop As New List(Of String) From {V, ""two""} End Module") End Function <WorkItem(545308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545308")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestDoNotMergeAmpersand() As Task Dim code = " Module Module1 Public Sub goo(Optional ByVal arg = ([|""a""|]) & ""b"") End Sub End Module " Dim expected = " Module Module1 Private Const {|Rename:V|} As String = ""a"" Public Sub goo(Optional ByVal arg = V & ""b"") End Sub End Module " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(545258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545258")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestVenusGeneration1() As Task Dim code = " Class C Sub Goo() #ExternalSource (""Goo"", 1) Console.WriteLine([|5|]) #End ExternalSource End Sub End Class " Dim expected = " Class C Sub Goo() #ExternalSource (""Goo"", 1) Const {|Rename:V|} As Integer = 5 Console.WriteLine(V) #End ExternalSource End Sub End Class " Await TestExactActionSetOfferedAsync(code, {String.Format(FeaturesResources.Introduce_local_constant_for_0, "5"), String.Format(FeaturesResources.Introduce_local_constant_for_all_occurrences_of_0, "5")}) Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(545258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545258")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestVenusGeneration2() As Task Dim code = " Class C #ExternalSource (""Goo"", 1) Sub Goo() If False Then Console.WriteLine([|5|]) End If End Sub #End ExternalSource End Class " Await TestExactActionSetOfferedAsync(code, {String.Format(FeaturesResources.Introduce_local_constant_for_0, "5"), String.Format(FeaturesResources.Introduce_local_constant_for_all_occurrences_of_0, "5")}) End Function <WorkItem(545258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545258")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestVenusGeneration3() As Task Dim code = " Class C Sub Goo() #ExternalSource (""Goo"", 1) If False Then Console.WriteLine([|5|]) End If #End ExternalSource End Sub End Class " Dim expected = " Class C Sub Goo() #ExternalSource (""Goo"", 1) If False Then Const {|Rename:V|} As Integer = 5 Console.WriteLine(V) End If #End ExternalSource End Sub End Class " Await TestExactActionSetOfferedAsync(code, {String.Format(FeaturesResources.Introduce_local_constant_for_0, "5"), String.Format(FeaturesResources.Introduce_local_constant_for_all_occurrences_of_0, "5")}) Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(545525, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545525")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInvocation() As Task Await TestInRegularAndScriptAsync( "Option Strict On Class C Shared Sub Main() Dim x = [|New C().Goo()|](0) End Sub Function Goo() As Integer() End Function End Class", "Option Strict On Class C Shared Sub Main() Dim {|Rename:vs|} As Integer() = New C().Goo() Dim x = vs(0) End Sub Function Goo() As Integer() End Function End Class") End Function <WorkItem(545829, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545829")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestOnImplicitMemberAccess() As Task Await TestAsync( "Module Program Sub Main() With """" Dim x = [|.GetHashCode|] Xor &H7F3E ' Introduce Local End With End Sub End Module", "Module Program Sub Main() With """" Dim {|Rename:getHashCode|} As Integer = .GetHashCode Dim x = getHashCode Xor &H7F3E ' Introduce Local End With End Sub End Module", parseOptions:=Nothing) Await TestAsync( "Module Program Sub Main() With """" Dim x = [|.GetHashCode|] Xor &H7F3E ' Introduce Local End With End Sub End Module", "Module Program Sub Main() With """" Dim {|Rename:getHashCode|} As Integer = .GetHashCode Dim x = getHashCode Xor &H7F3E ' Introduce Local End With End Sub End Module", parseOptions:=GetScriptOptions()) End Function <WorkItem(545702, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545702")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestMissingInRefLocation() As Task Dim markup = " Module A Sub Main() Goo([|1|]) End Sub Sub Goo(ByRef x As Long) End Sub Sub Goo(x As String) End Sub End Module " Await TestMissingInRegularAndScriptAsync(markup) End Function <WorkItem(546139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546139")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestAcrossPartialTypes() As Task Await TestInRegularAndScriptAsync( "Partial Class C Sub goo1(Optional x As String = [|""HELLO""|]) End Sub End Class Partial Class C Sub goo3(Optional x As String = ""HELLO"") End Sub End Class", "Partial Class C Private Const {|Rename:V|} As String = ""HELLO"" Sub goo1(Optional x As String = V) End Sub End Class Partial Class C Sub goo3(Optional x As String = V) End Sub End Class", index:=1) End Function <WorkItem(544669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544669")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestFunctionBody1() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Dim a1 = Function(ByVal x) [|x!goo|] End Sub End Module", "Module Program Sub Main(args As String()) Dim a1 = Function(ByVal x) Dim {|Rename:goo|} As Object = x!goo Return goo End Function End Sub End Module") End Function <WorkItem(1065689, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1065689")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestTrailingTrivia() As Task Dim code = " Module M Sub Main() Dim a = 1 + [|2|] ' comment End Sub End Module " Dim expected = " Module M Private Const {|Rename:V|} As Integer = 2 Sub Main() Dim a = 1 + V ' comment End Sub End Module " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(546815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546815")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInIfStatement() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If [|True|] Then End If End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Private Const {|Rename:V|} As Boolean = True Sub Main(args As String()) If V Then End If End Sub End Module") End Function <WorkItem(830928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/830928")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestIntroduceLocalRemovesUnnecessaryCast() As Task Await TestInRegularAndScriptAsync( "Imports System.Collections.Generic Class C Private Shared Sub Main(args As String()) Dim hSet = New HashSet(Of String)() hSet.Add([|hSet.ToString()|]) End Sub End Class", "Imports System.Collections.Generic Class C Private Shared Sub Main(args As String()) Dim hSet = New HashSet(Of String)() Dim {|Rename:item|} As String = hSet.ToString() hSet.Add(item) End Sub End Class") End Function <WorkItem(546691, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546691")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestIntroLocalInSingleLineLambda() As Task Dim code = " Module Program Sub Main() Dim x = Function() [|Sub() End Sub|] End Sub End Module " Dim expected = " Module Program Sub Main() Dim {|Rename:p|} = Sub() End Sub Dim x = Function() p End Sub End Module " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(530720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530720")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestSingleToMultilineLambdaLineBreaks() As Task Dim code = " Module Program Sub Main() Dim a = Function(c) [|c!goo|] End Sub End Module " Dim expected = " Module Program Sub Main() Dim a = Function(c) Dim {|Rename:goo|} As Object = c!goo Return goo End Function End Sub End Module " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(531478, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531478")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestEscapeKeywordsIfNeeded1() As Task Dim code = " Imports System.Collections.Generic Imports System.Linq Module Program Sub Main() Take([|From x In """"|]) End Sub Sub Take(x) End Sub End Module " Dim expected = " Imports System.Collections.Generic Imports System.Linq Module Program Sub Main() Dim {|Rename:x1|} As IEnumerable(Of Char) = From x In """" [Take](x1) End Sub Sub Take(x) End Sub End Module " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(632327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632327")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInsertAfterPreprocessor1() As Task Dim code = " Public Class Index_vbhtml Public Sub Execute() #ExternalSource (""Home\Index.vbhtml"", 1) Dim i = [|1 + 2|] + 3 If True Then Dim j = 1 + 2 + 3 End If #End ExternalSource End Sub End Class " Dim expected = " Public Class Index_vbhtml Public Sub Execute() #ExternalSource (""Home\Index.vbhtml"", 1) Const {|Rename:V|} As Integer = 1 + 2 Dim i = V + 3 If True Then Dim j = 1 + 2 + 3 End If #End ExternalSource End Sub End Class " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(632327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632327")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInsertAfterPreprocessor2() As Task Dim code = " Public Class Index_vbhtml Public Sub Execute() #ExternalSource (""Home\Index.vbhtml"", 1) Dim i = 1 + 2 + 3 If True Then Dim j = [|1 + 2|] + 3 End If #End ExternalSource End Sub End Class " Dim expected = " Public Class Index_vbhtml Public Sub Execute() #ExternalSource (""Home\Index.vbhtml"", 1) Dim i = 1 + 2 + 3 If True Then Const {|Rename:V|} As Integer = 1 + 2 Dim j = V + 3 End If #End ExternalSource End Sub End Class " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(682683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682683")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestDontRemoveParenthesesIfOperatorPrecedenceWouldBeBroken() As Task Dim code = " Imports System Module Program Sub Main() Console.WriteLine(5 - ([|1|] + 2)) End Sub End Module " Dim expected = " Imports System Module Program Sub Main() Const {|Rename:V|} As Integer = 1 Console.WriteLine(5 - (V + 2)) End Sub End Module " Await TestInRegularAndScriptAsync(code, expected, index:=2) End Function <WorkItem(1022458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1022458")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestDontSimplifyParentUnlessEntireInnerNodeIsSelected() As Task Dim code = " Imports System Module Program Sub Main() Dim s = ""Text"" Dim x = 42 If ([|s.Length|].CompareTo(x) > 0 AndAlso s.Length.CompareTo(x) > 0) Then End If End Sub End Module " Dim expected = " Imports System Module Program Sub Main() Dim s = ""Text"" Dim x = 42 Dim {|Rename:length|} As Integer = s.Length If (length.CompareTo(x) > 0 AndAlso length.CompareTo(x) > 0) Then End If End Sub End Module " Await TestInRegularAndScriptAsync(code, expected, index:=1) End Function <WorkItem(939259, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939259")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestIntroduceLocalWithTriviaInMultiLineStatements() As Task Dim code = " Imports System Module Program Sub Main() Dim x = If(True, [|1|], ' TODO: Comment 2) End Sub End Module " Dim expected = " Imports System Module Program Sub Main() Const {|Rename:V|} As Integer = 1 Dim x = If(True, V, ' TODO: Comment 2) End Sub End Module " Await TestInRegularAndScriptAsync(code, expected, index:=3) End Function <WorkItem(909152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/909152")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestMissingOnNothingLiteral() As Task Await TestMissingInRegularAndScriptAsync( " Imports System Module Program Sub Main(args As String()) Main([|Nothing|]) M(Nothing) End Sub Sub M(i As Integer) End Sub End Module ") End Function <WorkItem(1130990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130990")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInParentConditionalAccessExpressions() As Task Dim code = " Imports System Class C Function F(Of T)(x As T) As T Dim y = [|F(New C)|]?.F(New C)?.F(New C) Return x End Function End Class " Dim expected = " Imports System Class C Function F(Of T)(x As T) As T Dim {|Rename:c|} As C = F(New C) Dim y = c?.F(New C)?.F(New C) Return x End Function End Class " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(1130990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130990")> <WorkItem(3110, "https://github.com/dotnet/roslyn/issues/3110")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestMissingAcrossMultipleParentConditionalAccessExpressions() As Task Await TestMissingInRegularAndScriptAsync( " Imports System Class C Function F(Of T)(x As T) As T Dim y = [|F(New C)?.F(New C)|]?.F(New C) Return x End Function End Class ") End Function <WorkItem(1130990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130990")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestMissingOnInvocationExpressionInParentConditionalAccessExpressions() As Task Await TestMissingInRegularAndScriptAsync( " Imports System Class C Function F(Of T)(x As T) As T Dim y = F(New C)?.[|F(New C)|]?.F(New C) Return x End Function End Class ") End Function <WorkItem(1130990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130990")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestMissingOnMemberBindingExpressionInParentConditionalAccessExpressions() As Task Await TestMissingInRegularAndScriptAsync( " Imports System Class C Sub F() Dim s as String = ""Text"" Dim l = s?.[|Length|] End Sub End Class ") End Function <WorkItem(2026, "https://github.com/dotnet/roslyn/issues/2026")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestReplaceAllFromInsideIfBlock() As Task Dim code = " Imports System Module DataTipInfoGetterModule Friend Function GetInfoAsync() As DebugDataTipInfo Dim expression As ExpressionSyntax = Nothing Dim curr = DirectCast(expression.Parent, ExpressionSyntax) If curr Is expression.Parent Then Return New DebugDataTipInfo([|expression.Parent|].Span) End If Return Nothing End Function End Module Friend Class TextSpan End Class Friend Class ExpressionSyntax Public Property Parent As ExpressionSyntax Public Property Span As TextSpan End Class Friend Class DebugDataTipInfo Public Sub New(span As Object) End Sub End Class " Dim expected = " Imports System Module DataTipInfoGetterModule Friend Function GetInfoAsync() As DebugDataTipInfo Dim expression As ExpressionSyntax = Nothing Dim {|Rename:parent|} As ExpressionSyntax = expression.Parent Dim curr = DirectCast(parent, ExpressionSyntax) If curr Is parent Then Return New DebugDataTipInfo(parent.Span) End If Return Nothing End Function End Module Friend Class TextSpan End Class Friend Class ExpressionSyntax Public Property Parent As ExpressionSyntax Public Property Span As TextSpan End Class Friend Class DebugDataTipInfo Public Sub New(span As Object) End Sub End Class " Await TestInRegularAndScriptAsync(code, expected, index:=1) End Function <WorkItem(1065661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1065661")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestIntroduceVariableTextDoesntSpanLines1() As Task Dim code = " Class C Sub M() Dim s = """" + [|""a b c""|] End Sub End Class" Await TestSmartTagTextAsync(code, String.Format(FeaturesResources.Introduce_local_constant_for_0, """a b c"""), New TestParameters(index:=2)) End Function <WorkItem(1065661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1065661")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestIntroduceVariableTextDoesntSpanLines2() As Task Dim code = " Class C Sub M() Dim s = """" + [|$""a b c""|] End Sub End Class" Await TestSmartTagTextAsync(code, String.Format(FeaturesResources.Introduce_local_for_0, "$""a b c""")) End Function <WorkItem(976, "https://github.com/dotnet/roslyn/issues/976")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNoConstantForInterpolatedStrings1() As Task Dim code = " Module Program Sub Main() Dim args As String() = Nothing Console.WriteLine([|$""{DateTime.Now.ToString()}Text{args(0)}""|]) End Sub End Module " Dim expected = " Module Program Sub Main() Dim args As String() = Nothing Dim {|Rename:v|} As String = $""{DateTime.Now.ToString()}Text{args(0)}"" Console.WriteLine(v) End Sub End Module " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(976, "https://github.com/dotnet/roslyn/issues/976")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNoConstantForInterpolatedStrings2() As Task Dim code = " Module Program Sub Main() Console.WriteLine([|$""Text{{s}}""|]) Console.WriteLine($""Text{{s}}"") End Sub End Module " Dim expected = " Module Program Sub Main() Dim {|Rename:v|} As String = $""Text{{s}}"" Console.WriteLine(v) Console.WriteLine(v) End Sub End Module " Await TestInRegularAndScriptAsync(code, expected, index:=1) End Function <WorkItem(3147, "https://github.com/dotnet/roslyn/issues/3147")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestHandleFormattableStringTargetTyping1() As Task Const code = " Imports System " & FormattableStringType & " Namespace N Class C Public Sub M() Dim f = FormattableString.Invariant([|$""""|]) End Sub End Class End Namespace" Const expected = " Imports System " & FormattableStringType & " Namespace N Class C Public Sub M() Dim {|Rename:formattable|} As FormattableString = $"""" Dim f = FormattableString.Invariant(formattable) End Sub End Class End Namespace" Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(936, "https://github.com/dotnet/roslyn/issues/936")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInAutoPropertyInitializerEqualsClause() As Task Dim code = " Imports System Class C Property Name As String = [|""Roslyn""|] End Class " Dim expected = " Imports System Class C Private Const {|Rename:V|} As String = ""Roslyn"" Property Name As String = V End Class " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(936, "https://github.com/dotnet/roslyn/issues/936")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInAutoPropertyWithCollectionInitializerAfterEqualsClause() As Task Dim code = " Imports System Class C Property Grades As Integer() = [|{90, 73}|] End Class " Dim expected = " Imports System Class C Private Shared ReadOnly {|Rename:p|} As Integer() = {90, 73} Property Grades As Integer() = p End Class " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(936, "https://github.com/dotnet/roslyn/issues/936")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInAutoPropertyInitializerAsClause() As Task Dim code = " Imports System Class C Public Property Items As New List(Of String) From {[|""M""|], ""T"", ""W""} End Class " Dim expected = " Imports System Class C Private Const {|Rename:V|} As String = ""M"" Public Property Items As New List(Of String) From {V, ""T"", ""W""} End Class " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(936, "https://github.com/dotnet/roslyn/issues/936")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInAutoPropertyObjectCreationExpressionWithinAsClause() As Task Dim code = " Imports System Class C Property Orders As New List(Of Object)([|500|]) End Class " Dim expected = " Imports System Class C Private Const {|Rename:V|} As Integer = 500 Property Orders As New List(Of Object)(V) End Class " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(11777, "https://github.com/dotnet/roslyn/issues/11777")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestGenerateLocalConflictingName1() As Task Await TestInRegularAndScriptAsync( "class Program class MySpan public Start as integer end class sub Method(span as MySpan) dim pos as integer = span.Start while pos < [|span.Start|] dim start as integer = pos end while end sub end class", "class Program class MySpan public Start as integer end class sub Method(span as MySpan) dim pos as integer = span.Start Dim {|Rename:start1|} As Integer = span.Start while pos < start1 dim start as integer = pos end while end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TupleWithInferredName_LeaveExplicitName() As Task Dim code = " Class C Shared Dim y As Integer = 2 Sub M() Dim a As Integer = 1 Dim t = (a, x:=[|C.y|]) End Sub End Class " Dim expected = " Class C Shared Dim y As Integer = 2 Sub M() Dim a As Integer = 1 Dim {|Rename:y1|} As Integer = C.y Dim t = (a, x:=y1) End Sub End Class " Await TestAsync(code, expected, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TupleWithInferredName_InferredNameBecomesExplicit() As Task Dim code = " Class C Shared Dim y As Integer = 2 Sub M() Dim a As Integer = 1 Dim t = (a, [|C.y|]) End Sub End Class " Dim expected = " Class C Shared Dim y As Integer = 2 Sub M() Dim a As Integer = 1 Dim {|Rename:y1|} As Integer = C.y Dim t = (a, y:=y1) End Sub End Class " Await TestAsync(code, expected, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TupleWithInferredName_AllOccurrences() As Task Dim code = " Class C Shared Dim y As Integer = 2 Sub M() Dim a As Integer = 1 Dim t = (a, [|C.y|]) Dim t2 = (C.y, a) End Sub End Class " Dim expected = " Class C Shared Dim y As Integer = 2 Sub M() Dim a As Integer = 1 Dim {|Rename:y1|} As Integer = C.y Dim t = (a, y:=y1) Dim t2 = (y:=y1, a) End Sub End Class " Await TestAsync(code, expected, index:=1, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TupleWithInferredName_NoDuplicateNames() As Task Dim code = " Class C Shared Dim y As Integer = 2 Sub M() Dim t = (C.y, [|C.y|]) End Sub End Class " Dim expected = " Class C Shared Dim y As Integer = 2 Sub M() Dim {|Rename:y1|} As Integer = C.y Dim t = (y1, y1) End Sub End Class " Await TestInRegularAndScriptAsync(code, expected, index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TupleWithInferredName_NoReservedNames() As Task Dim code = " Class C Shared Dim rest As Integer = 2 Sub M() Dim a As Integer = 1 Dim t = (a, [|C.rest|]) End Sub End Class " Dim expected = " Class C Shared Dim rest As Integer = 2 Sub M() Dim a As Integer = 1 Dim {|Rename:rest1|} As Integer = C.rest Dim t = (a, rest1) End Sub End Class " Await TestAsync(code, expected, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function AnonymousTypeWithInferredName_LeaveExplicitName() As Task Dim code = " Class C Shared Dim y As Integer = 2 Sub M() Dim a As Integer = 1 Dim t = New With {a, [|C.y|]} End Sub End Class " Dim expected = " Class C Shared Dim y As Integer = 2 Sub M() Dim a As Integer = 1 Dim {|Rename:y1|} As Integer = C.y Dim t = New With {a, .y = y1} End Sub End Class " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(2423, "https://github.com/dotnet/roslyn/issues/2423")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestPickNameBasedOnArgument1() As Task Await TestInRegularAndScriptAsync( "class C public sub new(a as string, b as string) dim c = new TextSpan([|integer.Parse(a)|], integer.Parse(b)) end sub end class structure TextSpan public sub new(start as integer, length as integer) end sub end structure", "class C public sub new(a as string, b as string) Dim {|Rename:start|} As Integer = integer.Parse(a) dim c = new TextSpan(start, integer.Parse(b)) end sub end class structure TextSpan public sub new(start as integer, length as integer) end sub end structure") End Function <WorkItem(2423, "https://github.com/dotnet/roslyn/issues/2423")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestPickNameBasedOnArgument2() As Task Await TestInRegularAndScriptAsync( "class C public sub new(a as string, b as string) dim c = new TextSpan(integer.Parse(a), [|integer.Parse(b)|]) end sub end class structure TextSpan public sub new(start as integer, length as integer) end sub end structure", "class C public sub new(a as string, b as string) Dim {|Rename:length|} As Integer = integer.Parse(b) dim c = new TextSpan(integer.Parse(a), length) end sub end class structure TextSpan public sub new(start as integer, length as integer) end sub end structure") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(10123, "https://github.com/dotnet/roslyn/issues/10123")> Public Async Function TestSimpleParameterName() As Task Dim source = "Module Program Sub Main(x As Integer) Goo([|x|]) End Sub End Module" Dim expected = "Module Program Sub Main(x As Integer) Dim {|Rename:x1|} As Integer = x Goo(x1) End Sub End Module" Await TestInRegularAndScriptAsync(source, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(10123, "https://github.com/dotnet/roslyn/issues/10123")> Public Async Function TestSimpleParameterName_EmptySelection() As Task Dim source = "Module Program Sub Main(x As Integer) Goo([||]x) End Sub End Module" Await TestMissingAsync(source) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(10123, "https://github.com/dotnet/roslyn/issues/10123")> Public Async Function TestFieldName_QualifiedWithMe() As Task Dim source = "Module Program Dim x As Integer Sub Main() Goo([|x|]) End Sub End Module" Dim expected = "Module Program Dim x As Integer Sub Main() Dim {|Rename:x1|} As Integer = x Goo(x1) End Sub End Module" Await TestInRegularAndScriptAsync(source, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(10123, "https://github.com/dotnet/roslyn/issues/10123")> Public Async Function TestFieldName_QualifiedWithType() As Task Dim source = "Module Program Shared Dim x As Integer Sub Main() Goo([|Program.x|]) End Sub End Module" Dim expected = "Module Program Shared Dim x As Integer Sub Main() Dim {|Rename:x1|} As Integer = Program.x Goo(x1) End Sub End Module" Await TestInRegularAndScriptAsync(source, expected) End Function <WorkItem(21373, "https://github.com/dotnet/roslyn/issues/21373")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInAttribute() As Task Dim code = " Class C Public Property Foo() <Example([|3 + 3|])> Public Property Bar() End Class " Dim expected = " Class C Private Const {|Rename:V|} As Integer = 3 + 3 Public Property Foo() <Example(V)> Public Property Bar() End Class " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(28266, "https://github.com/dotnet/roslyn/issues/28266")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestCaretAtEndOfExpression1() As Task Await TestInRegularAndScriptAsync( "class C sub Goo() Bar(1[||], 2) end sub end class", "class C Private Const {|Rename:V|} As Integer = 1 sub Goo() Bar(V, 2) end sub end class") End Function <WorkItem(28266, "https://github.com/dotnet/roslyn/issues/28266")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestCaretAtEndOfExpression2() As Task Await TestInRegularAndScriptAsync( "class C sub Goo() Bar(1, 2[||]) end sub end class", "class C Private Const {|Rename:V|} As Integer = 2 sub Goo() Bar(1, V) end sub end class") End Function <WorkItem(28266, "https://github.com/dotnet/roslyn/issues/28266")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestCaretAtEndOfExpression3() As Task Await TestInRegularAndScriptAsync( "class C sub Goo() Bar(1, (2[||])) end sub end class", "class C Private Const {|Rename:V|} As Integer = (2) sub Goo() Bar(1, V) end sub end class") End Function <WorkItem(28266, "https://github.com/dotnet/roslyn/issues/28266")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestCaretAtEndOfExpression4() As Task Await TestInRegularAndScriptAsync( "class C sub Goo() Bar(1, Bar(2[||])) end sub end class", "class C Private Const {|Rename:V|} As Integer = 2 sub Goo() Bar(1, Bar(V)) end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(27949, "https://github.com/dotnet/roslyn/issues/27949")> Public Async Function TestWhitespaceSpanInAssignment() As Task Await TestMissingAsync(" Class C Dim x As Integer = [| |] 0 End Class ") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(28665, "https://github.com/dotnet/roslyn/issues/28665")> Public Async Function TestWhitespaceSpanInAttribute() As Task Await TestMissingAsync(" Class C <Example( [| |] )> Public Function Foo() End Function End Class ") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(30207, "https://github.com/dotnet/roslyn/issues/30207")> Public Async Function TestExplicitRecursiveInstanceMemberAccess_ForAllOccurrences() As Task Dim source = " Class C Dim c As C Sub Foo() Dim y = [|c|].c.c End Sub End Class " Dim expected = " Class C Dim c As C Sub Foo() Dim {|Rename:c1|} As C = c Dim y = c1.c.c End Sub End Class " Await TestInRegularAndScriptAsync(source, expected, index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(30207, "https://github.com/dotnet/roslyn/issues/30207")> Public Async Function TestImplicitRecursiveInstanceMemberAccess_ForAllOccurrences() As Task Dim source = " Class C Dim c As C Sub Foo() Dim y = [|Me.c|].c.c End Sub End Class " Dim expected = " Class C Dim c As C Sub Foo() Dim {|Rename:c1|} As C = Me.c Dim y = c1.c.c End Sub End Class " Await TestInRegularAndScriptAsync(source, expected, index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(30207, "https://github.com/dotnet/roslyn/issues/30207")> Public Async Function TestExpressionOfUndeclaredType() As Task Dim source = " Class C Sub Test Dim array As A() = [|A|].Bar() End Sub End Class" Await TestMissingAsync(source) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(47772, "https://github.com/dotnet/roslyn/issues/47772")> Public Async Function DoNotIntroduceConstantForConstant_Local() As Task Dim source = " Class C Sub Test Const i As Integer = [|10|] End Sub End Class " Await TestMissingAsync(source) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(47772, "https://github.com/dotnet/roslyn/issues/47772")> Public Async Function DoNotIntroduceConstantForConstant_Member() As Task Dim source = " Class C Const i As Integer = [|10|] End Class " Await TestMissingAsync(source) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(47772, "https://github.com/dotnet/roslyn/issues/47772")> Public Async Function DoNotIntroduceConstantForConstant_Parentheses() As Task Dim source = " Class C Const i As Integer = ([|10|]) End Class " Await TestMissingAsync(source) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(47772, "https://github.com/dotnet/roslyn/issues/47772")> Public Async Function DoNotIntroduceConstantForConstant_NotForSubExpression() As Task Dim source = " Class C Sub Test Const i As Integer = [|10|] + 10 End Sub End Class " Dim expected = " Class C Sub Test Const {|Rename:V|} As Integer = 10 Const i As Integer = V + 10 End Sub End Class " Await TestInRegularAndScriptAsync(source, expected, index:=2) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.IntroduceVariable Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings.IntroduceVariable Public Class IntroduceVariableTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New IntroduceVariableCodeRefactoringProvider() End Function Protected Overrides Function MassageActions(actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction) Return GetNestedActions(actions) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function Test1() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Console.WriteLine([|1 + 1|]) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Const {|Rename:Value|} As Integer = 1 + 1 Console.WriteLine(Value) End Sub End Module", index:=2) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function Test2() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Console.WriteLine([|1 + 1|]) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Const {|Rename:Value|} As Integer = 1 + 1 Console.WriteLine(Value) End Sub End Module", index:=3) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInSingleLineIfExpression1() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If goo([|1 + 1|]) Then bar(1 + 1) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Const {|Rename:V|} As Integer = 1 + 1 If goo(V) Then bar(1 + 1) End Sub End Module", index:=2) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInSingleLineIfExpression2() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If goo([|1 + 1|]) Then bar(1 + 1) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Const {|Rename:V|} As Integer = 1 + 1 If goo(V) Then bar(V) End Sub End Module", index:=3) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInSingleLineIfStatement1() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If goo(1 + 1) Then bar([|1 + 1|]) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If goo(1 + 1) Then Const {|Rename:V|} As Integer = 1 + 1 bar(V) End If End Sub End Module", index:=2) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInSingleLineIfStatement2() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If goo(1 + 1) Then bar([|1 + 1|]) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Const {|Rename:V|} As Integer = 1 + 1 If goo(V) Then bar(V) End Sub End Module", index:=3) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNoIntroduceFieldOnMethodTypeParameter() As Task Dim source = "Module Program Sub Main(Of T)() Goo([|CType(2.ToString(), T)|]) End Sub End Module" Await TestExactActionSetOfferedAsync( source, expectedActionSet:={ String.Format(FeaturesResources.Introduce_local_for_0, "CType(2.ToString(), T)"), String.Format(FeaturesResources.Introduce_local_for_all_occurrences_of_0, "CType(2.ToString(), T)")}) ' Verifies "Introduce field ..." is missing End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNoIntroduceFieldOnMethodParameter() As Task Dim source = "Module Program Sub Main(x As Integer) Goo([|x.ToString()|]) End Sub End Module" Await TestExactActionSetOfferedAsync( source, expectedActionSet:={ String.Format(FeaturesResources.Introduce_local_for_0, "x.ToString()"), String.Format(FeaturesResources.Introduce_local_for_all_occurrences_of_0, "x.ToString()")}) ' Verifies "Introduce field ..." is missing End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNoRefactoringOnExpressionInAssignmentStatement() As Task Dim source = "Module Program Sub Main(x As Integer) Dim r = [|x.ToString()|] End Sub End Module" Await TestMissingInRegularAndScriptAsync(source) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestLocalGeneratedInInnerBlock1() As Task Dim source = "Module Program Sub Main(x As Integer) If True Then Goo([|x.ToString()|]) End If End Sub End Module" Dim expected = "Module Program Sub Main(x As Integer) If True Then Dim {|Rename:v|} As String = x.ToString() Goo(v) End If End Sub End Module" Await TestInRegularAndScriptAsync(source, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestLocalGeneratedInInnerBlock2() As Task Dim source = "Module Program Sub Main(x As Integer) If True Then Goo([|x.ToString()|]) End If End Sub End Module" Dim expected = "Module Program Sub Main(x As Integer) If True Then Dim {|Rename:v|} As String = x.ToString() Goo(v) End If End Sub End Module" Await TestInRegularAndScriptAsync(source, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestLocalFromSingleExpressionInAnonType() As Task Dim source = "Module Program Sub Main(x As Integer) Dim f1 = New With {.SomeString = [|x.ToString()|]} End Sub End Module" Dim expected = "Module Program Sub Main(x As Integer) Dim {|Rename:v|} As String = x.ToString() Dim f1 = New With {.SomeString = v} End Sub End Module" Await TestInRegularAndScriptAsync(source, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestLocalFromMultipleExpressionsInAnonType() As Task Dim source = "Module Program Sub Main(x As Integer) Dim f1 = New With {.SomeString = [|x.ToString()|], .SomeOtherString = x.ToString()} Dim f2 = New With {.SomeString = x.ToString(), .SomeOtherString = x.ToString()} Dim str As String = x.ToString() End Sub End Module" Dim expected = "Module Program Sub Main(x As Integer) Dim {|Rename:v|} As String = x.ToString() Dim f1 = New With {.SomeString = v, .SomeOtherString = v} Dim f2 = New With {.SomeString = v, .SomeOtherString = v} Dim str As String = v End Sub End Module" Await TestInRegularAndScriptAsync(source, expected, index:=1) End Function <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestLocalFromInferredFieldInitializer() As Task Dim source = "Imports System Class C Sub M() Dim a As New With {[|Environment.TickCount|]} End Sub End Class" Dim expected = "Imports System Class C Sub M() Dim {|Rename:tickCount|} As Integer = Environment.TickCount Dim a As New With {tickCount} End Sub End Class" Await TestInRegularAndScriptAsync(source, expected, index:=1) End Function <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestLocalFromYieldStatement() As Task Dim source = "Imports System Class C Iterator Function F() As IEnumerable(Of Integer) Yield [|Environment.TickCount * 2|] End Function End Class" Dim expected = "Imports System Class C Iterator Function F() As IEnumerable(Of Integer) Dim {|Rename:v|} As Integer = Environment.TickCount * 2 Yield v End Function End Class" Await TestInRegularAndScriptAsync(source, expected, index:=1) End Function <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestLocalFromWhileStatement() As Task Dim source = "Class C Sub M() Dim x = 1 While [|x = 1|] End While End Sub End Class" Dim expected = "Class C Sub M() Dim x = 1 Dim {|Rename:v|} As Boolean = x = 1 While v End While End Sub End Class" Await TestInRegularAndScriptAsync(source, expected, index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestLocalFromSingleExpressionInObjectInitializer() As Task Dim source = "Module Program Structure GooStruct Dim GooMember1 As String End Structure Sub Main(x As Integer) Dim f1 = New GooStruct With {.GooMember1 = [|""t"" + ""test""|]} End Sub End Module" Dim expected = "Module Program Structure GooStruct Dim GooMember1 As String End Structure Sub Main(x As Integer) Const {|Rename:V|} As String = ""t"" + ""test"" Dim f1 = New GooStruct With {.GooMember1 = V} End Sub End Module" Await TestInRegularAndScriptAsync(source, expected, index:=2) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestLocalFromMultipleExpressionsInObjectInitializer() As Task Dim code = " Module Program Structure GooStruct Dim GooMember1 As String Dim GooMember2 As String End Structure Sub Main(x As Integer) Dim f1 = New GooStruct With {.GooMember1 = [|""t"" + ""test""|], .GooMember2 = ""t"" + ""test""} Dim f2 = New GooStruct With {.GooMember1 = ""t"" + ""test"", .GooMember2 = ""t"" + ""test""} Dim str As String = ""t"" + ""test"" End Sub End Module " Dim expected = " Module Program Structure GooStruct Dim GooMember1 As String Dim GooMember2 As String End Structure Sub Main(x As Integer) Const {|Rename:V|} As String = ""t"" + ""test"" Dim f1 = New GooStruct With {.GooMember1 = V, .GooMember2 = V} Dim f2 = New GooStruct With {.GooMember1 = V, .GooMember2 = V} Dim str As String = V End Sub End Module " Await TestInRegularAndScriptAsync(code, expected, index:=3) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestFieldFromMultipleExpressionsInAnonType() As Task Dim source = "Class Program Dim q = New With {.str = [|""t"" + ""test""|]} Dim r = New With {.str = ""t"" + ""test""} Sub Goo() Dim x = ""t"" + ""test"" End Sub End Class" Dim expected = "Class Program Private Const {|Rename:V|} As String = ""t"" + ""test"" Dim q = New With {.str = V} Dim r = New With {.str = V} Sub Goo() Dim x = V End Sub End Class" Await TestInRegularAndScriptAsync(source, expected, index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestPrivateFieldFromExpressionInField() As Task Dim source = "Class Program Dim x = Goo([|2 + 2|]) End Class" Dim expected = "Class Program Private Const {|Rename:V|} As Integer = 2 + 2 Dim x = Goo(V) End Class" Await TestInRegularAndScriptAsync(source, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNoLocalFromExpressionInField() As Task Dim source = "Class Program Dim x = Goo([|2 + 2|]) End Class" Await TestExactActionSetOfferedAsync(source, {String.Format(FeaturesResources.Introduce_constant_for_0, "2 + 2"), String.Format(FeaturesResources.Introduce_constant_for_all_occurrences_of_0, "2 + 2")}) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestSharedModifierAbsentInGeneratedModuleFields() As Task Dim source = "Module Program Private ReadOnly y As Integer = 1 Dim x = Goo([|2 + y|]) End Module" Dim expected = "Module Program Private ReadOnly y As Integer = 1 Private ReadOnly {|Rename:v|} As Integer = 2 + y Dim x = Goo(v) End Module" Await TestInRegularAndScriptAsync(source, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestSingleLocalInsertLocation() As Task Dim source = "Class Program Sub Method1() Dim v1 As String = ""TEST"" Dim v2 As Integer = 2 + 2 Goo([|2 + 2|]) End Sub End Class" Dim expected = "Class Program Sub Method1() Dim v1 As String = ""TEST"" Dim v2 As Integer = 2 + 2 Const {|Rename:V|} As Integer = 2 + 2 Goo(V) End Sub End Class" Await TestInRegularAndScriptAsync(source, expected, index:=2) End Function #Region "Parameter context" <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestConstantFieldGenerationForParameterSingleOccurrence() As Task ' This is incorrect: the field type should be Integer, not Object Dim source = "Module Module1 Sub Goo(Optional x As Integer = [|42|]) End Sub End Module" Dim expected = "Module Module1 Private Const {|Rename:V|} As Integer = 42 Sub Goo(Optional x As Integer = V) End Sub End Module" Await TestInRegularAndScriptAsync(source, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestConstantFieldGenerationForParameterAllOccurrences() As Task ' This is incorrect: the field type should be Integer, not Object Dim source = "Module Module1 Sub Bar(Optional x As Integer = 42) End Sub Sub Goo(Optional x As Integer = [|42|]) End Sub End Module" Dim expected = "Module Module1 Private Const {|Rename:V|} As Integer = 42 Sub Bar(Optional x As Integer = V) End Sub Sub Goo(Optional x As Integer = V) End Sub End Module" Await TestInRegularAndScriptAsync(source, expected, index:=1) End Function #End Region <WorkItem(540269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540269")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestReplaceDottedExpression() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Console.WriteLine([|Goo.someVariable|]) Console.WriteLine(Goo.someVariable) End Sub End Module Friend Class Goo Shared Public someVariable As Integer End Class", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim {|Rename:someVariable|} As Integer = Goo.someVariable Console.WriteLine(someVariable) Console.WriteLine(someVariable) End Sub End Module Friend Class Goo Shared Public someVariable As Integer End Class", index:=1) End Function <WorkItem(540457, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540457")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestReplaceSingleLineIfWithMultiLine1() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Goo([|2 + 2|]) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Const {|Rename:V|} As Integer = 2 + 2 Goo(V) End If End Sub End Module", index:=2) End Function <WorkItem(540457, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540457")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestReplaceSingleLineIfWithMultiLine2() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Goo([|1 + 1|]) Else Bar(1 + 1) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Const {|Rename:V|} As Integer = 1 + 1 Goo(V) Else Bar(1 + 1) End If End Sub End Module", index:=2) End Function <WorkItem(540457, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540457")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestReplaceSingleLineIfWithMultiLine3() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Goo([|1 + 1|]) Else Bar(1 + 1) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Const {|Rename:V|} As Integer = 1 + 1 If True Then Goo(V) Else Bar(V) End Sub End Module", index:=3) End Function <WorkItem(540457, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540457")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestReplaceSingleLineIfWithMultiLine4() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Goo(1 + 1) Else Bar([|1 + 1|]) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Goo(1 + 1) Else Const {|Rename:V|} As Integer = 1 + 1 Bar(V) End If End Sub End Module", index:=2) End Function <WorkItem(540468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540468")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestCantExtractMethodTypeParameterToFieldCount() As Task Await TestActionCountAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(Of T)(x As Integer) Goo([|CType(2.ToString(), T)|]) End Sub End Module", count:=2) End Function <WorkItem(540468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540468")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestCantExtractMethodTypeParameterToField() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(Of T)(x As Integer) Goo([|CType(2.ToString(), T)|]) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(Of T)(x As Integer) Dim {|Rename:t|} As T = CType(2.ToString(), T) Goo(t) End Sub End Module") End Function <WorkItem(540489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540489")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestOnlyFieldsInsideConstructorInitializer() As Task Await TestActionCountAsync( "Class Goo Sub New() Me.New([|2 + 2|]) End Sub Sub New(v As Integer) End Sub End Class", count:=2) Await TestInRegularAndScriptAsync( "Class Goo Sub New() Me.New([|2 + 2|]) End Sub Sub New(v As Integer) End Sub End Class", "Class Goo Private Const {|Rename:V|} As Integer = 2 + 2 Sub New() Me.New(V) End Sub Sub New(v As Integer) End Sub End Class") End Function <WorkItem(540485, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540485")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestIntroduceLocalForConstantExpression() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Dim s As String() = New String([|10|]) {} End Sub End Module", "Module Program Sub Main(args As String()) Const {|Rename:V|} As Integer = 10 Dim s As String() = New String(V) {} End Sub End Module", index:=3) End Function <WorkItem(1065689, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1065689")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestIntroduceLocalForConstantExpressionWithTrailingTrivia() As Task Await TestInRegularAndScriptAsync( " Class C Private Function GetX() As Object Return [|""c d "" + ' comment 1 ""a b"" ' comment 2|] End Function End Class ", " Class C Private Function GetX() As Object Const {|Rename:V|} As String = ""c d "" + ' comment 1 ""a b"" Return V ' comment 2 End Function End Class ", index:=3) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestIntroduceFieldWithTrailingTrivia() As Task Await TestInRegularAndScriptAsync( " Class C Private Sub S() Dim x = 1 + [|2|] ' comment End Sub End Class ", " Class C Private Const {|Rename:V|} As Integer = 2 Private Sub S() Dim x = 1 + V ' comment End Sub End Class ", index:=1) End Function <WorkItem(540487, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540487")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestFormattingForPartialExpression() As Task Dim code = " Module Program Sub Main() Dim i = [|1 + 2|] + 3 End Sub End Module " Dim expected = " Module Program Sub Main() Const {|Rename:V|} As Integer = 1 + 2 Dim i = V + 3 End Sub End Module " Await TestInRegularAndScriptAsync(code, expected, index:=2) End Function <WorkItem(540491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540491")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInAttribute1() As Task Await TestInRegularAndScriptAsync( "<Attr([|2 + 2|])> Class Goo End Class Friend Class AttrAttribute Inherits Attribute End Class", "<Attr(Goo.V)> Class Goo Friend Const {|Rename:V|} As Integer = 2 + 2 End Class Friend Class AttrAttribute Inherits Attribute End Class") End Function <WorkItem(540490, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540490")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInMyClassNew() As Task Await TestInRegularAndScriptAsync( "Class Goo Sub New() MyClass.New([|42|]) End Sub Sub New(x As Integer) End Sub End Class", "Class Goo Private Const {|Rename:X|} As Integer = 42 Sub New() MyClass.New(X) End Sub Sub New(x As Integer) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestSingleToMultiLineIf1() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Goo([|2 + 2|]) Else Bar(2 + 2) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Const {|Rename:V|} As Integer = 2 + 2 Goo(V) Else Bar(2 + 2) End If End Sub End Module", index:=2) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestSingleToMultiLineIf2() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Goo([|2 + 2|]) Else Bar(2 + 2) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Const {|Rename:V|} As Integer = 2 + 2 If True Then Goo(V) Else Bar(V) End Sub End Module", index:=3) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestSingleToMultiLineIf3() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Goo(2 + 2) Else Bar([|2 + 2|]) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Goo(2 + 2) Else Const {|Rename:V|} As Integer = 2 + 2 Bar(V) End If End Sub End Module", index:=2) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestSingleToMultiLineIf4() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Goo(2 + 2) Else Bar([|2 + 2|]) End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Const {|Rename:V|} As Integer = 2 + 2 If True Then Goo(V) Else Bar(V) End Sub End Module", index:=3) End Function <WorkItem(541604, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541604")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestAttribute() As Task Await TestInRegularAndScriptAsync( "<Attr([|2 + 2|])> Class Goo End Class Friend Class AttrAttribute Inherits System.Attribute End Class", "<Attr(Goo.V)> Class Goo Friend Const {|Rename:V|} As Integer = 2 + 2 End Class Friend Class AttrAttribute Inherits System.Attribute End Class") End Function <WorkItem(542092, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542092")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestRangeArgumentLowerBound1() As Task Await TestMissingInRegularAndScriptAsync("Module M Sub Main() Dim x() As Integer ReDim x([|0|] To 5) End Sub End Module") End Function <WorkItem(542092, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542092")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestRangeArgumentLowerBound2() As Task Dim code = " Module M Sub Main() Dim x() As Integer ReDim x(0 To 5) Dim a = [|0|] + 1 End Sub End Module " Dim expected = " Module M Sub Main() Dim x() As Integer ReDim x(0 To 5) Const {|Rename:V|} As Integer = 0 Dim a = V + 1 End Sub End Module " Await TestInRegularAndScriptAsync(code, expected, index:=3) End Function <WorkItem(543029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543029"), WorkItem(542963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542963"), WorkItem(542295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542295")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestUntypedExpression() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim q As Object If True Then q = [|Sub() End Sub|] End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim q As Object If True Then Dim {|Rename:p|} As Object = Sub() End Sub q = p End If End Sub End Module") End Function <WorkItem(542374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542374")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestFieldConstantInAttribute1() As Task Await TestInRegularAndScriptAsync( "<Goo(2 + 3 + 4)> Module Program Dim x = [|2 + 3|] + 4 End Module Friend Class GooAttribute Inherits Attribute Sub New(x As Integer) End Sub End Class", "<Goo(2 + 3 + 4)> Module Program Private Const {|Rename:V|} As Integer = 2 + 3 Dim x = V + 4 End Module Friend Class GooAttribute Inherits Attribute Sub New(x As Integer) End Sub End Class") End Function <WorkItem(542374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542374")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestFieldConstantInAttribute2() As Task Await TestAsync( "<Goo(2 + 3 + 4)> Module Program Dim x = [|2 + 3|] + 4 End Module Friend Class GooAttribute Inherits Attribute Sub New(x As Integer) End Sub End Class", "<Goo(V + 4)> Module Program Friend Const {|Rename:V|} As Integer = 2 + 3 Dim x = V + 4 End Module Friend Class GooAttribute Inherits Attribute Sub New(x As Integer) End Sub End Class", index:=1, parseOptions:=Nothing) End Function <WorkItem(542783, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542783")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestMissingOnAttributeName() As Task Await TestMissingInRegularAndScriptAsync( "<[|Obsolete|]> Class C End Class") End Function <WorkItem(542811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542811")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestMissingOnFilterClause() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub Main() Try Catch ex As Exception When [|+|] End Try End Sub End Module") End Function <WorkItem(542906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542906")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNoIntroduceLocalInAttribute() As Task Dim input = "Module Program \n <Obsolete([|""""|])> \n Sub Main(args As String()) \n End Sub \n End Module" Await TestActionCountAsync( NewLines(input), count:=2) Await TestInRegularAndScriptAsync( NewLines(input), "Module Program Private Const {|Rename:V|} As String = """" <Obsolete(V)> Sub Main(args As String()) End Sub End Module") End Function <WorkItem(542947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542947")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNotOnMyBase() As Task Await TestMissingInRegularAndScriptAsync( "Class c1 Public res As String Sub Goo() res = ""1"" End Sub End Class Class c2 Inherits c1 Sub scen1() [|MyBase|].Goo() End Sub End Class") End Function <WorkItem(541966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541966")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNestedMultiLineIf1() As Task Dim code = " Imports System Module Program Sub Main() If True Then If True Then Console.WriteLine([|1|]) Else Console.WriteLine(2) Else Console.WriteLine(3) End Sub End Module " Dim expected = " Imports System Module Program Sub Main() If True Then If True Then Const {|Rename:Value|} As Integer = 1 Console.WriteLine(Value) Else Console.WriteLine(2) End If Else Console.WriteLine(3) End If End Sub End Module " Await TestInRegularAndScriptAsync(code, expected, index:=3) End Function <WorkItem(541966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541966")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNestedMultiLineIf2() As Task Dim code = " Imports System Module Program Sub Main() If True Then If True Then Console.WriteLine(1) Else Console.WriteLine([|2|]) Else Console.WriteLine(3) End Sub End Module " Dim expected = " Imports System Module Program Sub Main() If True Then If True Then Console.WriteLine(1) Else Const {|Rename:Value|} As Integer = 2 Console.WriteLine(Value) End If Else Console.WriteLine(3) End If End Sub End Module " Await TestInRegularAndScriptAsync(code, expected, index:=3) End Function <WorkItem(541966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541966")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNestedMultiLineIf3() As Task Dim code = " Imports System Module Program Sub Main() If True Then If True Then Console.WriteLine(1) Else Console.WriteLine(2) Else Console.WriteLine([|3|]) End Sub End Module " Dim expected = " Imports System Module Program Sub Main() If True Then If True Then Console.WriteLine(1) Else Console.WriteLine(2) Else Const {|Rename:Value|} As Integer = 3 Console.WriteLine(Value) End If End Sub End Module " Await TestInRegularAndScriptAsync(code, expected, index:=3) End Function <WorkItem(543273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543273")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestSingleLineLambda1() As Task Await TestInRegularAndScriptAsync( "Imports System Module Program Sub Main Dim a = Sub(x As Integer) Console.WriteLine([|x + 1|]) ' Introduce local End Sub End Module", "Imports System Module Program Sub Main Dim a = Sub(x As Integer) Dim {|Rename:value|} As Integer = x + 1 Console.WriteLine(value) End Sub ' Introduce local End Sub End Module") End Function <WorkItem(543273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543273")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestSingleLineLambda2() As Task Await TestInRegularAndScriptAsync( "Imports System Module Program Sub Main Dim a = Sub(x As Integer) If True Then Console.WriteLine([|x + 1|]) Else Console.WriteLine() End Sub End Module", "Imports System Module Program Sub Main Dim a = Sub(x As Integer) If True Then Dim {|Rename:value|} As Integer = x + 1 Console.WriteLine(value) Else Console.WriteLine() End If End Sub End Sub End Module") End Function <WorkItem(543273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543273")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestSingleLineLambda3() As Task Await TestInRegularAndScriptAsync( "Imports System Module Program Sub Main Dim a = Sub(x As Integer) If True Then Console.WriteLine() Else Console.WriteLine([|x + 1|]) End Sub End Module", "Imports System Module Program Sub Main Dim a = Sub(x As Integer) If True Then Console.WriteLine() Else Dim {|Rename:value|} As Integer = x + 1 Console.WriteLine(value) End If End Sub End Sub End Module") End Function <WorkItem(543273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543273")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestSingleLineLambda4() As Task Await TestInRegularAndScriptAsync( "Imports System Module Program Sub Main Dim a = Sub(x As Integer) If True Then Console.WriteLine([|x + 1|]) Else Console.WriteLine(x + 1) End Sub End Module", "Imports System Module Program Sub Main Dim a = Sub(x As Integer) Dim {|Rename:value|} As Integer = x + 1 If True Then Console.WriteLine(value) Else Console.WriteLine(value) End Sub End Sub End Module", index:=1) End Function <WorkItem(543299, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543299")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestSingleLineLambda5() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Dim query = Sub(a) a = New With {Key .Key = Function(ByVal arg As Integer) As Integer Return arg End Function}.Key.Invoke([|a Or a|]) End Sub End Module", "Module Program Sub Main(args As String()) Dim query = Sub(a) Dim {|Rename:arg1|} As Object = a Or a a = New With {Key .Key = Function(ByVal arg As Integer) As Integer Return arg End Function}.Key.Invoke(arg1) End Sub End Sub End Module") End Function <WorkItem(542762, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542762")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNotInIntoClause() As Task Await TestMissingInRegularAndScriptAsync( "Imports System.Linq Module Sub Main() Dim x = Aggregate y In New Integer() {1} Into [|Count()|] End Sub End Module") End Function <WorkItem(543289, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543289")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNotOnAttribute1() As Task Await TestMissingInRegularAndScriptAsync( "Option Explicit Off Module Program <Runtime.CompilerServices.[|Extension|]()> _ Function Extension(ByVal x As Integer) As Integer Return x End Function End Module") End Function <WorkItem(543289, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543289")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNotOnAttribute1CommentsAfterLineContinuation() As Task Await TestMissingInRegularAndScriptAsync( "Option Explicit Off Module Program <Runtime.CompilerServices.[|Extension|]()> _ ' Test Function Extension(ByVal x As Integer) As Integer Return x End Function End Module") End Function <WorkItem(543289, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543289")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNotOnAttribute2() As Task Await TestMissingInRegularAndScriptAsync( "Option Explicit Off Module Program <Runtime.CompilerServices.[|Extension()|]> _ Function Extension(ByVal x As Integer) As Integer Return x End Function End Module") End Function <WorkItem(543289, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543289")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNotOnAttribute2CommentsAfterLineContinuation() As Task Await TestMissingInRegularAndScriptAsync( "Option Explicit Off Module Program <Runtime.CompilerServices.[|Extension()|]> _ ' Test Function Extension(ByVal x As Integer) As Integer Return x End Function End Module") End Function <WorkItem(543461, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543461")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestCollectionInitializer() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Dim i1 = New Integer() [|{4, 5}|] End Sub End Module") End Function <WorkItem(543573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543573")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestCaseInsensitiveNameConflict() As Task Await TestInRegularAndScriptAsync( "Class M Public Function Goo() Return [|Me.Goo|] * 0 End Function End Class", "Class M Public Function Goo() Dim {|Rename:goo1|} As Object = Me.Goo Return goo1 * 0 End Function End Class") End Function <WorkItem(543590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543590")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestQuery1() As Task Await TestInRegularAndScriptAsync( "Imports System.Linq Public Class Base Public Function Sample(ByVal arg As Integer) As Integer Dim results = From s In New Integer() {1} Select [|Sample(s)|] Return 0 End Function End Class", "Imports System.Linq Public Class Base Public Function Sample(ByVal arg As Integer) As Integer Dim results = From s In New Integer() {1} Let {|Rename:v|} = Sample(s) Select v Return 0 End Function End Class") End Function <WorkItem(543590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543590")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestQueryCount1() As Task Await TestActionCountAsync( "Imports System.Linq Public Class Base Public Function Sample(ByVal arg As Integer) As Integer Dim results = From s In New Integer() {1} Select [|Sample(s)|] Return 0 End Function End Class", count:=2) End Function <WorkItem(543590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543590")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestQuery2() As Task Await TestInRegularAndScriptAsync( "Imports System.Linq Public Class Base Public Function Sample(ByVal arg As Integer) As Integer Dim results = From s In New Integer() {1} Where [|Sample(s)|] > 21 Select Sample(s) Return 0 End Function End Class", "Imports System.Linq Public Class Base Public Function Sample(ByVal arg As Integer) As Integer Dim results = From s In New Integer() {1} Let {|Rename:v|} = Sample(s) Where v > 21 Select Sample(s) Return 0 End Function End Class") End Function <WorkItem(543590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543590")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestQuery3() As Task Await TestInRegularAndScriptAsync( "Imports System.Linq Public Class Base Public Function Sample(ByVal arg As Integer) As Integer Dim results = From s In New Integer() {1} Where [|Sample(s)|] > 21 Select Sample(s) Return 0 End Function End Class", "Imports System.Linq Public Class Base Public Function Sample(ByVal arg As Integer) As Integer Dim results = From s In New Integer() {1} Let {|Rename:v|} = Sample(s) Where v > 21 Select v Return 0 End Function End Class", index:=1) End Function <WorkItem(543590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543590")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestQuery4() As Task Await TestInRegularAndScriptAsync( "Imports System.Linq Public Class Base Public Function Sample(ByVal arg As Integer) As Integer Dim results = From s In New Integer() {1} Where Sample(s) > 21 Select [|Sample(s)|] Return 0 End Function End Class", "Imports System.Linq Public Class Base Public Function Sample(ByVal arg As Integer) As Integer Dim results = From s In New Integer() {1} Where Sample(s) > 21 Let {|Rename:v|} = Sample(s) Select v Return 0 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestQuery5() As Task Await TestInRegularAndScriptAsync( "Imports System.Linq Public Class Base Public Function Sample(ByVal arg As Integer) As Integer Dim results = From s In New Integer() {1} Where Sample(s) > 21 Select [|Sample(s)|] Return 0 End Function End Class", "Imports System.Linq Public Class Base Public Function Sample(ByVal arg As Integer) As Integer Dim results = From s In New Integer() {1} Let {|Rename:v|} = Sample(s) Where v > 21 Select v Return 0 End Function End Class", index:=1) End Function <WorkItem(543529, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543529")> <WorkItem(909152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/909152")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInStatementlessConstructorParameter() As Task Await TestMissingInRegularAndScriptAsync("Class C1 Sub New(Optional ByRef x As String = [|Nothing|]) End Sub End Class") End Function <WorkItem(543650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543650")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestReferenceToAnonymousTypeProperty() As Task Await TestMissingInRegularAndScriptAsync( "Class AM Sub M(args As String()) Dim var1 As New AM Dim at1 As New With {var1, .friend = [|.var1|]} End Sub End Class") End Function <WorkItem(543698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543698")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestIntegerArrayExpression() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main() Return [|New Integer() {}|] End Sub End Module", "Module Program Sub Main() Dim {|Rename:vs|} As Integer() = New Integer() {} Return vs End Sub End Module") End Function <WorkItem(544273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544273")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestAttributeNamedParameter() As Task Await TestMissingInRegularAndScriptAsync( "Class TestAttribute Inherits Attribute Public Sub New(Optional a As Integer = 42) End Sub End Class <Test([|a|]:=5)> Class Goo End Class") End Function <WorkItem(544265, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544265")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestMissingOnWrittenToExpression() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub Main() Dim x = New Integer() {1, 2} [|x(1)|] = 2 End Sub End Module") End Function <WorkItem(543824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543824")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestImplicitMemberAccess1() As Task Await TestMissingInRegularAndScriptAsync( "Imports System Public Class C1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Class Public Class C2 Public Shared Sub Main() Dim x = 1 + New C1() With {.FieldStr = [|.FieldInt|].ToString()} End Sub End Class") End Function <WorkItem(543824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543824")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestImplicitMemberAccess2() As Task Await TestMissingInRegularAndScriptAsync( "Imports System Public Class C1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Class Public Class C2 Public Shared Sub Main() Dim x = 1 + New C1() With {.FieldStr = [|.FieldInt.ToString|]()} End Sub End Class") End Function <WorkItem(543824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543824")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestImplicitMemberAccess3() As Task Await TestMissingInRegularAndScriptAsync( "Imports System Public Class C1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Class Public Class C2 Public Shared Sub Main() Dim x = 1 + New C1() With {.FieldStr = [|.FieldInt.ToString()|]} End Sub End Class") End Function <WorkItem(543824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543824")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestImplicitMemberAccess4() As Task Dim code = " Imports System Public Class C1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Class Public Class C2 Public Shared Sub Main() Dim x = 1 + [|New C1() With {.FieldStr = .FieldInt.ToString()}|] End Sub End Class " Dim expected = " Imports System Public Class C1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Class Public Class C2 Public Shared Sub Main() Dim {|Rename:c1|} As C1 = New C1() With {.FieldStr = .FieldInt.ToString()} Dim x = 1 + c1 End Sub End Class " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(529510, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529510")> <WpfFact(Skip:="529510"), Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNoRefactoringOnAddressOfExpression() As Task Dim source = "Imports System Module Module1 Public Sub Goo(ByVal a1 As Exception) End Sub Public Sub goo(ByVal a1 As Action(Of ArgumentException)) End Sub Sub Main() Goo(New Action(Of Exception)([|AddressOf Goo|])) End Sub End Module" Await TestMissingInRegularAndScriptAsync(source) End Function <WorkItem(529510, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529510")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)> Public Async Function TestMissingOnAddressOfInDelegate() As Task Await TestMissingInRegularAndScriptAsync( "Module Module1 Public Sub Goo(ByVal a1 As Exception) End Sub Public Sub goo(ByVal a1 As Action(Of ArgumentException)) End Sub Sub Main() goo(New Action(Of Exception)([|AddressOf Goo|])) End Sub End Module") End Function <WorkItem(545168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545168")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)> Public Async Function TestMissingOnXmlName() As Task Await TestMissingInRegularAndScriptAsync( "Module M Sub Main() Dim x = <[|x|]/> End Sub End Module") End Function <WorkItem(545262, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545262")> <WorkItem(909152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/909152")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInTernaryConditional() As Task Await TestMissingInRegularAndScriptAsync("Module Program Sub Main(args As String()) Dim p As Object = Nothing Dim Obj1 = If(New With {.a = True}.a, p, [|Nothing|]) End Sub End Module") End Function <WorkItem(545316, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545316")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInPropertyInitializer() As Task Await TestInRegularAndScriptAsync( "Module Module1 Property Prop As New List(Of String) From {[|""One""|], ""two""} End Module", "Module Module1 Private Const {|Rename:V|} As String = ""One"" Property Prop As New List(Of String) From {V, ""two""} End Module") End Function <WorkItem(545308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545308")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestDoNotMergeAmpersand() As Task Dim code = " Module Module1 Public Sub goo(Optional ByVal arg = ([|""a""|]) & ""b"") End Sub End Module " Dim expected = " Module Module1 Private Const {|Rename:V|} As String = ""a"" Public Sub goo(Optional ByVal arg = V & ""b"") End Sub End Module " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(545258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545258")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestVenusGeneration1() As Task Dim code = " Class C Sub Goo() #ExternalSource (""Goo"", 1) Console.WriteLine([|5|]) #End ExternalSource End Sub End Class " Dim expected = " Class C Sub Goo() #ExternalSource (""Goo"", 1) Const {|Rename:V|} As Integer = 5 Console.WriteLine(V) #End ExternalSource End Sub End Class " Await TestExactActionSetOfferedAsync(code, {String.Format(FeaturesResources.Introduce_local_constant_for_0, "5"), String.Format(FeaturesResources.Introduce_local_constant_for_all_occurrences_of_0, "5")}) Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(545258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545258")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestVenusGeneration2() As Task Dim code = " Class C #ExternalSource (""Goo"", 1) Sub Goo() If False Then Console.WriteLine([|5|]) End If End Sub #End ExternalSource End Class " Await TestExactActionSetOfferedAsync(code, {String.Format(FeaturesResources.Introduce_local_constant_for_0, "5"), String.Format(FeaturesResources.Introduce_local_constant_for_all_occurrences_of_0, "5")}) End Function <WorkItem(545258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545258")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestVenusGeneration3() As Task Dim code = " Class C Sub Goo() #ExternalSource (""Goo"", 1) If False Then Console.WriteLine([|5|]) End If #End ExternalSource End Sub End Class " Dim expected = " Class C Sub Goo() #ExternalSource (""Goo"", 1) If False Then Const {|Rename:V|} As Integer = 5 Console.WriteLine(V) End If #End ExternalSource End Sub End Class " Await TestExactActionSetOfferedAsync(code, {String.Format(FeaturesResources.Introduce_local_constant_for_0, "5"), String.Format(FeaturesResources.Introduce_local_constant_for_all_occurrences_of_0, "5")}) Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(545525, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545525")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInvocation() As Task Await TestInRegularAndScriptAsync( "Option Strict On Class C Shared Sub Main() Dim x = [|New C().Goo()|](0) End Sub Function Goo() As Integer() End Function End Class", "Option Strict On Class C Shared Sub Main() Dim {|Rename:vs|} As Integer() = New C().Goo() Dim x = vs(0) End Sub Function Goo() As Integer() End Function End Class") End Function <WorkItem(545829, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545829")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestOnImplicitMemberAccess() As Task Await TestAsync( "Module Program Sub Main() With """" Dim x = [|.GetHashCode|] Xor &H7F3E ' Introduce Local End With End Sub End Module", "Module Program Sub Main() With """" Dim {|Rename:getHashCode|} As Integer = .GetHashCode Dim x = getHashCode Xor &H7F3E ' Introduce Local End With End Sub End Module", parseOptions:=Nothing) Await TestAsync( "Module Program Sub Main() With """" Dim x = [|.GetHashCode|] Xor &H7F3E ' Introduce Local End With End Sub End Module", "Module Program Sub Main() With """" Dim {|Rename:getHashCode|} As Integer = .GetHashCode Dim x = getHashCode Xor &H7F3E ' Introduce Local End With End Sub End Module", parseOptions:=GetScriptOptions()) End Function <WorkItem(545702, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545702")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestMissingInRefLocation() As Task Dim markup = " Module A Sub Main() Goo([|1|]) End Sub Sub Goo(ByRef x As Long) End Sub Sub Goo(x As String) End Sub End Module " Await TestMissingInRegularAndScriptAsync(markup) End Function <WorkItem(546139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546139")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestAcrossPartialTypes() As Task Await TestInRegularAndScriptAsync( "Partial Class C Sub goo1(Optional x As String = [|""HELLO""|]) End Sub End Class Partial Class C Sub goo3(Optional x As String = ""HELLO"") End Sub End Class", "Partial Class C Private Const {|Rename:V|} As String = ""HELLO"" Sub goo1(Optional x As String = V) End Sub End Class Partial Class C Sub goo3(Optional x As String = V) End Sub End Class", index:=1) End Function <WorkItem(544669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544669")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestFunctionBody1() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Dim a1 = Function(ByVal x) [|x!goo|] End Sub End Module", "Module Program Sub Main(args As String()) Dim a1 = Function(ByVal x) Dim {|Rename:goo|} As Object = x!goo Return goo End Function End Sub End Module") End Function <WorkItem(1065689, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1065689")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestTrailingTrivia() As Task Dim code = " Module M Sub Main() Dim a = 1 + [|2|] ' comment End Sub End Module " Dim expected = " Module M Private Const {|Rename:V|} As Integer = 2 Sub Main() Dim a = 1 + V ' comment End Sub End Module " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(546815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546815")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInIfStatement() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If [|True|] Then End If End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Private Const {|Rename:V|} As Boolean = True Sub Main(args As String()) If V Then End If End Sub End Module") End Function <WorkItem(830928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/830928")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestIntroduceLocalRemovesUnnecessaryCast() As Task Await TestInRegularAndScriptAsync( "Imports System.Collections.Generic Class C Private Shared Sub Main(args As String()) Dim hSet = New HashSet(Of String)() hSet.Add([|hSet.ToString()|]) End Sub End Class", "Imports System.Collections.Generic Class C Private Shared Sub Main(args As String()) Dim hSet = New HashSet(Of String)() Dim {|Rename:item|} As String = hSet.ToString() hSet.Add(item) End Sub End Class") End Function <WorkItem(546691, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546691")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestIntroLocalInSingleLineLambda() As Task Dim code = " Module Program Sub Main() Dim x = Function() [|Sub() End Sub|] End Sub End Module " Dim expected = " Module Program Sub Main() Dim {|Rename:p|} = Sub() End Sub Dim x = Function() p End Sub End Module " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(530720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530720")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestSingleToMultilineLambdaLineBreaks() As Task Dim code = " Module Program Sub Main() Dim a = Function(c) [|c!goo|] End Sub End Module " Dim expected = " Module Program Sub Main() Dim a = Function(c) Dim {|Rename:goo|} As Object = c!goo Return goo End Function End Sub End Module " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(531478, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531478")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestEscapeKeywordsIfNeeded1() As Task Dim code = " Imports System.Collections.Generic Imports System.Linq Module Program Sub Main() Take([|From x In """"|]) End Sub Sub Take(x) End Sub End Module " Dim expected = " Imports System.Collections.Generic Imports System.Linq Module Program Sub Main() Dim {|Rename:x1|} As IEnumerable(Of Char) = From x In """" [Take](x1) End Sub Sub Take(x) End Sub End Module " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(632327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632327")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInsertAfterPreprocessor1() As Task Dim code = " Public Class Index_vbhtml Public Sub Execute() #ExternalSource (""Home\Index.vbhtml"", 1) Dim i = [|1 + 2|] + 3 If True Then Dim j = 1 + 2 + 3 End If #End ExternalSource End Sub End Class " Dim expected = " Public Class Index_vbhtml Public Sub Execute() #ExternalSource (""Home\Index.vbhtml"", 1) Const {|Rename:V|} As Integer = 1 + 2 Dim i = V + 3 If True Then Dim j = 1 + 2 + 3 End If #End ExternalSource End Sub End Class " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(632327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632327")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInsertAfterPreprocessor2() As Task Dim code = " Public Class Index_vbhtml Public Sub Execute() #ExternalSource (""Home\Index.vbhtml"", 1) Dim i = 1 + 2 + 3 If True Then Dim j = [|1 + 2|] + 3 End If #End ExternalSource End Sub End Class " Dim expected = " Public Class Index_vbhtml Public Sub Execute() #ExternalSource (""Home\Index.vbhtml"", 1) Dim i = 1 + 2 + 3 If True Then Const {|Rename:V|} As Integer = 1 + 2 Dim j = V + 3 End If #End ExternalSource End Sub End Class " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(682683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682683")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestDontRemoveParenthesesIfOperatorPrecedenceWouldBeBroken() As Task Dim code = " Imports System Module Program Sub Main() Console.WriteLine(5 - ([|1|] + 2)) End Sub End Module " Dim expected = " Imports System Module Program Sub Main() Const {|Rename:V|} As Integer = 1 Console.WriteLine(5 - (V + 2)) End Sub End Module " Await TestInRegularAndScriptAsync(code, expected, index:=2) End Function <WorkItem(1022458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1022458")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestDontSimplifyParentUnlessEntireInnerNodeIsSelected() As Task Dim code = " Imports System Module Program Sub Main() Dim s = ""Text"" Dim x = 42 If ([|s.Length|].CompareTo(x) > 0 AndAlso s.Length.CompareTo(x) > 0) Then End If End Sub End Module " Dim expected = " Imports System Module Program Sub Main() Dim s = ""Text"" Dim x = 42 Dim {|Rename:length|} As Integer = s.Length If (length.CompareTo(x) > 0 AndAlso length.CompareTo(x) > 0) Then End If End Sub End Module " Await TestInRegularAndScriptAsync(code, expected, index:=1) End Function <WorkItem(939259, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939259")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestIntroduceLocalWithTriviaInMultiLineStatements() As Task Dim code = " Imports System Module Program Sub Main() Dim x = If(True, [|1|], ' TODO: Comment 2) End Sub End Module " Dim expected = " Imports System Module Program Sub Main() Const {|Rename:V|} As Integer = 1 Dim x = If(True, V, ' TODO: Comment 2) End Sub End Module " Await TestInRegularAndScriptAsync(code, expected, index:=3) End Function <WorkItem(909152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/909152")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestMissingOnNothingLiteral() As Task Await TestMissingInRegularAndScriptAsync( " Imports System Module Program Sub Main(args As String()) Main([|Nothing|]) M(Nothing) End Sub Sub M(i As Integer) End Sub End Module ") End Function <WorkItem(1130990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130990")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInParentConditionalAccessExpressions() As Task Dim code = " Imports System Class C Function F(Of T)(x As T) As T Dim y = [|F(New C)|]?.F(New C)?.F(New C) Return x End Function End Class " Dim expected = " Imports System Class C Function F(Of T)(x As T) As T Dim {|Rename:c|} As C = F(New C) Dim y = c?.F(New C)?.F(New C) Return x End Function End Class " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(1130990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130990")> <WorkItem(3110, "https://github.com/dotnet/roslyn/issues/3110")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestMissingAcrossMultipleParentConditionalAccessExpressions() As Task Await TestMissingInRegularAndScriptAsync( " Imports System Class C Function F(Of T)(x As T) As T Dim y = [|F(New C)?.F(New C)|]?.F(New C) Return x End Function End Class ") End Function <WorkItem(1130990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130990")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestMissingOnInvocationExpressionInParentConditionalAccessExpressions() As Task Await TestMissingInRegularAndScriptAsync( " Imports System Class C Function F(Of T)(x As T) As T Dim y = F(New C)?.[|F(New C)|]?.F(New C) Return x End Function End Class ") End Function <WorkItem(1130990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130990")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestMissingOnMemberBindingExpressionInParentConditionalAccessExpressions() As Task Await TestMissingInRegularAndScriptAsync( " Imports System Class C Sub F() Dim s as String = ""Text"" Dim l = s?.[|Length|] End Sub End Class ") End Function <WorkItem(2026, "https://github.com/dotnet/roslyn/issues/2026")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestReplaceAllFromInsideIfBlock() As Task Dim code = " Imports System Module DataTipInfoGetterModule Friend Function GetInfoAsync() As DebugDataTipInfo Dim expression As ExpressionSyntax = Nothing Dim curr = DirectCast(expression.Parent, ExpressionSyntax) If curr Is expression.Parent Then Return New DebugDataTipInfo([|expression.Parent|].Span) End If Return Nothing End Function End Module Friend Class TextSpan End Class Friend Class ExpressionSyntax Public Property Parent As ExpressionSyntax Public Property Span As TextSpan End Class Friend Class DebugDataTipInfo Public Sub New(span As Object) End Sub End Class " Dim expected = " Imports System Module DataTipInfoGetterModule Friend Function GetInfoAsync() As DebugDataTipInfo Dim expression As ExpressionSyntax = Nothing Dim {|Rename:parent|} As ExpressionSyntax = expression.Parent Dim curr = DirectCast(parent, ExpressionSyntax) If curr Is parent Then Return New DebugDataTipInfo(parent.Span) End If Return Nothing End Function End Module Friend Class TextSpan End Class Friend Class ExpressionSyntax Public Property Parent As ExpressionSyntax Public Property Span As TextSpan End Class Friend Class DebugDataTipInfo Public Sub New(span As Object) End Sub End Class " Await TestInRegularAndScriptAsync(code, expected, index:=1) End Function <WorkItem(1065661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1065661")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestIntroduceVariableTextDoesntSpanLines1() As Task Dim code = " Class C Sub M() Dim s = """" + [|""a b c""|] End Sub End Class" Await TestSmartTagTextAsync(code, String.Format(FeaturesResources.Introduce_local_constant_for_0, """a b c"""), New TestParameters(index:=2)) End Function <WorkItem(1065661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1065661")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestIntroduceVariableTextDoesntSpanLines2() As Task Dim code = " Class C Sub M() Dim s = """" + [|$""a b c""|] End Sub End Class" Await TestSmartTagTextAsync(code, String.Format(FeaturesResources.Introduce_local_for_0, "$""a b c""")) End Function <WorkItem(976, "https://github.com/dotnet/roslyn/issues/976")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNoConstantForInterpolatedStrings1() As Task Dim code = " Module Program Sub Main() Dim args As String() = Nothing Console.WriteLine([|$""{DateTime.Now.ToString()}Text{args(0)}""|]) End Sub End Module " Dim expected = " Module Program Sub Main() Dim args As String() = Nothing Dim {|Rename:v|} As String = $""{DateTime.Now.ToString()}Text{args(0)}"" Console.WriteLine(v) End Sub End Module " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(976, "https://github.com/dotnet/roslyn/issues/976")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestNoConstantForInterpolatedStrings2() As Task Dim code = " Module Program Sub Main() Console.WriteLine([|$""Text{{s}}""|]) Console.WriteLine($""Text{{s}}"") End Sub End Module " Dim expected = " Module Program Sub Main() Dim {|Rename:v|} As String = $""Text{{s}}"" Console.WriteLine(v) Console.WriteLine(v) End Sub End Module " Await TestInRegularAndScriptAsync(code, expected, index:=1) End Function <WorkItem(3147, "https://github.com/dotnet/roslyn/issues/3147")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestHandleFormattableStringTargetTyping1() As Task Const code = " Imports System " & FormattableStringType & " Namespace N Class C Public Sub M() Dim f = FormattableString.Invariant([|$""""|]) End Sub End Class End Namespace" Const expected = " Imports System " & FormattableStringType & " Namespace N Class C Public Sub M() Dim {|Rename:formattable|} As FormattableString = $"""" Dim f = FormattableString.Invariant(formattable) End Sub End Class End Namespace" Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(936, "https://github.com/dotnet/roslyn/issues/936")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInAutoPropertyInitializerEqualsClause() As Task Dim code = " Imports System Class C Property Name As String = [|""Roslyn""|] End Class " Dim expected = " Imports System Class C Private Const {|Rename:V|} As String = ""Roslyn"" Property Name As String = V End Class " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(936, "https://github.com/dotnet/roslyn/issues/936")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInAutoPropertyWithCollectionInitializerAfterEqualsClause() As Task Dim code = " Imports System Class C Property Grades As Integer() = [|{90, 73}|] End Class " Dim expected = " Imports System Class C Private Shared ReadOnly {|Rename:p|} As Integer() = {90, 73} Property Grades As Integer() = p End Class " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(936, "https://github.com/dotnet/roslyn/issues/936")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInAutoPropertyInitializerAsClause() As Task Dim code = " Imports System Class C Public Property Items As New List(Of String) From {[|""M""|], ""T"", ""W""} End Class " Dim expected = " Imports System Class C Private Const {|Rename:V|} As String = ""M"" Public Property Items As New List(Of String) From {V, ""T"", ""W""} End Class " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(936, "https://github.com/dotnet/roslyn/issues/936")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInAutoPropertyObjectCreationExpressionWithinAsClause() As Task Dim code = " Imports System Class C Property Orders As New List(Of Object)([|500|]) End Class " Dim expected = " Imports System Class C Private Const {|Rename:V|} As Integer = 500 Property Orders As New List(Of Object)(V) End Class " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(11777, "https://github.com/dotnet/roslyn/issues/11777")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestGenerateLocalConflictingName1() As Task Await TestInRegularAndScriptAsync( "class Program class MySpan public Start as integer end class sub Method(span as MySpan) dim pos as integer = span.Start while pos < [|span.Start|] dim start as integer = pos end while end sub end class", "class Program class MySpan public Start as integer end class sub Method(span as MySpan) dim pos as integer = span.Start Dim {|Rename:start1|} As Integer = span.Start while pos < start1 dim start as integer = pos end while end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TupleWithInferredName_LeaveExplicitName() As Task Dim code = " Class C Shared Dim y As Integer = 2 Sub M() Dim a As Integer = 1 Dim t = (a, x:=[|C.y|]) End Sub End Class " Dim expected = " Class C Shared Dim y As Integer = 2 Sub M() Dim a As Integer = 1 Dim {|Rename:y1|} As Integer = C.y Dim t = (a, x:=y1) End Sub End Class " Await TestAsync(code, expected, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TupleWithInferredName_InferredNameBecomesExplicit() As Task Dim code = " Class C Shared Dim y As Integer = 2 Sub M() Dim a As Integer = 1 Dim t = (a, [|C.y|]) End Sub End Class " Dim expected = " Class C Shared Dim y As Integer = 2 Sub M() Dim a As Integer = 1 Dim {|Rename:y1|} As Integer = C.y Dim t = (a, y:=y1) End Sub End Class " Await TestAsync(code, expected, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TupleWithInferredName_AllOccurrences() As Task Dim code = " Class C Shared Dim y As Integer = 2 Sub M() Dim a As Integer = 1 Dim t = (a, [|C.y|]) Dim t2 = (C.y, a) End Sub End Class " Dim expected = " Class C Shared Dim y As Integer = 2 Sub M() Dim a As Integer = 1 Dim {|Rename:y1|} As Integer = C.y Dim t = (a, y:=y1) Dim t2 = (y:=y1, a) End Sub End Class " Await TestAsync(code, expected, index:=1, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TupleWithInferredName_NoDuplicateNames() As Task Dim code = " Class C Shared Dim y As Integer = 2 Sub M() Dim t = (C.y, [|C.y|]) End Sub End Class " Dim expected = " Class C Shared Dim y As Integer = 2 Sub M() Dim {|Rename:y1|} As Integer = C.y Dim t = (y1, y1) End Sub End Class " Await TestInRegularAndScriptAsync(code, expected, index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TupleWithInferredName_NoReservedNames() As Task Dim code = " Class C Shared Dim rest As Integer = 2 Sub M() Dim a As Integer = 1 Dim t = (a, [|C.rest|]) End Sub End Class " Dim expected = " Class C Shared Dim rest As Integer = 2 Sub M() Dim a As Integer = 1 Dim {|Rename:rest1|} As Integer = C.rest Dim t = (a, rest1) End Sub End Class " Await TestAsync(code, expected, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function AnonymousTypeWithInferredName_LeaveExplicitName() As Task Dim code = " Class C Shared Dim y As Integer = 2 Sub M() Dim a As Integer = 1 Dim t = New With {a, [|C.y|]} End Sub End Class " Dim expected = " Class C Shared Dim y As Integer = 2 Sub M() Dim a As Integer = 1 Dim {|Rename:y1|} As Integer = C.y Dim t = New With {a, .y = y1} End Sub End Class " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(2423, "https://github.com/dotnet/roslyn/issues/2423")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestPickNameBasedOnArgument1() As Task Await TestInRegularAndScriptAsync( "class C public sub new(a as string, b as string) dim c = new TextSpan([|integer.Parse(a)|], integer.Parse(b)) end sub end class structure TextSpan public sub new(start as integer, length as integer) end sub end structure", "class C public sub new(a as string, b as string) Dim {|Rename:start|} As Integer = integer.Parse(a) dim c = new TextSpan(start, integer.Parse(b)) end sub end class structure TextSpan public sub new(start as integer, length as integer) end sub end structure") End Function <WorkItem(2423, "https://github.com/dotnet/roslyn/issues/2423")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestPickNameBasedOnArgument2() As Task Await TestInRegularAndScriptAsync( "class C public sub new(a as string, b as string) dim c = new TextSpan(integer.Parse(a), [|integer.Parse(b)|]) end sub end class structure TextSpan public sub new(start as integer, length as integer) end sub end structure", "class C public sub new(a as string, b as string) Dim {|Rename:length|} As Integer = integer.Parse(b) dim c = new TextSpan(integer.Parse(a), length) end sub end class structure TextSpan public sub new(start as integer, length as integer) end sub end structure") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(10123, "https://github.com/dotnet/roslyn/issues/10123")> Public Async Function TestSimpleParameterName() As Task Dim source = "Module Program Sub Main(x As Integer) Goo([|x|]) End Sub End Module" Dim expected = "Module Program Sub Main(x As Integer) Dim {|Rename:x1|} As Integer = x Goo(x1) End Sub End Module" Await TestInRegularAndScriptAsync(source, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(10123, "https://github.com/dotnet/roslyn/issues/10123")> Public Async Function TestSimpleParameterName_EmptySelection() As Task Dim source = "Module Program Sub Main(x As Integer) Goo([||]x) End Sub End Module" Await TestMissingAsync(source) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(10123, "https://github.com/dotnet/roslyn/issues/10123")> Public Async Function TestFieldName_QualifiedWithMe() As Task Dim source = "Module Program Dim x As Integer Sub Main() Goo([|x|]) End Sub End Module" Dim expected = "Module Program Dim x As Integer Sub Main() Dim {|Rename:x1|} As Integer = x Goo(x1) End Sub End Module" Await TestInRegularAndScriptAsync(source, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(10123, "https://github.com/dotnet/roslyn/issues/10123")> Public Async Function TestFieldName_QualifiedWithType() As Task Dim source = "Module Program Shared Dim x As Integer Sub Main() Goo([|Program.x|]) End Sub End Module" Dim expected = "Module Program Shared Dim x As Integer Sub Main() Dim {|Rename:x1|} As Integer = Program.x Goo(x1) End Sub End Module" Await TestInRegularAndScriptAsync(source, expected) End Function <WorkItem(21373, "https://github.com/dotnet/roslyn/issues/21373")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestInAttribute() As Task Dim code = " Class C Public Property Foo() <Example([|3 + 3|])> Public Property Bar() End Class " Dim expected = " Class C Private Const {|Rename:V|} As Integer = 3 + 3 Public Property Foo() <Example(V)> Public Property Bar() End Class " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(28266, "https://github.com/dotnet/roslyn/issues/28266")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestCaretAtEndOfExpression1() As Task Await TestInRegularAndScriptAsync( "class C sub Goo() Bar(1[||], 2) end sub end class", "class C Private Const {|Rename:V|} As Integer = 1 sub Goo() Bar(V, 2) end sub end class") End Function <WorkItem(28266, "https://github.com/dotnet/roslyn/issues/28266")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestCaretAtEndOfExpression2() As Task Await TestInRegularAndScriptAsync( "class C sub Goo() Bar(1, 2[||]) end sub end class", "class C Private Const {|Rename:V|} As Integer = 2 sub Goo() Bar(1, V) end sub end class") End Function <WorkItem(28266, "https://github.com/dotnet/roslyn/issues/28266")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestCaretAtEndOfExpression3() As Task Await TestInRegularAndScriptAsync( "class C sub Goo() Bar(1, (2[||])) end sub end class", "class C Private Const {|Rename:V|} As Integer = (2) sub Goo() Bar(1, V) end sub end class") End Function <WorkItem(28266, "https://github.com/dotnet/roslyn/issues/28266")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> Public Async Function TestCaretAtEndOfExpression4() As Task Await TestInRegularAndScriptAsync( "class C sub Goo() Bar(1, Bar(2[||])) end sub end class", "class C Private Const {|Rename:V|} As Integer = 2 sub Goo() Bar(1, Bar(V)) end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(27949, "https://github.com/dotnet/roslyn/issues/27949")> Public Async Function TestWhitespaceSpanInAssignment() As Task Await TestMissingAsync(" Class C Dim x As Integer = [| |] 0 End Class ") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(28665, "https://github.com/dotnet/roslyn/issues/28665")> Public Async Function TestWhitespaceSpanInAttribute() As Task Await TestMissingAsync(" Class C <Example( [| |] )> Public Function Foo() End Function End Class ") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(30207, "https://github.com/dotnet/roslyn/issues/30207")> Public Async Function TestExplicitRecursiveInstanceMemberAccess_ForAllOccurrences() As Task Dim source = " Class C Dim c As C Sub Foo() Dim y = [|c|].c.c End Sub End Class " Dim expected = " Class C Dim c As C Sub Foo() Dim {|Rename:c1|} As C = c Dim y = c1.c.c End Sub End Class " Await TestInRegularAndScriptAsync(source, expected, index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(30207, "https://github.com/dotnet/roslyn/issues/30207")> Public Async Function TestImplicitRecursiveInstanceMemberAccess_ForAllOccurrences() As Task Dim source = " Class C Dim c As C Sub Foo() Dim y = [|Me.c|].c.c End Sub End Class " Dim expected = " Class C Dim c As C Sub Foo() Dim {|Rename:c1|} As C = Me.c Dim y = c1.c.c End Sub End Class " Await TestInRegularAndScriptAsync(source, expected, index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(30207, "https://github.com/dotnet/roslyn/issues/30207")> Public Async Function TestExpressionOfUndeclaredType() As Task Dim source = " Class C Sub Test Dim array As A() = [|A|].Bar() End Sub End Class" Await TestMissingAsync(source) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(47772, "https://github.com/dotnet/roslyn/issues/47772")> Public Async Function DoNotIntroduceConstantForConstant_Local() As Task Dim source = " Class C Sub Test Const i As Integer = [|10|] End Sub End Class " Await TestMissingAsync(source) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(47772, "https://github.com/dotnet/roslyn/issues/47772")> Public Async Function DoNotIntroduceConstantForConstant_Member() As Task Dim source = " Class C Const i As Integer = [|10|] End Class " Await TestMissingAsync(source) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(47772, "https://github.com/dotnet/roslyn/issues/47772")> Public Async Function DoNotIntroduceConstantForConstant_Parentheses() As Task Dim source = " Class C Const i As Integer = ([|10|]) End Class " Await TestMissingAsync(source) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(47772, "https://github.com/dotnet/roslyn/issues/47772")> Public Async Function DoNotIntroduceConstantForConstant_NotForSubExpression() As Task Dim source = " Class C Sub Test Const i As Integer = [|10|] + 10 End Sub End Class " Dim expected = " Class C Sub Test Const {|Rename:V|} As Integer = 10 Const i As Integer = V + 10 End Sub End Class " Await TestInRegularAndScriptAsync(source, expected, index:=2) End Function End Class End Namespace
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Features/CSharp/Portable/BraceCompletion/StringLiteralBraceCompletionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.BraceCompletion; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.BraceCompletion { [Export(LanguageNames.CSharp, typeof(IBraceCompletionService)), Shared] internal class StringLiteralBraceCompletionService : AbstractBraceCompletionService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public StringLiteralBraceCompletionService() { } protected override char OpeningBrace => DoubleQuote.OpenCharacter; protected override char ClosingBrace => DoubleQuote.CloseCharacter; public override Task<bool> AllowOverTypeAsync(BraceCompletionContext context, CancellationToken cancellationToken) => AllowOverTypeWithValidClosingTokenAsync(context, cancellationToken); public override async Task<bool> CanProvideBraceCompletionAsync(char brace, int openingPosition, Document document, CancellationToken cancellationToken) { // Only potentially valid for string literal completion if not in an interpolated string brace completion context. if (OpeningBrace == brace && await InterpolatedStringBraceCompletionService.IsPositionInInterpolatedStringContextAsync(document, openingPosition, cancellationToken).ConfigureAwait(false)) { return false; } return await base.CanProvideBraceCompletionAsync(brace, openingPosition, document, cancellationToken).ConfigureAwait(false); } protected override bool IsValidOpeningBraceToken(SyntaxToken token) => token.IsKind(SyntaxKind.StringLiteralToken); protected override bool IsValidClosingBraceToken(SyntaxToken token) => token.IsKind(SyntaxKind.StringLiteralToken); protected override Task<bool> IsValidOpenBraceTokenAtPositionAsync(SyntaxToken token, int position, Document document, CancellationToken cancellationToken) { var syntaxFactsService = document.GetRequiredLanguageService<ISyntaxFactsService>(); if (ParentIsSkippedTokensTriviaOrNull(syntaxFactsService, token) || !IsValidOpeningBraceToken(token)) { return SpecializedTasks.False; } if (token.SpanStart == position) { return SpecializedTasks.True; } // The character at the position is a double quote but the token's span start we found at the position // doesn't match the position. Check if we're in a verbatim string token @" where the token span start // is the @ character and the " is one past the token start. return Task.FromResult(token.SpanStart + 1 == position && token.IsVerbatimStringLiteral()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.BraceCompletion; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.BraceCompletion { [Export(LanguageNames.CSharp, typeof(IBraceCompletionService)), Shared] internal class StringLiteralBraceCompletionService : AbstractBraceCompletionService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public StringLiteralBraceCompletionService() { } protected override char OpeningBrace => DoubleQuote.OpenCharacter; protected override char ClosingBrace => DoubleQuote.CloseCharacter; public override Task<bool> AllowOverTypeAsync(BraceCompletionContext context, CancellationToken cancellationToken) => AllowOverTypeWithValidClosingTokenAsync(context, cancellationToken); public override async Task<bool> CanProvideBraceCompletionAsync(char brace, int openingPosition, Document document, CancellationToken cancellationToken) { // Only potentially valid for string literal completion if not in an interpolated string brace completion context. if (OpeningBrace == brace && await InterpolatedStringBraceCompletionService.IsPositionInInterpolatedStringContextAsync(document, openingPosition, cancellationToken).ConfigureAwait(false)) { return false; } return await base.CanProvideBraceCompletionAsync(brace, openingPosition, document, cancellationToken).ConfigureAwait(false); } protected override bool IsValidOpeningBraceToken(SyntaxToken token) => token.IsKind(SyntaxKind.StringLiteralToken); protected override bool IsValidClosingBraceToken(SyntaxToken token) => token.IsKind(SyntaxKind.StringLiteralToken); protected override Task<bool> IsValidOpenBraceTokenAtPositionAsync(SyntaxToken token, int position, Document document, CancellationToken cancellationToken) { var syntaxFactsService = document.GetRequiredLanguageService<ISyntaxFactsService>(); if (ParentIsSkippedTokensTriviaOrNull(syntaxFactsService, token) || !IsValidOpeningBraceToken(token)) { return SpecializedTasks.False; } if (token.SpanStart == position) { return SpecializedTasks.True; } // The character at the position is a double quote but the token's span start we found at the position // doesn't match the position. Check if we're in a verbatim string token @" where the token span start // is the @ character and the " is one past the token start. return Task.FromResult(token.SpanStart + 1 == position && token.IsVerbatimStringLiteral()); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ObjectKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ObjectKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender { public ObjectKeywordRecommender() : base(SyntaxKind.ObjectKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsNonAttributeExpressionContext || context.IsDefiniteCastTypeContext || context.IsStatementContext || context.IsGlobalStatementContext || context.IsObjectCreationTypeContext || (context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) || context.IsFunctionPointerTypeArgumentContext || context.IsIsOrAsTypeContext || context.IsLocalVariableDeclarationContext || context.IsParameterTypeContext || context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext || context.IsLocalFunctionDeclarationContext || context.IsImplicitOrExplicitOperatorTypeContext || context.IsTypeOfExpressionContext || context.IsCrefContext || syntaxTree.IsDefaultExpressionContext(position, context.LeftToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) || context.IsDelegateReturnTypeContext || syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || context.IsPossibleTupleContext || context.IsMemberDeclarationContext( validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } protected override SpecialType SpecialType => SpecialType.System_Object; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ObjectKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender { public ObjectKeywordRecommender() : base(SyntaxKind.ObjectKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsNonAttributeExpressionContext || context.IsDefiniteCastTypeContext || context.IsStatementContext || context.IsGlobalStatementContext || context.IsObjectCreationTypeContext || (context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) || context.IsFunctionPointerTypeArgumentContext || context.IsIsOrAsTypeContext || context.IsLocalVariableDeclarationContext || context.IsParameterTypeContext || context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext || context.IsLocalFunctionDeclarationContext || context.IsImplicitOrExplicitOperatorTypeContext || context.IsTypeOfExpressionContext || context.IsCrefContext || syntaxTree.IsDefaultExpressionContext(position, context.LeftToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) || context.IsDelegateReturnTypeContext || syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || context.IsPossibleTupleContext || context.IsMemberDeclarationContext( validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } protected override SpecialType SpecialType => SpecialType.System_Object; } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/Model/Comment.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Xml; using System.Xml.Serialization; namespace CSharpSyntaxGenerator { public class Comment { [XmlAnyElement] public XmlElement[] Body; } }
// Licensed to the .NET Foundation under one or more 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.Xml; using System.Xml.Serialization; namespace CSharpSyntaxGenerator { public class Comment { [XmlAnyElement] public XmlElement[] Body; } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/VisualStudio/Core/Test/Diagnostics/VisualStudioDiagnosticAnalyzerProviderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.IO Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.Diagnostics Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Diagnostics Public Class VisualStudioDiagnosticAnalyzerProviderTests <Fact> Public Sub GetAnalyzerReferencesInExtensions_Substitution() Dim extensionManager = New VisualStudioDiagnosticAnalyzerProvider( New MockExtensionManager("Microsoft.VisualStudio.Analyzer", "$RootFolder$\test\test.dll", "$ShellFolder$\test\test.dll", "test\test.dll"), GetType(MockExtensionManager.MockContent)) Dim references = extensionManager.GetAnalyzerReferencesInExtensions() AssertEx.SetEqual( { Path.Combine(TempRoot.Root, "ResolvedRootFolder\test\test.dll"), Path.Combine(TempRoot.Root, "ResolvedShellFolder\test\test.dll"), Path.Combine(TempRoot.Root, "InstallPath\test\test.dll") }, references.Select(Function(reference) reference.FullPath)) End Sub <Fact> Public Sub GetAnalyzerReferencesInExtensions() Dim extensionManager = New VisualStudioDiagnosticAnalyzerProvider( New MockExtensionManager("Microsoft.VisualStudio.Analyzer", "installPath1", "installPath2", "installPath3"), GetType(MockExtensionManager.MockContent)) Dim references = extensionManager.GetAnalyzerReferencesInExtensions() AssertEx.SetEqual( { Path.Combine(TempRoot.Root, "InstallPath\installPath1"), Path.Combine(TempRoot.Root, "InstallPath\installPath2"), Path.Combine(TempRoot.Root, "InstallPath\installPath3") }, references.Select(Function(reference) reference.FullPath)) End Sub <Fact, WorkItem(6285, "https://github.com/dotnet/roslyn/issues/6285")> Public Sub TestHostAnalyzerAssemblyLoader() Using tempRoot = New TempRoot Dim dir = tempRoot.CreateDirectory Dim analyzerFile = DesktopTestHelpers.CreateCSharpAnalyzerAssemblyWithTestAnalyzer(dir, "TestAnalyzer") Dim analyzerLoader = VisualStudioDiagnosticAnalyzerProvider.AnalyzerAssemblyLoader Dim hostAnalyzers = New HostDiagnosticAnalyzers(ImmutableArray.Create(Of AnalyzerReference)(New AnalyzerFileReference(analyzerFile.Path, analyzerLoader))) Dim analyzerReferenceMap = hostAnalyzers.GetOrCreateHostDiagnosticAnalyzersPerReference(LanguageNames.CSharp) Assert.Single(analyzerReferenceMap) Dim analyzers = analyzerReferenceMap.Single().Value Assert.Single(analyzers) Assert.Equal("TestAnalyzer", analyzers(0).ToString) End Using End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.IO Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.Diagnostics Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Diagnostics Public Class VisualStudioDiagnosticAnalyzerProviderTests <Fact> Public Sub GetAnalyzerReferencesInExtensions_Substitution() Dim extensionManager = New VisualStudioDiagnosticAnalyzerProvider( New MockExtensionManager("Microsoft.VisualStudio.Analyzer", "$RootFolder$\test\test.dll", "$ShellFolder$\test\test.dll", "test\test.dll"), GetType(MockExtensionManager.MockContent)) Dim references = extensionManager.GetAnalyzerReferencesInExtensions() AssertEx.SetEqual( { Path.Combine(TempRoot.Root, "ResolvedRootFolder\test\test.dll"), Path.Combine(TempRoot.Root, "ResolvedShellFolder\test\test.dll"), Path.Combine(TempRoot.Root, "InstallPath\test\test.dll") }, references.Select(Function(reference) reference.FullPath)) End Sub <Fact> Public Sub GetAnalyzerReferencesInExtensions() Dim extensionManager = New VisualStudioDiagnosticAnalyzerProvider( New MockExtensionManager("Microsoft.VisualStudio.Analyzer", "installPath1", "installPath2", "installPath3"), GetType(MockExtensionManager.MockContent)) Dim references = extensionManager.GetAnalyzerReferencesInExtensions() AssertEx.SetEqual( { Path.Combine(TempRoot.Root, "InstallPath\installPath1"), Path.Combine(TempRoot.Root, "InstallPath\installPath2"), Path.Combine(TempRoot.Root, "InstallPath\installPath3") }, references.Select(Function(reference) reference.FullPath)) End Sub <Fact, WorkItem(6285, "https://github.com/dotnet/roslyn/issues/6285")> Public Sub TestHostAnalyzerAssemblyLoader() Using tempRoot = New TempRoot Dim dir = tempRoot.CreateDirectory Dim analyzerFile = DesktopTestHelpers.CreateCSharpAnalyzerAssemblyWithTestAnalyzer(dir, "TestAnalyzer") Dim analyzerLoader = VisualStudioDiagnosticAnalyzerProvider.AnalyzerAssemblyLoader Dim hostAnalyzers = New HostDiagnosticAnalyzers(ImmutableArray.Create(Of AnalyzerReference)(New AnalyzerFileReference(analyzerFile.Path, analyzerLoader))) Dim analyzerReferenceMap = hostAnalyzers.GetOrCreateHostDiagnosticAnalyzersPerReference(LanguageNames.CSharp) Assert.Single(analyzerReferenceMap) Dim analyzers = analyzerReferenceMap.Single().Value Assert.Single(analyzers) Assert.Equal("TestAnalyzer", analyzers(0).ToString) End Using End Sub End Class End Namespace
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpMethodExtractor { private abstract partial class CSharpCodeGenerator : CodeGenerator<StatementSyntax, ExpressionSyntax, SyntaxNode> { private readonly SyntaxToken _methodName; private const string NewMethodPascalCaseStr = "NewMethod"; private const string NewMethodCamelCaseStr = "newMethod"; public static Task<GeneratedCode> GenerateAsync( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction, CancellationToken cancellationToken) { var codeGenerator = Create(insertionPoint, selectionResult, analyzerResult, options, localFunction); return codeGenerator.GenerateAsync(cancellationToken); } private static CSharpCodeGenerator Create( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction) { if (ExpressionCodeGenerator.IsExtractMethodOnExpression(selectionResult)) { return new ExpressionCodeGenerator(insertionPoint, selectionResult, analyzerResult, options, localFunction); } if (SingleStatementCodeGenerator.IsExtractMethodOnSingleStatement(selectionResult)) { return new SingleStatementCodeGenerator(insertionPoint, selectionResult, analyzerResult, options, localFunction); } if (MultipleStatementsCodeGenerator.IsExtractMethodOnMultipleStatements(selectionResult)) { return new MultipleStatementsCodeGenerator(insertionPoint, selectionResult, analyzerResult, options, localFunction); } throw ExceptionUtilities.UnexpectedValue(selectionResult); } protected CSharpCodeGenerator( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction) : base(insertionPoint, selectionResult, analyzerResult, options, localFunction) { Contract.ThrowIfFalse(SemanticDocument == selectionResult.SemanticDocument); var nameToken = CreateMethodName(); _methodName = nameToken.WithAdditionalAnnotations(MethodNameAnnotation); } private CSharpSelectionResult CSharpSelectionResult { get { return (CSharpSelectionResult)SelectionResult; } } protected override SyntaxNode GetPreviousMember(SemanticDocument document) { var node = InsertionPoint.With(document).GetContext(); return (node.Parent is GlobalStatementSyntax) ? node.Parent : node; } protected override OperationStatus<IMethodSymbol> GenerateMethodDefinition(bool localFunction, CancellationToken cancellationToken) { var result = CreateMethodBody(cancellationToken); var methodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Private, modifiers: CreateMethodModifiers(), returnType: AnalyzerResult.ReturnType, refKind: RefKind.None, explicitInterfaceImplementations: default, name: _methodName.ToString(), typeParameters: CreateMethodTypeParameters(), parameters: CreateMethodParameters(), statements: result.Data, methodKind: localFunction ? MethodKind.LocalFunction : MethodKind.Ordinary); return result.With( MethodDefinitionAnnotation.AddAnnotationToSymbol( Formatter.Annotation.AddAnnotationToSymbol(methodSymbol))); } protected override async Task<SyntaxNode> GenerateBodyForCallSiteContainerAsync(CancellationToken cancellationToken) { var container = GetOutermostCallSiteContainerToProcess(cancellationToken); var variableMapToRemove = CreateVariableDeclarationToRemoveMap( AnalyzerResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken), cancellationToken); var firstStatementToRemove = GetFirstStatementOrInitializerSelectedAtCallSite(); var lastStatementToRemove = GetLastStatementOrInitializerSelectedAtCallSite(); Contract.ThrowIfFalse(firstStatementToRemove.Parent == lastStatementToRemove.Parent); var statementsToInsert = await CreateStatementsOrInitializerToInsertAtCallSiteAsync(cancellationToken).ConfigureAwait(false); var callSiteGenerator = new CallSiteContainerRewriter( container, variableMapToRemove, firstStatementToRemove, lastStatementToRemove, statementsToInsert); return container.CopyAnnotationsTo(callSiteGenerator.Generate()).WithAdditionalAnnotations(Formatter.Annotation); } private async Task<ImmutableArray<SyntaxNode>> CreateStatementsOrInitializerToInsertAtCallSiteAsync(CancellationToken cancellationToken) { var selectedNode = GetFirstStatementOrInitializerSelectedAtCallSite(); // field initializer, constructor initializer, expression bodied member case if (selectedNode is ConstructorInitializerSyntax || selectedNode is FieldDeclarationSyntax || IsExpressionBodiedMember(selectedNode) || IsExpressionBodiedAccessor(selectedNode)) { var statement = await GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(cancellationToken).ConfigureAwait(false); return ImmutableArray.Create(statement); } // regular case var semanticModel = SemanticDocument.SemanticModel; var context = InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var statements = AddSplitOrMoveDeclarationOutStatementsToCallSite(cancellationToken); statements = postProcessor.MergeDeclarationStatements(statements); statements = AddAssignmentStatementToCallSite(statements, cancellationToken); statements = await AddInvocationAtCallSiteAsync(statements, cancellationToken).ConfigureAwait(false); statements = AddReturnIfUnreachable(statements); return statements.CastArray<SyntaxNode>(); } protected override bool ShouldLocalFunctionCaptureParameter(SyntaxNode node) => ((CSharpParseOptions)node.SyntaxTree.Options).LanguageVersion < LanguageVersion.CSharp8; private static bool IsExpressionBodiedMember(SyntaxNode node) => node is MemberDeclarationSyntax member && member.GetExpressionBody() != null; private static bool IsExpressionBodiedAccessor(SyntaxNode node) => node is AccessorDeclarationSyntax accessor && accessor.ExpressionBody != null; private SimpleNameSyntax CreateMethodNameForInvocation() { return AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0 ? (SimpleNameSyntax)SyntaxFactory.IdentifierName(_methodName) : SyntaxFactory.GenericName(_methodName, SyntaxFactory.TypeArgumentList(CreateMethodCallTypeVariables())); } private SeparatedSyntaxList<TypeSyntax> CreateMethodCallTypeVariables() { Contract.ThrowIfTrue(AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0); // propagate any type variable used in extracted code var typeVariables = new List<TypeSyntax>(); foreach (var methodTypeParameter in AnalyzerResult.MethodTypeParametersInDeclaration) { typeVariables.Add(SyntaxFactory.ParseTypeName(methodTypeParameter.Name)); } return SyntaxFactory.SeparatedList(typeVariables); } protected SyntaxNode GetCallSiteContainerFromOutermostMoveInVariable(CancellationToken cancellationToken) { var outmostVariable = GetOutermostVariableToMoveIntoMethodDefinition(cancellationToken); if (outmostVariable == null) { return null; } var idToken = outmostVariable.GetIdentifierTokenAtDeclaration(SemanticDocument); var declStatement = idToken.GetAncestor<LocalDeclarationStatementSyntax>(); Contract.ThrowIfNull(declStatement); Contract.ThrowIfFalse(declStatement.Parent.IsStatementContainerNode()); return declStatement.Parent; } private DeclarationModifiers CreateMethodModifiers() { var isUnsafe = CSharpSelectionResult.ShouldPutUnsafeModifier(); var isAsync = CSharpSelectionResult.ShouldPutAsyncModifier(); var isStatic = !AnalyzerResult.UseInstanceMember; var isReadOnly = AnalyzerResult.ShouldBeReadOnly; // Static local functions are only supported in C# 8.0 and later var languageVersion = ((CSharpParseOptions)SemanticDocument.SyntaxTree.Options).LanguageVersion; if (LocalFunction && (!Options.GetOption(CSharpCodeStyleOptions.PreferStaticLocalFunction).Value || languageVersion < LanguageVersion.CSharp8)) { isStatic = false; } return new DeclarationModifiers( isUnsafe: isUnsafe, isAsync: isAsync, isStatic: isStatic, isReadOnly: isReadOnly); } private static SyntaxKind GetParameterRefSyntaxKind(ParameterBehavior parameterBehavior) { return parameterBehavior == ParameterBehavior.Ref ? SyntaxKind.RefKeyword : parameterBehavior == ParameterBehavior.Out ? SyntaxKind.OutKeyword : SyntaxKind.None; } private OperationStatus<ImmutableArray<SyntaxNode>> CreateMethodBody(CancellationToken cancellationToken) { var statements = GetInitialStatementsForMethodDefinitions(); statements = SplitOrMoveDeclarationIntoMethodDefinition(statements, cancellationToken); statements = MoveDeclarationOutFromMethodDefinition(statements, cancellationToken); statements = AppendReturnStatementIfNeeded(statements); statements = CleanupCode(statements); // set output so that we can use it in negative preview var wrapped = WrapInCheckStatementIfNeeded(statements); return CheckActiveStatements(statements).With(wrapped.ToImmutableArray<SyntaxNode>()); } private IEnumerable<StatementSyntax> WrapInCheckStatementIfNeeded(IEnumerable<StatementSyntax> statements) { var kind = CSharpSelectionResult.UnderCheckedStatementContext(); if (kind == SyntaxKind.None) { return statements; } if (statements.Skip(1).Any()) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))); } if (statements.Single() is BlockSyntax block) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, block)); } return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))); } private static ImmutableArray<StatementSyntax> CleanupCode(ImmutableArray<StatementSyntax> statements) { statements = PostProcessor.RemoveRedundantBlock(statements); statements = PostProcessor.RemoveDeclarationAssignmentPattern(statements); statements = PostProcessor.RemoveInitializedDeclarationAndReturnPattern(statements); return statements; } private static OperationStatus CheckActiveStatements(IEnumerable<StatementSyntax> statements) { var count = statements.Count(); if (count == 0) { return OperationStatus.NoActiveStatement; } if (count == 1) { if (statements.Single() is ReturnStatementSyntax returnStatement && returnStatement.Expression == null) { return OperationStatus.NoActiveStatement; } } foreach (var statement in statements) { if (statement is not LocalDeclarationStatementSyntax declStatement) { return OperationStatus.Succeeded; } foreach (var variable in declStatement.Declaration.Variables) { if (variable.Initializer != null) { // found one return OperationStatus.Succeeded; } } } return OperationStatus.NoActiveStatement; } private ImmutableArray<StatementSyntax> MoveDeclarationOutFromMethodDefinition( ImmutableArray<StatementSyntax> statements, CancellationToken cancellationToken) { using var _ = ArrayBuilder<StatementSyntax>.GetInstance(out var result); var variableToRemoveMap = CreateVariableDeclarationToRemoveMap( AnalyzerResult.GetVariablesToMoveOutToCallSiteOrDelete(cancellationToken), cancellationToken); statements = statements.SelectAsArray(s => FixDeclarationExpressionsAndDeclarationPatterns(s, variableToRemoveMap)); foreach (var statement in statements) { if (statement is not LocalDeclarationStatementSyntax declarationStatement || declarationStatement.Declaration.Variables.FullSpan.IsEmpty) { // if given statement is not decl statement. result.Add(statement); continue; } var expressionStatements = new List<StatementSyntax>(); var list = new List<VariableDeclaratorSyntax>(); var triviaList = new List<SyntaxTrivia>(); // When we modify the declaration to an initialization we have to preserve the leading trivia var firstVariableToAttachTrivia = true; // go through each var decls in decl statement, and create new assignment if // variable is initialized at decl. foreach (var variableDeclaration in declarationStatement.Declaration.Variables) { if (variableToRemoveMap.HasSyntaxAnnotation(variableDeclaration)) { if (variableDeclaration.Initializer != null) { var identifier = ApplyTriviaFromDeclarationToAssignmentIdentifier(declarationStatement, firstVariableToAttachTrivia, variableDeclaration); // move comments with the variable here expressionStatements.Add(CreateAssignmentExpressionStatement(identifier, variableDeclaration.Initializer.Value)); } else { // we don't remove trivia around tokens we remove triviaList.AddRange(variableDeclaration.GetLeadingTrivia()); triviaList.AddRange(variableDeclaration.GetTrailingTrivia()); } firstVariableToAttachTrivia = false; continue; } // Prepend the trivia from the declarations without initialization to the next persisting variable declaration if (triviaList.Count > 0) { list.Add(variableDeclaration.WithPrependedLeadingTrivia(triviaList)); triviaList.Clear(); firstVariableToAttachTrivia = false; continue; } firstVariableToAttachTrivia = false; list.Add(variableDeclaration); } if (list.Count == 0 && triviaList.Count > 0) { // well, there are trivia associated with the node. // we can't just delete the node since then, we will lose // the trivia. unfortunately, it is not easy to attach the trivia // to next token. for now, create an empty statement and associate the // trivia to the statement // TODO : think about a way to trivia attached to next token result.Add(SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxFactory.TriviaList(triviaList), SyntaxKind.SemicolonToken, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)))); triviaList.Clear(); } // return survived var decls if (list.Count > 0) { result.Add(SyntaxFactory.LocalDeclarationStatement( declarationStatement.Modifiers, SyntaxFactory.VariableDeclaration( declarationStatement.Declaration.Type, SyntaxFactory.SeparatedList(list)), declarationStatement.SemicolonToken.WithPrependedLeadingTrivia(triviaList))); triviaList.Clear(); } // return any expression statement if there was any result.AddRange(expressionStatements); } return result.ToImmutable(); } /// <summary> /// If the statement has an <c>out var</c> declaration expression for a variable which /// needs to be removed, we need to turn it into a plain <c>out</c> parameter, so that /// it doesn't declare a duplicate variable. /// If the statement has a pattern declaration (such as <c>3 is int i</c>) for a variable /// which needs to be removed, we will annotate it as a conflict, since we don't have /// a better refactoring. /// </summary> private static StatementSyntax FixDeclarationExpressionsAndDeclarationPatterns(StatementSyntax statement, HashSet<SyntaxAnnotation> variablesToRemove) { var replacements = new Dictionary<SyntaxNode, SyntaxNode>(); var declarations = statement.DescendantNodes() .Where(n => n.IsKind(SyntaxKind.DeclarationExpression, SyntaxKind.DeclarationPattern)); foreach (var node in declarations) { switch (node.Kind()) { case SyntaxKind.DeclarationExpression: { var declaration = (DeclarationExpressionSyntax)node; if (declaration.Designation.Kind() != SyntaxKind.SingleVariableDesignation) { break; } var designation = (SingleVariableDesignationSyntax)declaration.Designation; var name = designation.Identifier.ValueText; if (variablesToRemove.HasSyntaxAnnotation(designation)) { var newLeadingTrivia = new SyntaxTriviaList(); newLeadingTrivia = newLeadingTrivia.AddRange(declaration.Type.GetLeadingTrivia()); newLeadingTrivia = newLeadingTrivia.AddRange(declaration.Type.GetTrailingTrivia()); newLeadingTrivia = newLeadingTrivia.AddRange(designation.GetLeadingTrivia()); replacements.Add(declaration, SyntaxFactory.IdentifierName(designation.Identifier) .WithLeadingTrivia(newLeadingTrivia)); } break; } case SyntaxKind.DeclarationPattern: { var pattern = (DeclarationPatternSyntax)node; if (!variablesToRemove.HasSyntaxAnnotation(pattern)) { break; } // We don't have a good refactoring for this, so we just annotate the conflict // For instance, when a local declared by a pattern declaration (`3 is int i`) is // used outside the block we're trying to extract. if (pattern.Designation is not SingleVariableDesignationSyntax designation) { break; } var identifier = designation.Identifier; var annotation = ConflictAnnotation.Create(CSharpFeaturesResources.Conflict_s_detected); var newIdentifier = identifier.WithAdditionalAnnotations(annotation); var newDesignation = designation.WithIdentifier(newIdentifier); replacements.Add(pattern, pattern.WithDesignation(newDesignation)); break; } } } return statement.ReplaceNodes(replacements.Keys, (orig, partiallyReplaced) => replacements[orig]); } private static SyntaxToken ApplyTriviaFromDeclarationToAssignmentIdentifier(LocalDeclarationStatementSyntax declarationStatement, bool firstVariableToAttachTrivia, VariableDeclaratorSyntax variable) { var identifier = variable.Identifier; var typeSyntax = declarationStatement.Declaration.Type; if (firstVariableToAttachTrivia && typeSyntax != null) { var identifierLeadingTrivia = new SyntaxTriviaList(); if (typeSyntax.HasLeadingTrivia) { identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetLeadingTrivia()); } identifierLeadingTrivia = identifierLeadingTrivia.AddRange(identifier.LeadingTrivia); identifier = identifier.WithLeadingTrivia(identifierLeadingTrivia); } return identifier; } private ImmutableArray<StatementSyntax> SplitOrMoveDeclarationIntoMethodDefinition( ImmutableArray<StatementSyntax> statements, CancellationToken cancellationToken) { var semanticModel = SemanticDocument.SemanticModel; var context = InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var declStatements = CreateDeclarationStatements(AnalyzerResult.GetVariablesToSplitOrMoveIntoMethodDefinition(cancellationToken), cancellationToken); declStatements = postProcessor.MergeDeclarationStatements(declStatements); return declStatements.Concat(statements); } private static ExpressionSyntax CreateAssignmentExpression(SyntaxToken identifier, ExpressionSyntax rvalue) { return SyntaxFactory.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(identifier), rvalue); } protected override bool LastStatementOrHasReturnStatementInReturnableConstruct() { var lastStatement = GetLastStatementOrInitializerSelectedAtCallSite(); var container = lastStatement.GetAncestorsOrThis<SyntaxNode>().FirstOrDefault(n => n.IsReturnableConstruct()); if (container == null) { // case such as field initializer return false; } var blockBody = container.GetBlockBody(); if (blockBody == null) { // such as expression lambda. there is no statement return false; } // check whether it is last statement except return statement var statements = blockBody.Statements; if (statements.Last() == lastStatement) { return true; } var index = statements.IndexOf((StatementSyntax)lastStatement); return statements[index + 1].Kind() == SyntaxKind.ReturnStatement; } protected override SyntaxToken CreateIdentifier(string name) => SyntaxFactory.Identifier(name); protected override StatementSyntax CreateReturnStatement(string identifierName = null) { return string.IsNullOrEmpty(identifierName) ? SyntaxFactory.ReturnStatement() : SyntaxFactory.ReturnStatement(SyntaxFactory.IdentifierName(identifierName)); } protected override ExpressionSyntax CreateCallSignature() { var methodName = CreateMethodNameForInvocation().WithAdditionalAnnotations(Simplifier.Annotation); var arguments = new List<ArgumentSyntax>(); var isLocalFunction = LocalFunction && ShouldLocalFunctionCaptureParameter(SemanticDocument.Root); foreach (var argument in AnalyzerResult.MethodParameters) { if (!isLocalFunction || !argument.CanBeCapturedByLocalFunction) { var modifier = GetParameterRefSyntaxKind(argument.ParameterModifier); var refOrOut = modifier == SyntaxKind.None ? default : SyntaxFactory.Token(modifier); arguments.Add(SyntaxFactory.Argument(SyntaxFactory.IdentifierName(argument.Name)).WithRefOrOutKeyword(refOrOut)); } } var invocation = SyntaxFactory.InvocationExpression(methodName, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments))); var shouldPutAsyncModifier = CSharpSelectionResult.ShouldPutAsyncModifier(); if (!shouldPutAsyncModifier) { return invocation; } if (CSharpSelectionResult.ShouldCallConfigureAwaitFalse()) { if (AnalyzerResult.ReturnType.GetMembers().Any(x => x is IMethodSymbol { Name: nameof(Task.ConfigureAwait), Parameters: { Length: 1 } parameters } && parameters[0].Type.SpecialType == SpecialType.System_Boolean)) { invocation = SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, invocation, SyntaxFactory.IdentifierName(nameof(Task.ConfigureAwait))), SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Argument(SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression))))); } } return SyntaxFactory.AwaitExpression(invocation); } protected override StatementSyntax CreateAssignmentExpressionStatement(SyntaxToken identifier, ExpressionSyntax rvalue) => SyntaxFactory.ExpressionStatement(CreateAssignmentExpression(identifier, rvalue)); protected override StatementSyntax CreateDeclarationStatement( VariableInfo variable, ExpressionSyntax initialValue, CancellationToken cancellationToken) { var type = variable.GetVariableType(SemanticDocument); var typeNode = type.GenerateTypeSyntax(); var equalsValueClause = initialValue == null ? null : SyntaxFactory.EqualsValueClause(value: initialValue); return SyntaxFactory.LocalDeclarationStatement( SyntaxFactory.VariableDeclaration(typeNode) .AddVariables(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(variable.Name)).WithInitializer(equalsValueClause))); } protected override async Task<GeneratedCode> CreateGeneratedCodeAsync(OperationStatus status, SemanticDocument newDocument, CancellationToken cancellationToken) { if (status.Succeeded()) { // in hybrid code cases such as extract method, formatter will have some difficulties on where it breaks lines in two. // here, we explicitly insert newline at the end of "{" of auto generated method decl so that anchor knows how to find out // indentation of inserted statements (from users code) with user code style preserved var root = newDocument.Root; var methodDefinition = root.GetAnnotatedNodes<SyntaxNode>(MethodDefinitionAnnotation).First(); #pragma warning disable IDE0007 // Use implicit type (False positive: https://github.com/dotnet/roslyn/issues/44507) SyntaxNode newMethodDefinition = methodDefinition switch #pragma warning restore IDE0007 // Use implicit type { MethodDeclarationSyntax method => TweakNewLinesInMethod(method), LocalFunctionStatementSyntax localFunction => TweakNewLinesInMethod(localFunction), _ => throw new NotSupportedException("SyntaxNode expected to be MethodDeclarationSyntax or LocalFunctionStatementSyntax."), }; newDocument = await newDocument.WithSyntaxRootAsync( root.ReplaceNode(methodDefinition, newMethodDefinition), cancellationToken).ConfigureAwait(false); } return await base.CreateGeneratedCodeAsync(status, newDocument, cancellationToken).ConfigureAwait(false); } private static MethodDeclarationSyntax TweakNewLinesInMethod(MethodDeclarationSyntax method) => TweakNewLinesInMethod(method, method.Body, method.ExpressionBody); private static LocalFunctionStatementSyntax TweakNewLinesInMethod(LocalFunctionStatementSyntax method) => TweakNewLinesInMethod(method, method.Body, method.ExpressionBody); private static TDeclarationNode TweakNewLinesInMethod<TDeclarationNode>(TDeclarationNode method, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody) where TDeclarationNode : SyntaxNode { if (body != null) { return method.ReplaceToken( body.OpenBraceToken, body.OpenBraceToken.WithAppendedTrailingTrivia( SpecializedCollections.SingletonEnumerable(SyntaxFactory.ElasticCarriageReturnLineFeed))); } else if (expressionBody != null) { return method.ReplaceToken( expressionBody.ArrowToken, expressionBody.ArrowToken.WithPrependedLeadingTrivia( SpecializedCollections.SingletonEnumerable(SyntaxFactory.ElasticCarriageReturnLineFeed))); } else { return method; } } protected StatementSyntax GetStatementContainingInvocationToExtractedMethodWorker() { var callSignature = CreateCallSignature(); if (AnalyzerResult.HasReturnType) { Contract.ThrowIfTrue(AnalyzerResult.HasVariableToUseAsReturnValue); return SyntaxFactory.ReturnStatement(callSignature); } return SyntaxFactory.ExpressionStatement(callSignature); } protected override async Task<SemanticDocument> UpdateMethodAfterGenerationAsync( SemanticDocument originalDocument, OperationStatus<IMethodSymbol> methodSymbolResult, CancellationToken cancellationToken) { // Only need to update for nullable reference types in return if (methodSymbolResult.Data.ReturnType.NullableAnnotation != NullableAnnotation.Annotated) { return await base.UpdateMethodAfterGenerationAsync(originalDocument, methodSymbolResult, cancellationToken).ConfigureAwait(false); } var syntaxNode = originalDocument.Root.GetAnnotatedNodesAndTokens(MethodDefinitionAnnotation).FirstOrDefault().AsNode(); var nodeIsMethodOrLocalFunction = syntaxNode is MethodDeclarationSyntax || syntaxNode is LocalFunctionStatementSyntax; if (!nodeIsMethodOrLocalFunction) { return await base.UpdateMethodAfterGenerationAsync(originalDocument, methodSymbolResult, cancellationToken).ConfigureAwait(false); } var nullableReturnOperations = await CheckReturnOperations(syntaxNode, methodSymbolResult, originalDocument, cancellationToken).ConfigureAwait(false); if (nullableReturnOperations is object) { return nullableReturnOperations; } var returnType = syntaxNode is MethodDeclarationSyntax method ? method.ReturnType : ((LocalFunctionStatementSyntax)syntaxNode).ReturnType; var newDocument = await GenerateNewDocument(methodSymbolResult, returnType, originalDocument, cancellationToken).ConfigureAwait(false); return await SemanticDocument.CreateAsync(newDocument, cancellationToken).ConfigureAwait(false); static bool ReturnOperationBelongsToMethod(SyntaxNode returnOperationSyntax, SyntaxNode methodSyntax) { var enclosingMethod = returnOperationSyntax.FirstAncestorOrSelf<SyntaxNode>(n => n switch { BaseMethodDeclarationSyntax _ => true, AnonymousFunctionExpressionSyntax _ => true, LocalFunctionStatementSyntax _ => true, _ => false }); return enclosingMethod == methodSyntax; } async Task<SemanticDocument> CheckReturnOperations( SyntaxNode node, OperationStatus<IMethodSymbol> methodSymbolResult, SemanticDocument originalDocument, CancellationToken cancellationToken) { var semanticModel = originalDocument.SemanticModel; var methodOperation = semanticModel.GetOperation(node, cancellationToken); var returnOperations = methodOperation.DescendantsAndSelf().OfType<IReturnOperation>(); foreach (var returnOperation in returnOperations) { // If the return statement is located in a nested local function or lambda it // shouldn't contribute to the nullability of the extracted method's return type if (!ReturnOperationBelongsToMethod(returnOperation.Syntax, methodOperation.Syntax)) { continue; } var syntax = returnOperation.ReturnedValue?.Syntax ?? returnOperation.Syntax; var returnTypeInfo = semanticModel.GetTypeInfo(syntax, cancellationToken); if (returnTypeInfo.Nullability.FlowState == NullableFlowState.MaybeNull) { // Flow state shows that return is correctly nullable return await base.UpdateMethodAfterGenerationAsync(originalDocument, methodSymbolResult, cancellationToken).ConfigureAwait(false); } } return null; } static async Task<Document> GenerateNewDocument( OperationStatus<IMethodSymbol> methodSymbolResult, TypeSyntax returnType, SemanticDocument originalDocument, CancellationToken cancellationToken) { // Return type can be updated to not be null var newType = methodSymbolResult.Data.ReturnType.WithNullableAnnotation(NullableAnnotation.NotAnnotated); var oldRoot = await originalDocument.Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newRoot = oldRoot.ReplaceNode(returnType, newType.GenerateTypeSyntax()); return originalDocument.Document.WithSyntaxRoot(newRoot); } } protected SyntaxToken GenerateMethodNameForStatementGenerators() { var semanticModel = SemanticDocument.SemanticModel; var nameGenerator = new UniqueNameGenerator(semanticModel); var scope = CSharpSelectionResult.GetContainingScope(); // If extracting a local function, we want to ensure all local variables are considered when generating a unique name. if (LocalFunction) { scope = CSharpSelectionResult.GetFirstTokenInSelection().Parent; } return SyntaxFactory.Identifier(nameGenerator.CreateUniqueMethodName(scope, GenerateMethodNameFromUserPreference())); } protected string GenerateMethodNameFromUserPreference() { var methodName = NewMethodPascalCaseStr; if (!LocalFunction) { return methodName; } // For local functions, pascal case and camel case should be the most common and therefore we only consider those cases. var namingPreferences = Options.GetOption(NamingStyleOptions.NamingPreferences, LanguageNames.CSharp); var localFunctionPreferences = namingPreferences.SymbolSpecifications.Where(symbol => symbol.AppliesTo(new SymbolKindOrTypeKind(MethodKind.LocalFunction), CreateMethodModifiers(), null)); var namingRules = namingPreferences.Rules.NamingRules; var localFunctionKind = new SymbolKindOrTypeKind(MethodKind.LocalFunction); if (LocalFunction) { if (namingRules.Any(rule => rule.NamingStyle.CapitalizationScheme.Equals(Capitalization.CamelCase) && rule.SymbolSpecification.AppliesTo(localFunctionKind, CreateMethodModifiers(), null))) { methodName = NewMethodCamelCaseStr; } } // We default to pascal case. return methodName; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable 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.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpMethodExtractor { private abstract partial class CSharpCodeGenerator : CodeGenerator<StatementSyntax, ExpressionSyntax, SyntaxNode> { private readonly SyntaxToken _methodName; private const string NewMethodPascalCaseStr = "NewMethod"; private const string NewMethodCamelCaseStr = "newMethod"; public static Task<GeneratedCode> GenerateAsync( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction, CancellationToken cancellationToken) { var codeGenerator = Create(insertionPoint, selectionResult, analyzerResult, options, localFunction); return codeGenerator.GenerateAsync(cancellationToken); } private static CSharpCodeGenerator Create( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction) { if (ExpressionCodeGenerator.IsExtractMethodOnExpression(selectionResult)) { return new ExpressionCodeGenerator(insertionPoint, selectionResult, analyzerResult, options, localFunction); } if (SingleStatementCodeGenerator.IsExtractMethodOnSingleStatement(selectionResult)) { return new SingleStatementCodeGenerator(insertionPoint, selectionResult, analyzerResult, options, localFunction); } if (MultipleStatementsCodeGenerator.IsExtractMethodOnMultipleStatements(selectionResult)) { return new MultipleStatementsCodeGenerator(insertionPoint, selectionResult, analyzerResult, options, localFunction); } throw ExceptionUtilities.UnexpectedValue(selectionResult); } protected CSharpCodeGenerator( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction) : base(insertionPoint, selectionResult, analyzerResult, options, localFunction) { Contract.ThrowIfFalse(SemanticDocument == selectionResult.SemanticDocument); var nameToken = CreateMethodName(); _methodName = nameToken.WithAdditionalAnnotations(MethodNameAnnotation); } private CSharpSelectionResult CSharpSelectionResult { get { return (CSharpSelectionResult)SelectionResult; } } protected override SyntaxNode GetPreviousMember(SemanticDocument document) { var node = InsertionPoint.With(document).GetContext(); return (node.Parent is GlobalStatementSyntax) ? node.Parent : node; } protected override OperationStatus<IMethodSymbol> GenerateMethodDefinition(bool localFunction, CancellationToken cancellationToken) { var result = CreateMethodBody(cancellationToken); var methodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Private, modifiers: CreateMethodModifiers(), returnType: AnalyzerResult.ReturnType, refKind: RefKind.None, explicitInterfaceImplementations: default, name: _methodName.ToString(), typeParameters: CreateMethodTypeParameters(), parameters: CreateMethodParameters(), statements: result.Data, methodKind: localFunction ? MethodKind.LocalFunction : MethodKind.Ordinary); return result.With( MethodDefinitionAnnotation.AddAnnotationToSymbol( Formatter.Annotation.AddAnnotationToSymbol(methodSymbol))); } protected override async Task<SyntaxNode> GenerateBodyForCallSiteContainerAsync(CancellationToken cancellationToken) { var container = GetOutermostCallSiteContainerToProcess(cancellationToken); var variableMapToRemove = CreateVariableDeclarationToRemoveMap( AnalyzerResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken), cancellationToken); var firstStatementToRemove = GetFirstStatementOrInitializerSelectedAtCallSite(); var lastStatementToRemove = GetLastStatementOrInitializerSelectedAtCallSite(); Contract.ThrowIfFalse(firstStatementToRemove.Parent == lastStatementToRemove.Parent); var statementsToInsert = await CreateStatementsOrInitializerToInsertAtCallSiteAsync(cancellationToken).ConfigureAwait(false); var callSiteGenerator = new CallSiteContainerRewriter( container, variableMapToRemove, firstStatementToRemove, lastStatementToRemove, statementsToInsert); return container.CopyAnnotationsTo(callSiteGenerator.Generate()).WithAdditionalAnnotations(Formatter.Annotation); } private async Task<ImmutableArray<SyntaxNode>> CreateStatementsOrInitializerToInsertAtCallSiteAsync(CancellationToken cancellationToken) { var selectedNode = GetFirstStatementOrInitializerSelectedAtCallSite(); // field initializer, constructor initializer, expression bodied member case if (selectedNode is ConstructorInitializerSyntax || selectedNode is FieldDeclarationSyntax || IsExpressionBodiedMember(selectedNode) || IsExpressionBodiedAccessor(selectedNode)) { var statement = await GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(cancellationToken).ConfigureAwait(false); return ImmutableArray.Create(statement); } // regular case var semanticModel = SemanticDocument.SemanticModel; var context = InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var statements = AddSplitOrMoveDeclarationOutStatementsToCallSite(cancellationToken); statements = postProcessor.MergeDeclarationStatements(statements); statements = AddAssignmentStatementToCallSite(statements, cancellationToken); statements = await AddInvocationAtCallSiteAsync(statements, cancellationToken).ConfigureAwait(false); statements = AddReturnIfUnreachable(statements); return statements.CastArray<SyntaxNode>(); } protected override bool ShouldLocalFunctionCaptureParameter(SyntaxNode node) => ((CSharpParseOptions)node.SyntaxTree.Options).LanguageVersion < LanguageVersion.CSharp8; private static bool IsExpressionBodiedMember(SyntaxNode node) => node is MemberDeclarationSyntax member && member.GetExpressionBody() != null; private static bool IsExpressionBodiedAccessor(SyntaxNode node) => node is AccessorDeclarationSyntax accessor && accessor.ExpressionBody != null; private SimpleNameSyntax CreateMethodNameForInvocation() { return AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0 ? (SimpleNameSyntax)SyntaxFactory.IdentifierName(_methodName) : SyntaxFactory.GenericName(_methodName, SyntaxFactory.TypeArgumentList(CreateMethodCallTypeVariables())); } private SeparatedSyntaxList<TypeSyntax> CreateMethodCallTypeVariables() { Contract.ThrowIfTrue(AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0); // propagate any type variable used in extracted code var typeVariables = new List<TypeSyntax>(); foreach (var methodTypeParameter in AnalyzerResult.MethodTypeParametersInDeclaration) { typeVariables.Add(SyntaxFactory.ParseTypeName(methodTypeParameter.Name)); } return SyntaxFactory.SeparatedList(typeVariables); } protected SyntaxNode GetCallSiteContainerFromOutermostMoveInVariable(CancellationToken cancellationToken) { var outmostVariable = GetOutermostVariableToMoveIntoMethodDefinition(cancellationToken); if (outmostVariable == null) { return null; } var idToken = outmostVariable.GetIdentifierTokenAtDeclaration(SemanticDocument); var declStatement = idToken.GetAncestor<LocalDeclarationStatementSyntax>(); Contract.ThrowIfNull(declStatement); Contract.ThrowIfFalse(declStatement.Parent.IsStatementContainerNode()); return declStatement.Parent; } private DeclarationModifiers CreateMethodModifiers() { var isUnsafe = CSharpSelectionResult.ShouldPutUnsafeModifier(); var isAsync = CSharpSelectionResult.ShouldPutAsyncModifier(); var isStatic = !AnalyzerResult.UseInstanceMember; var isReadOnly = AnalyzerResult.ShouldBeReadOnly; // Static local functions are only supported in C# 8.0 and later var languageVersion = ((CSharpParseOptions)SemanticDocument.SyntaxTree.Options).LanguageVersion; if (LocalFunction && (!Options.GetOption(CSharpCodeStyleOptions.PreferStaticLocalFunction).Value || languageVersion < LanguageVersion.CSharp8)) { isStatic = false; } return new DeclarationModifiers( isUnsafe: isUnsafe, isAsync: isAsync, isStatic: isStatic, isReadOnly: isReadOnly); } private static SyntaxKind GetParameterRefSyntaxKind(ParameterBehavior parameterBehavior) { return parameterBehavior == ParameterBehavior.Ref ? SyntaxKind.RefKeyword : parameterBehavior == ParameterBehavior.Out ? SyntaxKind.OutKeyword : SyntaxKind.None; } private OperationStatus<ImmutableArray<SyntaxNode>> CreateMethodBody(CancellationToken cancellationToken) { var statements = GetInitialStatementsForMethodDefinitions(); statements = SplitOrMoveDeclarationIntoMethodDefinition(statements, cancellationToken); statements = MoveDeclarationOutFromMethodDefinition(statements, cancellationToken); statements = AppendReturnStatementIfNeeded(statements); statements = CleanupCode(statements); // set output so that we can use it in negative preview var wrapped = WrapInCheckStatementIfNeeded(statements); return CheckActiveStatements(statements).With(wrapped.ToImmutableArray<SyntaxNode>()); } private IEnumerable<StatementSyntax> WrapInCheckStatementIfNeeded(IEnumerable<StatementSyntax> statements) { var kind = CSharpSelectionResult.UnderCheckedStatementContext(); if (kind == SyntaxKind.None) { return statements; } if (statements.Skip(1).Any()) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))); } if (statements.Single() is BlockSyntax block) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, block)); } return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))); } private static ImmutableArray<StatementSyntax> CleanupCode(ImmutableArray<StatementSyntax> statements) { statements = PostProcessor.RemoveRedundantBlock(statements); statements = PostProcessor.RemoveDeclarationAssignmentPattern(statements); statements = PostProcessor.RemoveInitializedDeclarationAndReturnPattern(statements); return statements; } private static OperationStatus CheckActiveStatements(IEnumerable<StatementSyntax> statements) { var count = statements.Count(); if (count == 0) { return OperationStatus.NoActiveStatement; } if (count == 1) { if (statements.Single() is ReturnStatementSyntax returnStatement && returnStatement.Expression == null) { return OperationStatus.NoActiveStatement; } } foreach (var statement in statements) { if (statement is not LocalDeclarationStatementSyntax declStatement) { return OperationStatus.Succeeded; } foreach (var variable in declStatement.Declaration.Variables) { if (variable.Initializer != null) { // found one return OperationStatus.Succeeded; } } } return OperationStatus.NoActiveStatement; } private ImmutableArray<StatementSyntax> MoveDeclarationOutFromMethodDefinition( ImmutableArray<StatementSyntax> statements, CancellationToken cancellationToken) { using var _ = ArrayBuilder<StatementSyntax>.GetInstance(out var result); var variableToRemoveMap = CreateVariableDeclarationToRemoveMap( AnalyzerResult.GetVariablesToMoveOutToCallSiteOrDelete(cancellationToken), cancellationToken); statements = statements.SelectAsArray(s => FixDeclarationExpressionsAndDeclarationPatterns(s, variableToRemoveMap)); foreach (var statement in statements) { if (statement is not LocalDeclarationStatementSyntax declarationStatement || declarationStatement.Declaration.Variables.FullSpan.IsEmpty) { // if given statement is not decl statement. result.Add(statement); continue; } var expressionStatements = new List<StatementSyntax>(); var list = new List<VariableDeclaratorSyntax>(); var triviaList = new List<SyntaxTrivia>(); // When we modify the declaration to an initialization we have to preserve the leading trivia var firstVariableToAttachTrivia = true; // go through each var decls in decl statement, and create new assignment if // variable is initialized at decl. foreach (var variableDeclaration in declarationStatement.Declaration.Variables) { if (variableToRemoveMap.HasSyntaxAnnotation(variableDeclaration)) { if (variableDeclaration.Initializer != null) { var identifier = ApplyTriviaFromDeclarationToAssignmentIdentifier(declarationStatement, firstVariableToAttachTrivia, variableDeclaration); // move comments with the variable here expressionStatements.Add(CreateAssignmentExpressionStatement(identifier, variableDeclaration.Initializer.Value)); } else { // we don't remove trivia around tokens we remove triviaList.AddRange(variableDeclaration.GetLeadingTrivia()); triviaList.AddRange(variableDeclaration.GetTrailingTrivia()); } firstVariableToAttachTrivia = false; continue; } // Prepend the trivia from the declarations without initialization to the next persisting variable declaration if (triviaList.Count > 0) { list.Add(variableDeclaration.WithPrependedLeadingTrivia(triviaList)); triviaList.Clear(); firstVariableToAttachTrivia = false; continue; } firstVariableToAttachTrivia = false; list.Add(variableDeclaration); } if (list.Count == 0 && triviaList.Count > 0) { // well, there are trivia associated with the node. // we can't just delete the node since then, we will lose // the trivia. unfortunately, it is not easy to attach the trivia // to next token. for now, create an empty statement and associate the // trivia to the statement // TODO : think about a way to trivia attached to next token result.Add(SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxFactory.TriviaList(triviaList), SyntaxKind.SemicolonToken, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)))); triviaList.Clear(); } // return survived var decls if (list.Count > 0) { result.Add(SyntaxFactory.LocalDeclarationStatement( declarationStatement.Modifiers, SyntaxFactory.VariableDeclaration( declarationStatement.Declaration.Type, SyntaxFactory.SeparatedList(list)), declarationStatement.SemicolonToken.WithPrependedLeadingTrivia(triviaList))); triviaList.Clear(); } // return any expression statement if there was any result.AddRange(expressionStatements); } return result.ToImmutable(); } /// <summary> /// If the statement has an <c>out var</c> declaration expression for a variable which /// needs to be removed, we need to turn it into a plain <c>out</c> parameter, so that /// it doesn't declare a duplicate variable. /// If the statement has a pattern declaration (such as <c>3 is int i</c>) for a variable /// which needs to be removed, we will annotate it as a conflict, since we don't have /// a better refactoring. /// </summary> private static StatementSyntax FixDeclarationExpressionsAndDeclarationPatterns(StatementSyntax statement, HashSet<SyntaxAnnotation> variablesToRemove) { var replacements = new Dictionary<SyntaxNode, SyntaxNode>(); var declarations = statement.DescendantNodes() .Where(n => n.IsKind(SyntaxKind.DeclarationExpression, SyntaxKind.DeclarationPattern)); foreach (var node in declarations) { switch (node.Kind()) { case SyntaxKind.DeclarationExpression: { var declaration = (DeclarationExpressionSyntax)node; if (declaration.Designation.Kind() != SyntaxKind.SingleVariableDesignation) { break; } var designation = (SingleVariableDesignationSyntax)declaration.Designation; var name = designation.Identifier.ValueText; if (variablesToRemove.HasSyntaxAnnotation(designation)) { var newLeadingTrivia = new SyntaxTriviaList(); newLeadingTrivia = newLeadingTrivia.AddRange(declaration.Type.GetLeadingTrivia()); newLeadingTrivia = newLeadingTrivia.AddRange(declaration.Type.GetTrailingTrivia()); newLeadingTrivia = newLeadingTrivia.AddRange(designation.GetLeadingTrivia()); replacements.Add(declaration, SyntaxFactory.IdentifierName(designation.Identifier) .WithLeadingTrivia(newLeadingTrivia)); } break; } case SyntaxKind.DeclarationPattern: { var pattern = (DeclarationPatternSyntax)node; if (!variablesToRemove.HasSyntaxAnnotation(pattern)) { break; } // We don't have a good refactoring for this, so we just annotate the conflict // For instance, when a local declared by a pattern declaration (`3 is int i`) is // used outside the block we're trying to extract. if (pattern.Designation is not SingleVariableDesignationSyntax designation) { break; } var identifier = designation.Identifier; var annotation = ConflictAnnotation.Create(CSharpFeaturesResources.Conflict_s_detected); var newIdentifier = identifier.WithAdditionalAnnotations(annotation); var newDesignation = designation.WithIdentifier(newIdentifier); replacements.Add(pattern, pattern.WithDesignation(newDesignation)); break; } } } return statement.ReplaceNodes(replacements.Keys, (orig, partiallyReplaced) => replacements[orig]); } private static SyntaxToken ApplyTriviaFromDeclarationToAssignmentIdentifier(LocalDeclarationStatementSyntax declarationStatement, bool firstVariableToAttachTrivia, VariableDeclaratorSyntax variable) { var identifier = variable.Identifier; var typeSyntax = declarationStatement.Declaration.Type; if (firstVariableToAttachTrivia && typeSyntax != null) { var identifierLeadingTrivia = new SyntaxTriviaList(); if (typeSyntax.HasLeadingTrivia) { identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetLeadingTrivia()); } identifierLeadingTrivia = identifierLeadingTrivia.AddRange(identifier.LeadingTrivia); identifier = identifier.WithLeadingTrivia(identifierLeadingTrivia); } return identifier; } private ImmutableArray<StatementSyntax> SplitOrMoveDeclarationIntoMethodDefinition( ImmutableArray<StatementSyntax> statements, CancellationToken cancellationToken) { var semanticModel = SemanticDocument.SemanticModel; var context = InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var declStatements = CreateDeclarationStatements(AnalyzerResult.GetVariablesToSplitOrMoveIntoMethodDefinition(cancellationToken), cancellationToken); declStatements = postProcessor.MergeDeclarationStatements(declStatements); return declStatements.Concat(statements); } private static ExpressionSyntax CreateAssignmentExpression(SyntaxToken identifier, ExpressionSyntax rvalue) { return SyntaxFactory.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(identifier), rvalue); } protected override bool LastStatementOrHasReturnStatementInReturnableConstruct() { var lastStatement = GetLastStatementOrInitializerSelectedAtCallSite(); var container = lastStatement.GetAncestorsOrThis<SyntaxNode>().FirstOrDefault(n => n.IsReturnableConstruct()); if (container == null) { // case such as field initializer return false; } var blockBody = container.GetBlockBody(); if (blockBody == null) { // such as expression lambda. there is no statement return false; } // check whether it is last statement except return statement var statements = blockBody.Statements; if (statements.Last() == lastStatement) { return true; } var index = statements.IndexOf((StatementSyntax)lastStatement); return statements[index + 1].Kind() == SyntaxKind.ReturnStatement; } protected override SyntaxToken CreateIdentifier(string name) => SyntaxFactory.Identifier(name); protected override StatementSyntax CreateReturnStatement(string identifierName = null) { return string.IsNullOrEmpty(identifierName) ? SyntaxFactory.ReturnStatement() : SyntaxFactory.ReturnStatement(SyntaxFactory.IdentifierName(identifierName)); } protected override ExpressionSyntax CreateCallSignature() { var methodName = CreateMethodNameForInvocation().WithAdditionalAnnotations(Simplifier.Annotation); var arguments = new List<ArgumentSyntax>(); var isLocalFunction = LocalFunction && ShouldLocalFunctionCaptureParameter(SemanticDocument.Root); foreach (var argument in AnalyzerResult.MethodParameters) { if (!isLocalFunction || !argument.CanBeCapturedByLocalFunction) { var modifier = GetParameterRefSyntaxKind(argument.ParameterModifier); var refOrOut = modifier == SyntaxKind.None ? default : SyntaxFactory.Token(modifier); arguments.Add(SyntaxFactory.Argument(SyntaxFactory.IdentifierName(argument.Name)).WithRefOrOutKeyword(refOrOut)); } } var invocation = SyntaxFactory.InvocationExpression(methodName, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments))); var shouldPutAsyncModifier = CSharpSelectionResult.ShouldPutAsyncModifier(); if (!shouldPutAsyncModifier) { return invocation; } if (CSharpSelectionResult.ShouldCallConfigureAwaitFalse()) { if (AnalyzerResult.ReturnType.GetMembers().Any(x => x is IMethodSymbol { Name: nameof(Task.ConfigureAwait), Parameters: { Length: 1 } parameters } && parameters[0].Type.SpecialType == SpecialType.System_Boolean)) { invocation = SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, invocation, SyntaxFactory.IdentifierName(nameof(Task.ConfigureAwait))), SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Argument(SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression))))); } } return SyntaxFactory.AwaitExpression(invocation); } protected override StatementSyntax CreateAssignmentExpressionStatement(SyntaxToken identifier, ExpressionSyntax rvalue) => SyntaxFactory.ExpressionStatement(CreateAssignmentExpression(identifier, rvalue)); protected override StatementSyntax CreateDeclarationStatement( VariableInfo variable, ExpressionSyntax initialValue, CancellationToken cancellationToken) { var type = variable.GetVariableType(SemanticDocument); var typeNode = type.GenerateTypeSyntax(); var equalsValueClause = initialValue == null ? null : SyntaxFactory.EqualsValueClause(value: initialValue); return SyntaxFactory.LocalDeclarationStatement( SyntaxFactory.VariableDeclaration(typeNode) .AddVariables(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(variable.Name)).WithInitializer(equalsValueClause))); } protected override async Task<GeneratedCode> CreateGeneratedCodeAsync(OperationStatus status, SemanticDocument newDocument, CancellationToken cancellationToken) { if (status.Succeeded()) { // in hybrid code cases such as extract method, formatter will have some difficulties on where it breaks lines in two. // here, we explicitly insert newline at the end of "{" of auto generated method decl so that anchor knows how to find out // indentation of inserted statements (from users code) with user code style preserved var root = newDocument.Root; var methodDefinition = root.GetAnnotatedNodes<SyntaxNode>(MethodDefinitionAnnotation).First(); #pragma warning disable IDE0007 // Use implicit type (False positive: https://github.com/dotnet/roslyn/issues/44507) SyntaxNode newMethodDefinition = methodDefinition switch #pragma warning restore IDE0007 // Use implicit type { MethodDeclarationSyntax method => TweakNewLinesInMethod(method), LocalFunctionStatementSyntax localFunction => TweakNewLinesInMethod(localFunction), _ => throw new NotSupportedException("SyntaxNode expected to be MethodDeclarationSyntax or LocalFunctionStatementSyntax."), }; newDocument = await newDocument.WithSyntaxRootAsync( root.ReplaceNode(methodDefinition, newMethodDefinition), cancellationToken).ConfigureAwait(false); } return await base.CreateGeneratedCodeAsync(status, newDocument, cancellationToken).ConfigureAwait(false); } private static MethodDeclarationSyntax TweakNewLinesInMethod(MethodDeclarationSyntax method) => TweakNewLinesInMethod(method, method.Body, method.ExpressionBody); private static LocalFunctionStatementSyntax TweakNewLinesInMethod(LocalFunctionStatementSyntax method) => TweakNewLinesInMethod(method, method.Body, method.ExpressionBody); private static TDeclarationNode TweakNewLinesInMethod<TDeclarationNode>(TDeclarationNode method, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody) where TDeclarationNode : SyntaxNode { if (body != null) { return method.ReplaceToken( body.OpenBraceToken, body.OpenBraceToken.WithAppendedTrailingTrivia( SpecializedCollections.SingletonEnumerable(SyntaxFactory.ElasticCarriageReturnLineFeed))); } else if (expressionBody != null) { return method.ReplaceToken( expressionBody.ArrowToken, expressionBody.ArrowToken.WithPrependedLeadingTrivia( SpecializedCollections.SingletonEnumerable(SyntaxFactory.ElasticCarriageReturnLineFeed))); } else { return method; } } protected StatementSyntax GetStatementContainingInvocationToExtractedMethodWorker() { var callSignature = CreateCallSignature(); if (AnalyzerResult.HasReturnType) { Contract.ThrowIfTrue(AnalyzerResult.HasVariableToUseAsReturnValue); return SyntaxFactory.ReturnStatement(callSignature); } return SyntaxFactory.ExpressionStatement(callSignature); } protected override async Task<SemanticDocument> UpdateMethodAfterGenerationAsync( SemanticDocument originalDocument, OperationStatus<IMethodSymbol> methodSymbolResult, CancellationToken cancellationToken) { // Only need to update for nullable reference types in return if (methodSymbolResult.Data.ReturnType.NullableAnnotation != NullableAnnotation.Annotated) { return await base.UpdateMethodAfterGenerationAsync(originalDocument, methodSymbolResult, cancellationToken).ConfigureAwait(false); } var syntaxNode = originalDocument.Root.GetAnnotatedNodesAndTokens(MethodDefinitionAnnotation).FirstOrDefault().AsNode(); var nodeIsMethodOrLocalFunction = syntaxNode is MethodDeclarationSyntax || syntaxNode is LocalFunctionStatementSyntax; if (!nodeIsMethodOrLocalFunction) { return await base.UpdateMethodAfterGenerationAsync(originalDocument, methodSymbolResult, cancellationToken).ConfigureAwait(false); } var nullableReturnOperations = await CheckReturnOperations(syntaxNode, methodSymbolResult, originalDocument, cancellationToken).ConfigureAwait(false); if (nullableReturnOperations is object) { return nullableReturnOperations; } var returnType = syntaxNode is MethodDeclarationSyntax method ? method.ReturnType : ((LocalFunctionStatementSyntax)syntaxNode).ReturnType; var newDocument = await GenerateNewDocument(methodSymbolResult, returnType, originalDocument, cancellationToken).ConfigureAwait(false); return await SemanticDocument.CreateAsync(newDocument, cancellationToken).ConfigureAwait(false); static bool ReturnOperationBelongsToMethod(SyntaxNode returnOperationSyntax, SyntaxNode methodSyntax) { var enclosingMethod = returnOperationSyntax.FirstAncestorOrSelf<SyntaxNode>(n => n switch { BaseMethodDeclarationSyntax _ => true, AnonymousFunctionExpressionSyntax _ => true, LocalFunctionStatementSyntax _ => true, _ => false }); return enclosingMethod == methodSyntax; } async Task<SemanticDocument> CheckReturnOperations( SyntaxNode node, OperationStatus<IMethodSymbol> methodSymbolResult, SemanticDocument originalDocument, CancellationToken cancellationToken) { var semanticModel = originalDocument.SemanticModel; var methodOperation = semanticModel.GetOperation(node, cancellationToken); var returnOperations = methodOperation.DescendantsAndSelf().OfType<IReturnOperation>(); foreach (var returnOperation in returnOperations) { // If the return statement is located in a nested local function or lambda it // shouldn't contribute to the nullability of the extracted method's return type if (!ReturnOperationBelongsToMethod(returnOperation.Syntax, methodOperation.Syntax)) { continue; } var syntax = returnOperation.ReturnedValue?.Syntax ?? returnOperation.Syntax; var returnTypeInfo = semanticModel.GetTypeInfo(syntax, cancellationToken); if (returnTypeInfo.Nullability.FlowState == NullableFlowState.MaybeNull) { // Flow state shows that return is correctly nullable return await base.UpdateMethodAfterGenerationAsync(originalDocument, methodSymbolResult, cancellationToken).ConfigureAwait(false); } } return null; } static async Task<Document> GenerateNewDocument( OperationStatus<IMethodSymbol> methodSymbolResult, TypeSyntax returnType, SemanticDocument originalDocument, CancellationToken cancellationToken) { // Return type can be updated to not be null var newType = methodSymbolResult.Data.ReturnType.WithNullableAnnotation(NullableAnnotation.NotAnnotated); var oldRoot = await originalDocument.Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newRoot = oldRoot.ReplaceNode(returnType, newType.GenerateTypeSyntax()); return originalDocument.Document.WithSyntaxRoot(newRoot); } } protected SyntaxToken GenerateMethodNameForStatementGenerators() { var semanticModel = SemanticDocument.SemanticModel; var nameGenerator = new UniqueNameGenerator(semanticModel); var scope = CSharpSelectionResult.GetContainingScope(); // If extracting a local function, we want to ensure all local variables are considered when generating a unique name. if (LocalFunction) { scope = CSharpSelectionResult.GetFirstTokenInSelection().Parent; } return SyntaxFactory.Identifier(nameGenerator.CreateUniqueMethodName(scope, GenerateMethodNameFromUserPreference())); } protected string GenerateMethodNameFromUserPreference() { var methodName = NewMethodPascalCaseStr; if (!LocalFunction) { return methodName; } // For local functions, pascal case and camel case should be the most common and therefore we only consider those cases. var namingPreferences = Options.GetOption(NamingStyleOptions.NamingPreferences, LanguageNames.CSharp); var localFunctionPreferences = namingPreferences.SymbolSpecifications.Where(symbol => symbol.AppliesTo(new SymbolKindOrTypeKind(MethodKind.LocalFunction), CreateMethodModifiers(), null)); var namingRules = namingPreferences.Rules.NamingRules; var localFunctionKind = new SymbolKindOrTypeKind(MethodKind.LocalFunction); if (LocalFunction) { if (namingRules.Any(rule => rule.NamingStyle.CapitalizationScheme.Equals(Capitalization.CamelCase) && rule.SymbolSpecification.AppliesTo(localFunctionKind, CreateMethodModifiers(), null))) { methodName = NewMethodCamelCaseStr; } } // We default to pascal case. return methodName; } } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/VisualStudio/Core/Def/ID.InteractiveCommands.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.VisualStudio.LanguageServices { internal static partial class ID { internal static class InteractiveCommands { public const int InteractiveToolWindow = 0x0001; public const int ResetInteractiveFromProject = 0x0002; // TODO: Remove pending https://github.com/dotnet/roslyn/issues/8927 . public const int ExecuteInInteractiveWindow = 0x0010C; public const string CSharpInteractiveCommandSetIdString = "1492DB0A-85A2-4E43-BF0D-CE55B89A8CC6"; public static readonly Guid CSharpInteractiveCommandSetId = new(CSharpInteractiveCommandSetIdString); public const string VisualBasicInteractiveCommandSetIdString = "93DF185E-D75B-4FDB-9D47-E90F111971C5"; public static readonly Guid VisualBasicInteractiveCommandSetId = new(VisualBasicInteractiveCommandSetIdString); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.VisualStudio.LanguageServices { internal static partial class ID { internal static class InteractiveCommands { public const int InteractiveToolWindow = 0x0001; public const int ResetInteractiveFromProject = 0x0002; // TODO: Remove pending https://github.com/dotnet/roslyn/issues/8927 . public const int ExecuteInInteractiveWindow = 0x0010C; public const string CSharpInteractiveCommandSetIdString = "1492DB0A-85A2-4E43-BF0D-CE55B89A8CC6"; public static readonly Guid CSharpInteractiveCommandSetId = new(CSharpInteractiveCommandSetIdString); public const string VisualBasicInteractiveCommandSetIdString = "93DF185E-D75B-4FDB-9D47-E90F111971C5"; public static readonly Guid VisualBasicInteractiveCommandSetId = new(VisualBasicInteractiveCommandSetIdString); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/EditorFeatures/Core/Shared/Extensions/ITextViewExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Outlining; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static partial class ITextViewExtensions { /// <summary> /// Collects the content types in the view's buffer graph. /// </summary> public static ISet<IContentType> GetContentTypes(this ITextView textView) { return new HashSet<IContentType>( textView.BufferGraph.GetTextBuffers(_ => true).Select(b => b.ContentType)); } public static bool IsReadOnlyOnSurfaceBuffer(this ITextView textView, SnapshotSpan span) { var spansInView = textView.BufferGraph.MapUpToBuffer(span, SpanTrackingMode.EdgeInclusive, textView.TextBuffer); return spansInView.Any(spanInView => textView.TextBuffer.IsReadOnly(spanInView.Span)); } public static SnapshotPoint? GetCaretPoint(this ITextView textView, ITextBuffer subjectBuffer) { var caret = textView.Caret.Position; return textView.BufferGraph.MapUpOrDownToBuffer(caret.BufferPosition, subjectBuffer); } public static SnapshotPoint? GetCaretPoint(this ITextView textView, Predicate<ITextSnapshot> match) { var caret = textView.Caret.Position; var span = textView.BufferGraph.MapUpOrDownToFirstMatch(new SnapshotSpan(caret.BufferPosition, 0), match); if (span.HasValue) { return span.Value.Start; } else { return null; } } public static VirtualSnapshotPoint? GetVirtualCaretPoint(this ITextView textView, ITextBuffer subjectBuffer) { if (subjectBuffer == textView.TextBuffer) { return textView.Caret.Position.VirtualBufferPosition; } var mappedPoint = textView.BufferGraph.MapDownToBuffer( textView.Caret.Position.VirtualBufferPosition.Position, PointTrackingMode.Negative, subjectBuffer, PositionAffinity.Predecessor); return mappedPoint.HasValue ? new VirtualSnapshotPoint(mappedPoint.Value) : default; } public static ITextBuffer? GetBufferContainingCaret(this ITextView textView, string contentType = ContentTypeNames.RoslynContentType) { var point = GetCaretPoint(textView, s => s.ContentType.IsOfType(contentType)); return point.HasValue ? point.Value.Snapshot.TextBuffer : null; } public static SnapshotPoint? GetPositionInView(this ITextView textView, SnapshotPoint point) => textView.BufferGraph.MapUpToSnapshot(point, PointTrackingMode.Positive, PositionAffinity.Successor, textView.TextSnapshot); public static NormalizedSnapshotSpanCollection GetSpanInView(this ITextView textView, SnapshotSpan span) => textView.BufferGraph.MapUpToSnapshot(span, SpanTrackingMode.EdgeInclusive, textView.TextSnapshot); public static void SetSelection( this ITextView textView, VirtualSnapshotPoint anchorPoint, VirtualSnapshotPoint activePoint) { var isReversed = activePoint < anchorPoint; var start = isReversed ? activePoint : anchorPoint; var end = isReversed ? anchorPoint : activePoint; SetSelection(textView, new SnapshotSpan(start.Position, end.Position), isReversed); } public static void SetSelection( this ITextView textView, SnapshotSpan span, bool isReversed = false) { var spanInView = textView.GetSpanInView(span).Single(); textView.Selection.Select(spanInView, isReversed); textView.Caret.MoveTo(isReversed ? spanInView.Start : spanInView.End); } /// <summary> /// Sets a multi selection with the last span as the primary selection. /// Also maps up to the correct span in view before attempting to set the selection. /// </summary> public static void SetMultiSelection(this ITextView textView, IEnumerable<SnapshotSpan> spans) { var spansInView = spans.Select(s => new Selection(textView.GetSpanInView(s).Single())); textView.GetMultiSelectionBroker().SetSelectionRange(spansInView, spansInView.Last()); } public static bool TryMoveCaretToAndEnsureVisible(this ITextView textView, SnapshotPoint point, IOutliningManagerService? outliningManagerService = null, EnsureSpanVisibleOptions ensureSpanVisibleOptions = EnsureSpanVisibleOptions.None) => textView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(point), outliningManagerService, ensureSpanVisibleOptions); public static bool TryMoveCaretToAndEnsureVisible(this ITextView textView, VirtualSnapshotPoint point, IOutliningManagerService? outliningManagerService = null, EnsureSpanVisibleOptions ensureSpanVisibleOptions = EnsureSpanVisibleOptions.None) { if (textView.IsClosed) { return false; } var pointInView = textView.GetPositionInView(point.Position); if (!pointInView.HasValue) { return false; } // If we were given an outlining service, we need to expand any outlines first, or else // the Caret.MoveTo won't land in the correct location if our target is inside a // collapsed outline. if (outliningManagerService != null) { var outliningManager = outliningManagerService.GetOutliningManager(textView); if (outliningManager != null) { outliningManager.ExpandAll(new SnapshotSpan(pointInView.Value, length: 0), match: _ => true); } } var newPosition = textView.Caret.MoveTo(new VirtualSnapshotPoint(pointInView.Value, point.VirtualSpaces)); // We use the caret's position in the view's current snapshot here in case something // changed text in response to a caret move (e.g. line commit) var spanInView = new SnapshotSpan(newPosition.BufferPosition, 0); textView.ViewScroller.EnsureSpanVisible(spanInView, ensureSpanVisibleOptions); return true; } /// <summary> /// Gets or creates a view property that would go away when view gets closed /// </summary> public static TProperty GetOrCreateAutoClosingProperty<TProperty, TTextView>( this TTextView textView, Func<TTextView, TProperty> valueCreator) where TTextView : ITextView { return textView.GetOrCreateAutoClosingProperty(typeof(TProperty), valueCreator); } /// <summary> /// Gets or creates a view property that would go away when view gets closed /// </summary> public static TProperty GetOrCreateAutoClosingProperty<TProperty, TTextView>( this TTextView textView, object key, Func<TTextView, TProperty> valueCreator) where TTextView : ITextView { GetOrCreateAutoClosingProperty(textView, key, valueCreator, out var value); return value; } /// <summary> /// Gets or creates a view property that would go away when view gets closed /// </summary> public static bool GetOrCreateAutoClosingProperty<TProperty, TTextView>( this TTextView textView, object key, Func<TTextView, TProperty> valueCreator, out TProperty value) where TTextView : ITextView { return AutoClosingViewProperty<TProperty, TTextView>.GetOrCreateValue(textView, key, valueCreator, out value); } /// <summary> /// Gets or creates a per subject buffer property. /// </summary> public static TProperty GetOrCreatePerSubjectBufferProperty<TProperty, TTextView>( this TTextView textView, ITextBuffer subjectBuffer, object key, Func<TTextView, ITextBuffer, TProperty> valueCreator) where TTextView : class, ITextView { GetOrCreatePerSubjectBufferProperty(textView, subjectBuffer, key, valueCreator, out var value); return value; } /// <summary> /// Gets or creates a per subject buffer property, returning true if it needed to create it. /// </summary> public static bool GetOrCreatePerSubjectBufferProperty<TProperty, TTextView>( this TTextView textView, ITextBuffer subjectBuffer, object key, Func<TTextView, ITextBuffer, TProperty> valueCreator, out TProperty value) where TTextView : class, ITextView { Contract.ThrowIfNull(textView); Contract.ThrowIfNull(subjectBuffer); Contract.ThrowIfNull(valueCreator); return PerSubjectBufferProperty<TProperty, TTextView>.GetOrCreateValue(textView, subjectBuffer, key, valueCreator, out value); } public static bool TryGetPerSubjectBufferProperty<TProperty, TTextView>( this TTextView textView, ITextBuffer subjectBuffer, object key, [MaybeNullWhen(false)] out TProperty value) where TTextView : class, ITextView { Contract.ThrowIfNull(textView); Contract.ThrowIfNull(subjectBuffer); return PerSubjectBufferProperty<TProperty, TTextView>.TryGetValue(textView, subjectBuffer, key, out value); } public static void AddPerSubjectBufferProperty<TProperty, TTextView>( this TTextView textView, ITextBuffer subjectBuffer, object key, TProperty value) where TTextView : class, ITextView { Contract.ThrowIfNull(textView); Contract.ThrowIfNull(subjectBuffer); PerSubjectBufferProperty<TProperty, TTextView>.AddValue(textView, subjectBuffer, key, value); } public static void RemovePerSubjectBufferProperty<TProperty, TTextView>( this TTextView textView, ITextBuffer subjectBuffer, object key) where TTextView : class, ITextView { Contract.ThrowIfNull(textView); Contract.ThrowIfNull(subjectBuffer); PerSubjectBufferProperty<TProperty, TTextView>.RemoveValue(textView, subjectBuffer, key); } public static bool TypeCharWasHandledStrangely( this ITextView textView, ITextBuffer subjectBuffer, char ch) { var finalCaretPositionOpt = textView.GetCaretPoint(subjectBuffer); if (finalCaretPositionOpt == null) { // Caret moved outside of our buffer. Don't want to handle this typed character. return true; } var previousPosition = finalCaretPositionOpt.Value.Position - 1; var inRange = previousPosition >= 0 && previousPosition < subjectBuffer.CurrentSnapshot.Length; if (!inRange) { // The character before the caret isn't even in the buffer we care about. Don't // handle this. return true; } if (subjectBuffer.CurrentSnapshot[previousPosition] != ch) { // The character that was typed is not in the buffer at the typed location. Don't // handle this character. return true; } return false; } public static int? GetDesiredIndentation(this ITextView textView, ISmartIndentationService smartIndentService, ITextSnapshotLine line) { var pointInView = textView.BufferGraph.MapUpToSnapshot( line.Start, PointTrackingMode.Positive, PositionAffinity.Successor, textView.TextSnapshot); if (!pointInView.HasValue) { return null; } var lineInView = textView.TextSnapshot.GetLineFromPosition(pointInView.Value.Position); return smartIndentService.GetDesiredIndentation(textView, lineInView); } public static bool TryGetSurfaceBufferSpan( this ITextView textView, VirtualSnapshotSpan virtualSnapshotSpan, out VirtualSnapshotSpan surfaceBufferSpan) { // If we are already on the surface buffer, then there's no reason to attempt mappings // as we'll lose virtualness if (virtualSnapshotSpan.Snapshot.TextBuffer == textView.TextBuffer) { surfaceBufferSpan = virtualSnapshotSpan; return true; } // We have to map. We'll lose virtualness in this process because // mapping virtual points through projections is poorly defined. var targetSpan = textView.BufferGraph.MapUpToSnapshot( virtualSnapshotSpan.SnapshotSpan, SpanTrackingMode.EdgeExclusive, textView.TextSnapshot).FirstOrNull(); if (targetSpan.HasValue) { surfaceBufferSpan = new VirtualSnapshotSpan(targetSpan.Value); return true; } surfaceBufferSpan = default; return false; } /// <summary> /// Returns the span of the lines in subjectBuffer that is currently visible in the provided /// view. "extraLines" can be provided to get a span that encompasses some number of lines /// before and after the actual visible lines. /// </summary> public static SnapshotSpan? GetVisibleLinesSpan(this ITextView textView, ITextBuffer subjectBuffer, int extraLines = 0) { // No point in continuing if the text view has been closed. if (textView.IsClosed) { return null; } // If we're being called while the textview is actually in the middle of a layout, then // we can't proceed. Much of the text view state is unsafe to access (and will throw). if (textView.InLayout) { return null; } // During text view initialization the TextViewLines may be null. In that case we can't // get an appropriate visisble span. if (textView.TextViewLines == null) { return null; } // Determine the range of text that is visible in the view. Then map this down to the // bufffer passed in. From that, determine the start/end line for the buffer that is in // view. var visibleSpan = textView.TextViewLines.FormattedSpan; var visibleSpansInBuffer = textView.BufferGraph.MapDownToBuffer(visibleSpan, SpanTrackingMode.EdgeInclusive, subjectBuffer); if (visibleSpansInBuffer.Count == 0) { return null; } var visibleStart = visibleSpansInBuffer.First().Start; var visibleEnd = visibleSpansInBuffer.Last().End; var snapshot = subjectBuffer.CurrentSnapshot; var startLine = visibleStart.GetContainingLine().LineNumber; var endLine = visibleEnd.GetContainingLine().LineNumber; startLine = Math.Max(startLine - extraLines, 0); endLine = Math.Min(endLine + extraLines, snapshot.LineCount - 1); var start = snapshot.GetLineFromLineNumber(startLine).Start; var end = snapshot.GetLineFromLineNumber(endLine).EndIncludingLineBreak; var span = new SnapshotSpan(snapshot, Span.FromBounds(start, end)); return span; } /// <summary> /// Determines if the textbuffer passed in matches the buffer for the textview. /// </summary> public static bool IsNotSurfaceBufferOfTextView(this ITextView textView, ITextBuffer textBuffer) => textBuffer != textView.TextBuffer; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Outlining; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static partial class ITextViewExtensions { /// <summary> /// Collects the content types in the view's buffer graph. /// </summary> public static ISet<IContentType> GetContentTypes(this ITextView textView) { return new HashSet<IContentType>( textView.BufferGraph.GetTextBuffers(_ => true).Select(b => b.ContentType)); } public static bool IsReadOnlyOnSurfaceBuffer(this ITextView textView, SnapshotSpan span) { var spansInView = textView.BufferGraph.MapUpToBuffer(span, SpanTrackingMode.EdgeInclusive, textView.TextBuffer); return spansInView.Any(spanInView => textView.TextBuffer.IsReadOnly(spanInView.Span)); } public static SnapshotPoint? GetCaretPoint(this ITextView textView, ITextBuffer subjectBuffer) { var caret = textView.Caret.Position; return textView.BufferGraph.MapUpOrDownToBuffer(caret.BufferPosition, subjectBuffer); } public static SnapshotPoint? GetCaretPoint(this ITextView textView, Predicate<ITextSnapshot> match) { var caret = textView.Caret.Position; var span = textView.BufferGraph.MapUpOrDownToFirstMatch(new SnapshotSpan(caret.BufferPosition, 0), match); if (span.HasValue) { return span.Value.Start; } else { return null; } } public static VirtualSnapshotPoint? GetVirtualCaretPoint(this ITextView textView, ITextBuffer subjectBuffer) { if (subjectBuffer == textView.TextBuffer) { return textView.Caret.Position.VirtualBufferPosition; } var mappedPoint = textView.BufferGraph.MapDownToBuffer( textView.Caret.Position.VirtualBufferPosition.Position, PointTrackingMode.Negative, subjectBuffer, PositionAffinity.Predecessor); return mappedPoint.HasValue ? new VirtualSnapshotPoint(mappedPoint.Value) : default; } public static ITextBuffer? GetBufferContainingCaret(this ITextView textView, string contentType = ContentTypeNames.RoslynContentType) { var point = GetCaretPoint(textView, s => s.ContentType.IsOfType(contentType)); return point.HasValue ? point.Value.Snapshot.TextBuffer : null; } public static SnapshotPoint? GetPositionInView(this ITextView textView, SnapshotPoint point) => textView.BufferGraph.MapUpToSnapshot(point, PointTrackingMode.Positive, PositionAffinity.Successor, textView.TextSnapshot); public static NormalizedSnapshotSpanCollection GetSpanInView(this ITextView textView, SnapshotSpan span) => textView.BufferGraph.MapUpToSnapshot(span, SpanTrackingMode.EdgeInclusive, textView.TextSnapshot); public static void SetSelection( this ITextView textView, VirtualSnapshotPoint anchorPoint, VirtualSnapshotPoint activePoint) { var isReversed = activePoint < anchorPoint; var start = isReversed ? activePoint : anchorPoint; var end = isReversed ? anchorPoint : activePoint; SetSelection(textView, new SnapshotSpan(start.Position, end.Position), isReversed); } public static void SetSelection( this ITextView textView, SnapshotSpan span, bool isReversed = false) { var spanInView = textView.GetSpanInView(span).Single(); textView.Selection.Select(spanInView, isReversed); textView.Caret.MoveTo(isReversed ? spanInView.Start : spanInView.End); } /// <summary> /// Sets a multi selection with the last span as the primary selection. /// Also maps up to the correct span in view before attempting to set the selection. /// </summary> public static void SetMultiSelection(this ITextView textView, IEnumerable<SnapshotSpan> spans) { var spansInView = spans.Select(s => new Selection(textView.GetSpanInView(s).Single())); textView.GetMultiSelectionBroker().SetSelectionRange(spansInView, spansInView.Last()); } public static bool TryMoveCaretToAndEnsureVisible(this ITextView textView, SnapshotPoint point, IOutliningManagerService? outliningManagerService = null, EnsureSpanVisibleOptions ensureSpanVisibleOptions = EnsureSpanVisibleOptions.None) => textView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(point), outliningManagerService, ensureSpanVisibleOptions); public static bool TryMoveCaretToAndEnsureVisible(this ITextView textView, VirtualSnapshotPoint point, IOutliningManagerService? outliningManagerService = null, EnsureSpanVisibleOptions ensureSpanVisibleOptions = EnsureSpanVisibleOptions.None) { if (textView.IsClosed) { return false; } var pointInView = textView.GetPositionInView(point.Position); if (!pointInView.HasValue) { return false; } // If we were given an outlining service, we need to expand any outlines first, or else // the Caret.MoveTo won't land in the correct location if our target is inside a // collapsed outline. if (outliningManagerService != null) { var outliningManager = outliningManagerService.GetOutliningManager(textView); if (outliningManager != null) { outliningManager.ExpandAll(new SnapshotSpan(pointInView.Value, length: 0), match: _ => true); } } var newPosition = textView.Caret.MoveTo(new VirtualSnapshotPoint(pointInView.Value, point.VirtualSpaces)); // We use the caret's position in the view's current snapshot here in case something // changed text in response to a caret move (e.g. line commit) var spanInView = new SnapshotSpan(newPosition.BufferPosition, 0); textView.ViewScroller.EnsureSpanVisible(spanInView, ensureSpanVisibleOptions); return true; } /// <summary> /// Gets or creates a view property that would go away when view gets closed /// </summary> public static TProperty GetOrCreateAutoClosingProperty<TProperty, TTextView>( this TTextView textView, Func<TTextView, TProperty> valueCreator) where TTextView : ITextView { return textView.GetOrCreateAutoClosingProperty(typeof(TProperty), valueCreator); } /// <summary> /// Gets or creates a view property that would go away when view gets closed /// </summary> public static TProperty GetOrCreateAutoClosingProperty<TProperty, TTextView>( this TTextView textView, object key, Func<TTextView, TProperty> valueCreator) where TTextView : ITextView { GetOrCreateAutoClosingProperty(textView, key, valueCreator, out var value); return value; } /// <summary> /// Gets or creates a view property that would go away when view gets closed /// </summary> public static bool GetOrCreateAutoClosingProperty<TProperty, TTextView>( this TTextView textView, object key, Func<TTextView, TProperty> valueCreator, out TProperty value) where TTextView : ITextView { return AutoClosingViewProperty<TProperty, TTextView>.GetOrCreateValue(textView, key, valueCreator, out value); } /// <summary> /// Gets or creates a per subject buffer property. /// </summary> public static TProperty GetOrCreatePerSubjectBufferProperty<TProperty, TTextView>( this TTextView textView, ITextBuffer subjectBuffer, object key, Func<TTextView, ITextBuffer, TProperty> valueCreator) where TTextView : class, ITextView { GetOrCreatePerSubjectBufferProperty(textView, subjectBuffer, key, valueCreator, out var value); return value; } /// <summary> /// Gets or creates a per subject buffer property, returning true if it needed to create it. /// </summary> public static bool GetOrCreatePerSubjectBufferProperty<TProperty, TTextView>( this TTextView textView, ITextBuffer subjectBuffer, object key, Func<TTextView, ITextBuffer, TProperty> valueCreator, out TProperty value) where TTextView : class, ITextView { Contract.ThrowIfNull(textView); Contract.ThrowIfNull(subjectBuffer); Contract.ThrowIfNull(valueCreator); return PerSubjectBufferProperty<TProperty, TTextView>.GetOrCreateValue(textView, subjectBuffer, key, valueCreator, out value); } public static bool TryGetPerSubjectBufferProperty<TProperty, TTextView>( this TTextView textView, ITextBuffer subjectBuffer, object key, [MaybeNullWhen(false)] out TProperty value) where TTextView : class, ITextView { Contract.ThrowIfNull(textView); Contract.ThrowIfNull(subjectBuffer); return PerSubjectBufferProperty<TProperty, TTextView>.TryGetValue(textView, subjectBuffer, key, out value); } public static void AddPerSubjectBufferProperty<TProperty, TTextView>( this TTextView textView, ITextBuffer subjectBuffer, object key, TProperty value) where TTextView : class, ITextView { Contract.ThrowIfNull(textView); Contract.ThrowIfNull(subjectBuffer); PerSubjectBufferProperty<TProperty, TTextView>.AddValue(textView, subjectBuffer, key, value); } public static void RemovePerSubjectBufferProperty<TProperty, TTextView>( this TTextView textView, ITextBuffer subjectBuffer, object key) where TTextView : class, ITextView { Contract.ThrowIfNull(textView); Contract.ThrowIfNull(subjectBuffer); PerSubjectBufferProperty<TProperty, TTextView>.RemoveValue(textView, subjectBuffer, key); } public static bool TypeCharWasHandledStrangely( this ITextView textView, ITextBuffer subjectBuffer, char ch) { var finalCaretPositionOpt = textView.GetCaretPoint(subjectBuffer); if (finalCaretPositionOpt == null) { // Caret moved outside of our buffer. Don't want to handle this typed character. return true; } var previousPosition = finalCaretPositionOpt.Value.Position - 1; var inRange = previousPosition >= 0 && previousPosition < subjectBuffer.CurrentSnapshot.Length; if (!inRange) { // The character before the caret isn't even in the buffer we care about. Don't // handle this. return true; } if (subjectBuffer.CurrentSnapshot[previousPosition] != ch) { // The character that was typed is not in the buffer at the typed location. Don't // handle this character. return true; } return false; } public static int? GetDesiredIndentation(this ITextView textView, ISmartIndentationService smartIndentService, ITextSnapshotLine line) { var pointInView = textView.BufferGraph.MapUpToSnapshot( line.Start, PointTrackingMode.Positive, PositionAffinity.Successor, textView.TextSnapshot); if (!pointInView.HasValue) { return null; } var lineInView = textView.TextSnapshot.GetLineFromPosition(pointInView.Value.Position); return smartIndentService.GetDesiredIndentation(textView, lineInView); } public static bool TryGetSurfaceBufferSpan( this ITextView textView, VirtualSnapshotSpan virtualSnapshotSpan, out VirtualSnapshotSpan surfaceBufferSpan) { // If we are already on the surface buffer, then there's no reason to attempt mappings // as we'll lose virtualness if (virtualSnapshotSpan.Snapshot.TextBuffer == textView.TextBuffer) { surfaceBufferSpan = virtualSnapshotSpan; return true; } // We have to map. We'll lose virtualness in this process because // mapping virtual points through projections is poorly defined. var targetSpan = textView.BufferGraph.MapUpToSnapshot( virtualSnapshotSpan.SnapshotSpan, SpanTrackingMode.EdgeExclusive, textView.TextSnapshot).FirstOrNull(); if (targetSpan.HasValue) { surfaceBufferSpan = new VirtualSnapshotSpan(targetSpan.Value); return true; } surfaceBufferSpan = default; return false; } /// <summary> /// Returns the span of the lines in subjectBuffer that is currently visible in the provided /// view. "extraLines" can be provided to get a span that encompasses some number of lines /// before and after the actual visible lines. /// </summary> public static SnapshotSpan? GetVisibleLinesSpan(this ITextView textView, ITextBuffer subjectBuffer, int extraLines = 0) { // No point in continuing if the text view has been closed. if (textView.IsClosed) { return null; } // If we're being called while the textview is actually in the middle of a layout, then // we can't proceed. Much of the text view state is unsafe to access (and will throw). if (textView.InLayout) { return null; } // During text view initialization the TextViewLines may be null. In that case we can't // get an appropriate visisble span. if (textView.TextViewLines == null) { return null; } // Determine the range of text that is visible in the view. Then map this down to the // bufffer passed in. From that, determine the start/end line for the buffer that is in // view. var visibleSpan = textView.TextViewLines.FormattedSpan; var visibleSpansInBuffer = textView.BufferGraph.MapDownToBuffer(visibleSpan, SpanTrackingMode.EdgeInclusive, subjectBuffer); if (visibleSpansInBuffer.Count == 0) { return null; } var visibleStart = visibleSpansInBuffer.First().Start; var visibleEnd = visibleSpansInBuffer.Last().End; var snapshot = subjectBuffer.CurrentSnapshot; var startLine = visibleStart.GetContainingLine().LineNumber; var endLine = visibleEnd.GetContainingLine().LineNumber; startLine = Math.Max(startLine - extraLines, 0); endLine = Math.Min(endLine + extraLines, snapshot.LineCount - 1); var start = snapshot.GetLineFromLineNumber(startLine).Start; var end = snapshot.GetLineFromLineNumber(endLine).EndIncludingLineBreak; var span = new SnapshotSpan(snapshot, Span.FromBounds(start, end)); return span; } /// <summary> /// Determines if the textbuffer passed in matches the buffer for the textview. /// </summary> public static bool IsNotSurfaceBufferOfTextView(this ITextView textView, ITextBuffer textBuffer) => textBuffer != textView.TextBuffer; } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/EditorFeatures/Core/Extensibility/NavigationBar/WrappedNavigationBarItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.NavigationBar; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor { /// <summary> /// Implementation of the editor layer <see cref="NavigationBarItem"/> that wraps a feature layer <see cref="RoslynNavigationBarItem"/> /// </summary> // We suppress this as this type *does* override ComputeAdditionalHashCodeParts internal sealed class WrappedNavigationBarItem : NavigationBarItem, IEquatable<WrappedNavigationBarItem> { public readonly RoslynNavigationBarItem UnderlyingItem; internal WrappedNavigationBarItem(ITextVersion textVersion, RoslynNavigationBarItem underlyingItem) : base( textVersion, underlyingItem.Text, underlyingItem.Glyph, GetSpans(underlyingItem), GetNavigationSpan(underlyingItem), underlyingItem.ChildItems.SelectAsArray(v => (NavigationBarItem)new WrappedNavigationBarItem(textVersion, v)), underlyingItem.Indent, underlyingItem.Bolded, underlyingItem.Grayed) { UnderlyingItem = underlyingItem; } private static ImmutableArray<TextSpan> GetSpans(RoslynNavigationBarItem underlyingItem) { return underlyingItem is RoslynNavigationBarItem.SymbolItem symbolItem && symbolItem.Location.InDocumentInfo != null ? symbolItem.Location.InDocumentInfo.Value.spans : ImmutableArray<TextSpan>.Empty; } private static TextSpan? GetNavigationSpan(RoslynNavigationBarItem underlyingItem) { return underlyingItem is RoslynNavigationBarItem.SymbolItem symbolItem && symbolItem.Location.InDocumentInfo != null ? symbolItem.Location.InDocumentInfo.Value.navigationSpan : null; } public override bool Equals(object? obj) => Equals(obj as WrappedNavigationBarItem); public bool Equals(WrappedNavigationBarItem? other) => base.Equals(other) && UnderlyingItem.Equals(other.UnderlyingItem); public override int GetHashCode() => throw new NotImplementedException(); } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.NavigationBar; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor { /// <summary> /// Implementation of the editor layer <see cref="NavigationBarItem"/> that wraps a feature layer <see cref="RoslynNavigationBarItem"/> /// </summary> // We suppress this as this type *does* override ComputeAdditionalHashCodeParts internal sealed class WrappedNavigationBarItem : NavigationBarItem, IEquatable<WrappedNavigationBarItem> { public readonly RoslynNavigationBarItem UnderlyingItem; internal WrappedNavigationBarItem(ITextVersion textVersion, RoslynNavigationBarItem underlyingItem) : base( textVersion, underlyingItem.Text, underlyingItem.Glyph, GetSpans(underlyingItem), GetNavigationSpan(underlyingItem), underlyingItem.ChildItems.SelectAsArray(v => (NavigationBarItem)new WrappedNavigationBarItem(textVersion, v)), underlyingItem.Indent, underlyingItem.Bolded, underlyingItem.Grayed) { UnderlyingItem = underlyingItem; } private static ImmutableArray<TextSpan> GetSpans(RoslynNavigationBarItem underlyingItem) { return underlyingItem is RoslynNavigationBarItem.SymbolItem symbolItem && symbolItem.Location.InDocumentInfo != null ? symbolItem.Location.InDocumentInfo.Value.spans : ImmutableArray<TextSpan>.Empty; } private static TextSpan? GetNavigationSpan(RoslynNavigationBarItem underlyingItem) { return underlyingItem is RoslynNavigationBarItem.SymbolItem symbolItem && symbolItem.Location.InDocumentInfo != null ? symbolItem.Location.InDocumentInfo.Value.navigationSpan : null; } public override bool Equals(object? obj) => Equals(obj as WrappedNavigationBarItem); public bool Equals(WrappedNavigationBarItem? other) => base.Equals(other) && UnderlyingItem.Equals(other.UnderlyingItem); public override int GetHashCode() => throw new NotImplementedException(); } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/VisualStudio/IntegrationTest/TestUtilities/Harness/MessageFilter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using IMessageFilter = Microsoft.VisualStudio.OLE.Interop.IMessageFilter; using INTERFACEINFO = Microsoft.VisualStudio.OLE.Interop.INTERFACEINFO; using PENDINGMSG = Microsoft.VisualStudio.OLE.Interop.PENDINGMSG; using SERVERCALL = Microsoft.VisualStudio.OLE.Interop.SERVERCALL; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Harness { public sealed class MessageFilter : IMessageFilter, IDisposable { private const uint CancelCall = ~0U; private readonly MessageFilterSafeHandle _messageFilterRegistration; private readonly TimeSpan _timeout; private readonly TimeSpan _retryDelay; public MessageFilter() : this(timeout: TimeSpan.FromSeconds(60), retryDelay: TimeSpan.FromMilliseconds(150)) { } public MessageFilter(TimeSpan timeout, TimeSpan retryDelay) { _timeout = timeout; _retryDelay = retryDelay; _messageFilterRegistration = MessageFilterSafeHandle.Register(this); } public uint HandleInComingCall(uint dwCallType, IntPtr htaskCaller, uint dwTickCount, INTERFACEINFO[] lpInterfaceInfo) { return (uint)SERVERCALL.SERVERCALL_ISHANDLED; } public uint RetryRejectedCall(IntPtr htaskCallee, uint dwTickCount, uint dwRejectType) { if ((SERVERCALL)dwRejectType != SERVERCALL.SERVERCALL_RETRYLATER && (SERVERCALL)dwRejectType != SERVERCALL.SERVERCALL_REJECTED) { return CancelCall; } if (dwTickCount >= _timeout.TotalMilliseconds) { return CancelCall; } return (uint)_retryDelay.TotalMilliseconds; } public uint MessagePending(IntPtr htaskCallee, uint dwTickCount, uint dwPendingType) { return (uint)PENDINGMSG.PENDINGMSG_WAITDEFPROCESS; } public void Dispose() { _messageFilterRegistration.Dispose(); } } }
// Licensed to the .NET Foundation under one or more 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 IMessageFilter = Microsoft.VisualStudio.OLE.Interop.IMessageFilter; using INTERFACEINFO = Microsoft.VisualStudio.OLE.Interop.INTERFACEINFO; using PENDINGMSG = Microsoft.VisualStudio.OLE.Interop.PENDINGMSG; using SERVERCALL = Microsoft.VisualStudio.OLE.Interop.SERVERCALL; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Harness { public sealed class MessageFilter : IMessageFilter, IDisposable { private const uint CancelCall = ~0U; private readonly MessageFilterSafeHandle _messageFilterRegistration; private readonly TimeSpan _timeout; private readonly TimeSpan _retryDelay; public MessageFilter() : this(timeout: TimeSpan.FromSeconds(60), retryDelay: TimeSpan.FromMilliseconds(150)) { } public MessageFilter(TimeSpan timeout, TimeSpan retryDelay) { _timeout = timeout; _retryDelay = retryDelay; _messageFilterRegistration = MessageFilterSafeHandle.Register(this); } public uint HandleInComingCall(uint dwCallType, IntPtr htaskCaller, uint dwTickCount, INTERFACEINFO[] lpInterfaceInfo) { return (uint)SERVERCALL.SERVERCALL_ISHANDLED; } public uint RetryRejectedCall(IntPtr htaskCallee, uint dwTickCount, uint dwRejectType) { if ((SERVERCALL)dwRejectType != SERVERCALL.SERVERCALL_RETRYLATER && (SERVERCALL)dwRejectType != SERVERCALL.SERVERCALL_REJECTED) { return CancelCall; } if (dwTickCount >= _timeout.TotalMilliseconds) { return CancelCall; } return (uint)_retryDelay.TotalMilliseconds; } public uint MessagePending(IntPtr htaskCallee, uint dwTickCount, uint dwPendingType) { return (uint)PENDINGMSG.PENDINGMSG_WAITDEFPROCESS; } public void Dispose() { _messageFilterRegistration.Dispose(); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/ExpressionEvaluator/CSharp/Test/ResultProvider/DebuggerBrowsableAttributeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Reflection; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class DebuggerBrowsableAttributeTests : CSharpResultProviderTestBase { [Fact] public void Never() { var source = @"using System.Diagnostics; [DebuggerTypeProxy(typeof(P))] class C { [DebuggerBrowsable(DebuggerBrowsableState.Never)] object F = 1; object P { get { return 3; } } } class P { public P(C c) { } public object G = 2; [DebuggerBrowsable(DebuggerBrowsableState.Never)] public object Q { get { return 4; } } }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("new C()", value); Verify(evalResult, EvalResult("new C()", "{C}", "C", "new C()", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("G", "2", "object {int}", "new P(new C()).G"), EvalResult("Raw View", null, "", "new C(), raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); children = GetChildren(children[1]); Verify(children, EvalResult("P", "3", "object {int}", "(new C()).P", DkmEvaluationResultFlags.ReadOnly)); } /// <summary> /// DebuggerBrowsableAttributes are not inherited. /// </summary> [Fact] public void Never_OverridesAndImplements() { var source = @"using System.Diagnostics; interface I { [DebuggerBrowsable(DebuggerBrowsableState.Never)] object P1 { get; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] object P2 { get; } object P3 { get; } object P4 { get; } } abstract class A { [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal abstract object P5 { get; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal virtual object P6 { get { return 0; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal abstract object P7 { get; } internal abstract object P8 { get; } } class B : A, I { public object P1 { get { return 1; } } object I.P2 { get { return 2; } } object I.P3 { get { return 3; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] object I.P4 { get { return 4; } } internal override object P5 { get { return 5; } } internal override object P6 { get { return 6; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal override object P7 { get { return 7; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal override object P8 { get { return 8; } } } class C { I o = new B(); }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("c", value); Verify(evalResult, EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("o", "{B}", "I {B}", "c.o", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite)); children = GetChildren(children[0]); Verify(children, EvalResult("I.P2", "2", "object {int}", "c.o.P2", DkmEvaluationResultFlags.ReadOnly), EvalResult("I.P3", "3", "object {int}", "c.o.P3", DkmEvaluationResultFlags.ReadOnly), EvalResult("P1", "1", "object {int}", "((B)c.o).P1", DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite), EvalResult("P5", "5", "object {int}", "((B)c.o).P5", DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite), EvalResult("P6", "6", "object {int}", "((B)c.o).P6", DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite)); } [Fact] public void DuplicateAttributes() { var source = @"using System.Diagnostics; abstract class A { [DebuggerBrowsable(DebuggerBrowsableState.Never)] public object P1; [DebuggerBrowsable(DebuggerBrowsableState.Never)] public object P2; internal object P3 => 0; } class B : A { [DebuggerBrowsable(DebuggerBrowsableState.Never)] new public object P1 => base.P1; new public object P2 => 1; [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal new object P3 => 2; }"; var assembly = GetAssembly(source); var type = assembly.GetType("B"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None, valueFlags: DkmClrValueFlags.Synthetic); var evalResult = FormatResult("this", value); Verify(evalResult, EvalResult("this", "{B}", "B", "this", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("P3 (A)", "0", "object {int}", "((A)this).P3", DkmEvaluationResultFlags.ReadOnly)); } /// <summary> /// DkmClrDebuggerBrowsableAttributes are obtained from the /// containing type and associated with the member name. For /// explicit interface implementations, the name will include /// namespace and type. /// </summary> [Fact] public void Never_ExplicitNamespaceGeneric() { var source = @"using System.Diagnostics; namespace N1 { namespace N2 { class A<T> { internal interface I<U> { T P { get; } U Q { get; } } } } class B : N2.A<object>.I<int> { [DebuggerBrowsable(DebuggerBrowsableState.Never)] object N2.A<object>.I<int>.P { get { return 1; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public int Q { get { return 2; } } } }"; var assembly = GetAssembly(source); var type = assembly.GetType("N1.B"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{N1.B}", "N1.B", "o")); } [Fact] public void RootHidden() { var source = @"using System.Diagnostics; struct S { internal S(int[] x, object[] y) : this() { this.F = x; this.Q = y; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal int[] F; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal int P { get { return this.F.Length; } } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal object[] Q { get; private set; } } class A { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly B G = new B { H = 4 }; } class B { internal object H; }"; var assembly = GetAssembly(source); var typeS = assembly.GetType("S"); var typeA = assembly.GetType("A"); var value = CreateDkmClrValue( value: typeS.Instantiate(new int[] { 1, 2 }, new object[] { 3, typeA.Instantiate() }), type: new DkmClrType((TypeImpl)typeS), evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{S}", "S", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "1", "int", "o.F[0]"), EvalResult("[1]", "2", "int", "o.F[1]"), EvalResult("[0]", "3", "object {int}", "o.Q[0]"), EvalResult("[1]", "{A}", "object {A}", "o.Q[1]", DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(children[3]), EvalResult("H", "4", "object {int}", "((A)o.Q[1]).G.H")); } [Fact] public void RootHidden_Exception() { var source = @"using System; using System.Diagnostics; class E : Exception { } class F : E { object G = 1; } class C { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] object P { get { throw new F(); } } }"; using (new EnsureEnglishUICulture()) { var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children[1], EvalResult("G", "1", "object {int}", null)); Verify(children[7], EvalResult("Message", "\"Exception of type 'F' was thrown.\"", "string", null, DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.ReadOnly)); } } } /// <summary> /// Instance of type where all members are marked /// [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]. /// </summary> [WorkItem(934800, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/934800")] [Fact] public void RootHidden_Empty() { var source = @"using System.Diagnostics; class A { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly object F1 = new C(); } class B { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly object F2 = new C(); } class C { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly object F3 = new object(); [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly object F4 = null; }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); // Ideally, not expandable. var children = GetChildren(evalResult); Verify(children); // No children. } [Fact] public void DebuggerBrowsable_GenericType() { var source = @"using System.Diagnostics; class C<T> { internal C(T f, T g) { this.F = f; this.G = g; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal readonly T F; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly T G; } struct S { internal S(object o) { this.O = o; } internal readonly object O; }"; var assembly = GetAssembly(source); var typeS = assembly.GetType("S"); var typeC = assembly.GetType("C`1").MakeGenericType(typeS); var value = CreateDkmClrValue( value: typeC.Instantiate(typeS.Instantiate(1), typeS.Instantiate(2)), type: new DkmClrType((TypeImpl)typeC), evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C<S>}", "C<S>", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("O", "2", "object {int}", "o.G.O", DkmEvaluationResultFlags.ReadOnly)); } [Fact] public void RootHidden_ExplicitImplementation() { var source = @"using System.Diagnostics; interface I<T> { T P { get; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] T Q { get; } } class A { internal object F; } class B : I<A> { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] A I<A>.P { get { return new A() { F = 1 }; } } A I<A>.Q { get { return new A() { F = 2 }; } } }"; var assembly = GetAssembly(source); var type = assembly.GetType("B"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{B}", "B", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "1", "object {int}", "((I<A>)o).P.F"), EvalResult("I<A>.Q", "{A}", "A", "((I<A>)o).Q", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly)); Verify(GetChildren(children[1]), EvalResult("F", "2", "object {int}", "((I<A>)o).Q.F", DkmEvaluationResultFlags.CanFavorite)); } [Fact] public void RootHidden_ProxyType() { var source = @"using System.Diagnostics; [DebuggerTypeProxy(typeof(P))] class A { internal A(int f) { this.F = f; } internal int F; } class P { private readonly A a; public P(A a) { this.a = a; } public object Q { get { return this.a.F; } } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public object R { get { return this.a.F + 1; } } } class B { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal object F = new A(1); internal object G = new A(3); }"; var assembly = GetAssembly(source); var type = assembly.GetType("B"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{B}", "B", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Q", "1", "object {int}", "new P(o.F).Q", DkmEvaluationResultFlags.ReadOnly), EvalResult("Raw View", null, "", "o.F, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("G", "{A}", "object {A}", "o.G", DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(children[1]), EvalResult("F", "1", "int", "((A)o.F).F")); Verify(GetChildren(children[2]), EvalResult("Q", "3", "object {int}", "new P(o.G).Q", DkmEvaluationResultFlags.ReadOnly), EvalResult("Raw View", null, "", "o.G, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); } [Fact] public void RootHidden_Recursive() { var source = @"using System.Diagnostics; class A { internal A(object o) { this.F = o; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal object F; } class B { internal B(object o) { this.F = o; } internal object F; }"; var assembly = GetAssembly(source); var typeA = assembly.GetType("A"); var typeB = assembly.GetType("B"); var value = CreateDkmClrValue( value: typeA.Instantiate(typeA.Instantiate(typeA.Instantiate(typeB.Instantiate(4)))), type: new DkmClrType((TypeImpl)typeA), evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{A}", "A", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "4", "object {int}", "((B)((A)((A)o.F).F).F).F")); } [Fact] public void RootHidden_OnStaticMembers() { var source = @"using System.Diagnostics; class A { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal static object F = new B(); } class B { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal static object P { get { return new C(); } } internal static object G = 1; } class C { internal static object Q { get { return 3; } } internal object H = 2; }"; var assembly = GetAssembly(source); var type = assembly.GetType("A"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{A}", "A", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Static members", null, "", "A", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); children = GetChildren(children[0]); Verify(children, EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); children = GetChildren(children[0]); Verify(children, EvalResult("G", "1", "object {int}", "B.G"), EvalResult("H", "2", "object {int}", "((C)B.P).H"), EvalResult("Static members", null, "", "C", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); children = GetChildren(children[2]); Verify(children, EvalResult("Q", "3", "object {int}", "C.Q", DkmEvaluationResultFlags.ReadOnly)); } // Dev12 exposes the contents of RootHidden members even // if the members are private (e.g.: ImmutableArray<T>). [Fact] public void RootHidden_OnNonPublicMembers() { var source = @"using System.Diagnostics; public class C<T> { public C(params T[] items) { this.items = items; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] private T[] items; }"; var assembly = GetAssembly(source); var runtime = new DkmClrRuntimeInstance(new Assembly[0]); var type = assembly.GetType("C`1").MakeGenericType(typeof(int)); var value = CreateDkmClrValue( value: type.Instantiate(1, 2, 3), type: new DkmClrType(runtime.DefaultModule, runtime.DefaultAppDomain, (TypeImpl)type), evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers)); Verify(evalResult, EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "1", "int", "o.items[0]"), EvalResult("[1]", "2", "int", "o.items[1]"), EvalResult("[2]", "3", "int", "o.items[2]")); } // Dev12 does not merge "Static members" (or "Non-Public // members") across multiple RootHidden members. In // other words, there may be multiple "Static members" (or // "Non-Public members") rows within the same container. [Fact] public void RootHidden_WithStaticAndNonPublicMembers() { var source = @"using System.Diagnostics; public class A { public static int PA { get { return 1; } } internal int FA = 2; } public class B { internal int PB { get { return 3; } } public static int FB = 4; } public class C { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public readonly object FA = new A(); [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public object PB { get { return new B(); } } public static int PC { get { return 5; } } internal int FC = 6; }"; var assembly = GetAssembly(source); var runtime = new DkmClrRuntimeInstance(new Assembly[0]); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: new DkmClrType(runtime.DefaultModule, runtime.DefaultAppDomain, (TypeImpl)type), evalFlags: DkmEvaluationResultFlags.None); var inspectionContext = CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers); var evalResult = FormatResult("o", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult, inspectionContext: inspectionContext); Verify(children, EvalResult("Static members", null, "", "A", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class), EvalResult("Non-Public members", null, "", "o.FA, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class), EvalResult("Non-Public members", null, "", "o.PB, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("Static members", null, "", "C", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class), EvalResult("Non-Public members", null, "", "o, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); Verify(GetChildren(children[0]), EvalResult("PA", "1", "int", "A.PA", DkmEvaluationResultFlags.ReadOnly)); Verify(GetChildren(children[1]), EvalResult("FA", "2", "int", "((A)o.FA).FA")); Verify(GetChildren(children[2]), EvalResult("FB", "4", "int", "B.FB")); Verify(GetChildren(children[3]), EvalResult("PB", "3", "int", "((B)o.PB).PB", DkmEvaluationResultFlags.ReadOnly)); Verify(GetChildren(children[4]), EvalResult("PC", "5", "int", "C.PC", DkmEvaluationResultFlags.ReadOnly)); Verify(GetChildren(children[5]), EvalResult("FC", "6", "int", "o.FC")); } [Fact] public void ConstructedGenericType() { var source = @" using System.Diagnostics; public class C<T> { public T X; [DebuggerBrowsable(DebuggerBrowsableState.Never)] public T Y; } "; var assembly = GetAssembly(source); var type = assembly.GetType("C`1").MakeGenericType(typeof(int)); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(evalResult), EvalResult("X", "0", "int", "o.X", DkmEvaluationResultFlags.CanFavorite)); } [WorkItem(18581, "https://github.com/dotnet/roslyn/issues/18581")] [Fact] public void AccessibilityNotTrumpedByAttribute() { var source = @"using System.Diagnostics; class C { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private int[] _someArray = { 10, 20 }; private object SomethingPrivate = 3; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] internal object InternalCollapsed { get { return 1; } } [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] private object PrivateCollapsed { get { return 3; } } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] private int[] PrivateRootHidden { get { return _someArray; } } }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("new C()", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers)); Verify(evalResult, EvalResult("new C()", "{C}", "C", "new C()", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "10", "int", "(new C()).PrivateRootHidden[0]"), EvalResult("[1]", "20", "int", "(new C()).PrivateRootHidden[1]"), EvalResult("Non-Public members", null, "", "new C(), hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); var nonPublicChildren = GetChildren(children[2]); Verify(nonPublicChildren, EvalResult("InternalCollapsed", "1", "object {int}", "(new C()).InternalCollapsed", DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Internal), EvalResult("PrivateCollapsed", "3", "object {int}", "(new C()).PrivateCollapsed", DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Private), EvalResult("SomethingPrivate", "3", "object {int}", "(new C()).SomethingPrivate", DkmEvaluationResultFlags.None, DkmEvaluationResultCategory.Data, DkmEvaluationResultAccessType.Private)); } } }
// Licensed to the .NET Foundation under one or more 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.Reflection; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class DebuggerBrowsableAttributeTests : CSharpResultProviderTestBase { [Fact] public void Never() { var source = @"using System.Diagnostics; [DebuggerTypeProxy(typeof(P))] class C { [DebuggerBrowsable(DebuggerBrowsableState.Never)] object F = 1; object P { get { return 3; } } } class P { public P(C c) { } public object G = 2; [DebuggerBrowsable(DebuggerBrowsableState.Never)] public object Q { get { return 4; } } }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("new C()", value); Verify(evalResult, EvalResult("new C()", "{C}", "C", "new C()", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("G", "2", "object {int}", "new P(new C()).G"), EvalResult("Raw View", null, "", "new C(), raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); children = GetChildren(children[1]); Verify(children, EvalResult("P", "3", "object {int}", "(new C()).P", DkmEvaluationResultFlags.ReadOnly)); } /// <summary> /// DebuggerBrowsableAttributes are not inherited. /// </summary> [Fact] public void Never_OverridesAndImplements() { var source = @"using System.Diagnostics; interface I { [DebuggerBrowsable(DebuggerBrowsableState.Never)] object P1 { get; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] object P2 { get; } object P3 { get; } object P4 { get; } } abstract class A { [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal abstract object P5 { get; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal virtual object P6 { get { return 0; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal abstract object P7 { get; } internal abstract object P8 { get; } } class B : A, I { public object P1 { get { return 1; } } object I.P2 { get { return 2; } } object I.P3 { get { return 3; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] object I.P4 { get { return 4; } } internal override object P5 { get { return 5; } } internal override object P6 { get { return 6; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal override object P7 { get { return 7; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal override object P8 { get { return 8; } } } class C { I o = new B(); }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("c", value); Verify(evalResult, EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("o", "{B}", "I {B}", "c.o", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite)); children = GetChildren(children[0]); Verify(children, EvalResult("I.P2", "2", "object {int}", "c.o.P2", DkmEvaluationResultFlags.ReadOnly), EvalResult("I.P3", "3", "object {int}", "c.o.P3", DkmEvaluationResultFlags.ReadOnly), EvalResult("P1", "1", "object {int}", "((B)c.o).P1", DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite), EvalResult("P5", "5", "object {int}", "((B)c.o).P5", DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite), EvalResult("P6", "6", "object {int}", "((B)c.o).P6", DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite)); } [Fact] public void DuplicateAttributes() { var source = @"using System.Diagnostics; abstract class A { [DebuggerBrowsable(DebuggerBrowsableState.Never)] public object P1; [DebuggerBrowsable(DebuggerBrowsableState.Never)] public object P2; internal object P3 => 0; } class B : A { [DebuggerBrowsable(DebuggerBrowsableState.Never)] new public object P1 => base.P1; new public object P2 => 1; [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal new object P3 => 2; }"; var assembly = GetAssembly(source); var type = assembly.GetType("B"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None, valueFlags: DkmClrValueFlags.Synthetic); var evalResult = FormatResult("this", value); Verify(evalResult, EvalResult("this", "{B}", "B", "this", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("P3 (A)", "0", "object {int}", "((A)this).P3", DkmEvaluationResultFlags.ReadOnly)); } /// <summary> /// DkmClrDebuggerBrowsableAttributes are obtained from the /// containing type and associated with the member name. For /// explicit interface implementations, the name will include /// namespace and type. /// </summary> [Fact] public void Never_ExplicitNamespaceGeneric() { var source = @"using System.Diagnostics; namespace N1 { namespace N2 { class A<T> { internal interface I<U> { T P { get; } U Q { get; } } } } class B : N2.A<object>.I<int> { [DebuggerBrowsable(DebuggerBrowsableState.Never)] object N2.A<object>.I<int>.P { get { return 1; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public int Q { get { return 2; } } } }"; var assembly = GetAssembly(source); var type = assembly.GetType("N1.B"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{N1.B}", "N1.B", "o")); } [Fact] public void RootHidden() { var source = @"using System.Diagnostics; struct S { internal S(int[] x, object[] y) : this() { this.F = x; this.Q = y; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal int[] F; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal int P { get { return this.F.Length; } } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal object[] Q { get; private set; } } class A { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly B G = new B { H = 4 }; } class B { internal object H; }"; var assembly = GetAssembly(source); var typeS = assembly.GetType("S"); var typeA = assembly.GetType("A"); var value = CreateDkmClrValue( value: typeS.Instantiate(new int[] { 1, 2 }, new object[] { 3, typeA.Instantiate() }), type: new DkmClrType((TypeImpl)typeS), evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{S}", "S", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "1", "int", "o.F[0]"), EvalResult("[1]", "2", "int", "o.F[1]"), EvalResult("[0]", "3", "object {int}", "o.Q[0]"), EvalResult("[1]", "{A}", "object {A}", "o.Q[1]", DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(children[3]), EvalResult("H", "4", "object {int}", "((A)o.Q[1]).G.H")); } [Fact] public void RootHidden_Exception() { var source = @"using System; using System.Diagnostics; class E : Exception { } class F : E { object G = 1; } class C { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] object P { get { throw new F(); } } }"; using (new EnsureEnglishUICulture()) { var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children[1], EvalResult("G", "1", "object {int}", null)); Verify(children[7], EvalResult("Message", "\"Exception of type 'F' was thrown.\"", "string", null, DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.ReadOnly)); } } } /// <summary> /// Instance of type where all members are marked /// [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]. /// </summary> [WorkItem(934800, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/934800")] [Fact] public void RootHidden_Empty() { var source = @"using System.Diagnostics; class A { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly object F1 = new C(); } class B { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly object F2 = new C(); } class C { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly object F3 = new object(); [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly object F4 = null; }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); // Ideally, not expandable. var children = GetChildren(evalResult); Verify(children); // No children. } [Fact] public void DebuggerBrowsable_GenericType() { var source = @"using System.Diagnostics; class C<T> { internal C(T f, T g) { this.F = f; this.G = g; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal readonly T F; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly T G; } struct S { internal S(object o) { this.O = o; } internal readonly object O; }"; var assembly = GetAssembly(source); var typeS = assembly.GetType("S"); var typeC = assembly.GetType("C`1").MakeGenericType(typeS); var value = CreateDkmClrValue( value: typeC.Instantiate(typeS.Instantiate(1), typeS.Instantiate(2)), type: new DkmClrType((TypeImpl)typeC), evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C<S>}", "C<S>", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("O", "2", "object {int}", "o.G.O", DkmEvaluationResultFlags.ReadOnly)); } [Fact] public void RootHidden_ExplicitImplementation() { var source = @"using System.Diagnostics; interface I<T> { T P { get; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] T Q { get; } } class A { internal object F; } class B : I<A> { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] A I<A>.P { get { return new A() { F = 1 }; } } A I<A>.Q { get { return new A() { F = 2 }; } } }"; var assembly = GetAssembly(source); var type = assembly.GetType("B"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{B}", "B", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "1", "object {int}", "((I<A>)o).P.F"), EvalResult("I<A>.Q", "{A}", "A", "((I<A>)o).Q", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly)); Verify(GetChildren(children[1]), EvalResult("F", "2", "object {int}", "((I<A>)o).Q.F", DkmEvaluationResultFlags.CanFavorite)); } [Fact] public void RootHidden_ProxyType() { var source = @"using System.Diagnostics; [DebuggerTypeProxy(typeof(P))] class A { internal A(int f) { this.F = f; } internal int F; } class P { private readonly A a; public P(A a) { this.a = a; } public object Q { get { return this.a.F; } } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public object R { get { return this.a.F + 1; } } } class B { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal object F = new A(1); internal object G = new A(3); }"; var assembly = GetAssembly(source); var type = assembly.GetType("B"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{B}", "B", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Q", "1", "object {int}", "new P(o.F).Q", DkmEvaluationResultFlags.ReadOnly), EvalResult("Raw View", null, "", "o.F, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("G", "{A}", "object {A}", "o.G", DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(children[1]), EvalResult("F", "1", "int", "((A)o.F).F")); Verify(GetChildren(children[2]), EvalResult("Q", "3", "object {int}", "new P(o.G).Q", DkmEvaluationResultFlags.ReadOnly), EvalResult("Raw View", null, "", "o.G, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); } [Fact] public void RootHidden_Recursive() { var source = @"using System.Diagnostics; class A { internal A(object o) { this.F = o; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal object F; } class B { internal B(object o) { this.F = o; } internal object F; }"; var assembly = GetAssembly(source); var typeA = assembly.GetType("A"); var typeB = assembly.GetType("B"); var value = CreateDkmClrValue( value: typeA.Instantiate(typeA.Instantiate(typeA.Instantiate(typeB.Instantiate(4)))), type: new DkmClrType((TypeImpl)typeA), evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{A}", "A", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "4", "object {int}", "((B)((A)((A)o.F).F).F).F")); } [Fact] public void RootHidden_OnStaticMembers() { var source = @"using System.Diagnostics; class A { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal static object F = new B(); } class B { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal static object P { get { return new C(); } } internal static object G = 1; } class C { internal static object Q { get { return 3; } } internal object H = 2; }"; var assembly = GetAssembly(source); var type = assembly.GetType("A"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{A}", "A", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Static members", null, "", "A", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); children = GetChildren(children[0]); Verify(children, EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); children = GetChildren(children[0]); Verify(children, EvalResult("G", "1", "object {int}", "B.G"), EvalResult("H", "2", "object {int}", "((C)B.P).H"), EvalResult("Static members", null, "", "C", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); children = GetChildren(children[2]); Verify(children, EvalResult("Q", "3", "object {int}", "C.Q", DkmEvaluationResultFlags.ReadOnly)); } // Dev12 exposes the contents of RootHidden members even // if the members are private (e.g.: ImmutableArray<T>). [Fact] public void RootHidden_OnNonPublicMembers() { var source = @"using System.Diagnostics; public class C<T> { public C(params T[] items) { this.items = items; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] private T[] items; }"; var assembly = GetAssembly(source); var runtime = new DkmClrRuntimeInstance(new Assembly[0]); var type = assembly.GetType("C`1").MakeGenericType(typeof(int)); var value = CreateDkmClrValue( value: type.Instantiate(1, 2, 3), type: new DkmClrType(runtime.DefaultModule, runtime.DefaultAppDomain, (TypeImpl)type), evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers)); Verify(evalResult, EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "1", "int", "o.items[0]"), EvalResult("[1]", "2", "int", "o.items[1]"), EvalResult("[2]", "3", "int", "o.items[2]")); } // Dev12 does not merge "Static members" (or "Non-Public // members") across multiple RootHidden members. In // other words, there may be multiple "Static members" (or // "Non-Public members") rows within the same container. [Fact] public void RootHidden_WithStaticAndNonPublicMembers() { var source = @"using System.Diagnostics; public class A { public static int PA { get { return 1; } } internal int FA = 2; } public class B { internal int PB { get { return 3; } } public static int FB = 4; } public class C { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public readonly object FA = new A(); [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public object PB { get { return new B(); } } public static int PC { get { return 5; } } internal int FC = 6; }"; var assembly = GetAssembly(source); var runtime = new DkmClrRuntimeInstance(new Assembly[0]); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: new DkmClrType(runtime.DefaultModule, runtime.DefaultAppDomain, (TypeImpl)type), evalFlags: DkmEvaluationResultFlags.None); var inspectionContext = CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers); var evalResult = FormatResult("o", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult, inspectionContext: inspectionContext); Verify(children, EvalResult("Static members", null, "", "A", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class), EvalResult("Non-Public members", null, "", "o.FA, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class), EvalResult("Non-Public members", null, "", "o.PB, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("Static members", null, "", "C", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class), EvalResult("Non-Public members", null, "", "o, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); Verify(GetChildren(children[0]), EvalResult("PA", "1", "int", "A.PA", DkmEvaluationResultFlags.ReadOnly)); Verify(GetChildren(children[1]), EvalResult("FA", "2", "int", "((A)o.FA).FA")); Verify(GetChildren(children[2]), EvalResult("FB", "4", "int", "B.FB")); Verify(GetChildren(children[3]), EvalResult("PB", "3", "int", "((B)o.PB).PB", DkmEvaluationResultFlags.ReadOnly)); Verify(GetChildren(children[4]), EvalResult("PC", "5", "int", "C.PC", DkmEvaluationResultFlags.ReadOnly)); Verify(GetChildren(children[5]), EvalResult("FC", "6", "int", "o.FC")); } [Fact] public void ConstructedGenericType() { var source = @" using System.Diagnostics; public class C<T> { public T X; [DebuggerBrowsable(DebuggerBrowsableState.Never)] public T Y; } "; var assembly = GetAssembly(source); var type = assembly.GetType("C`1").MakeGenericType(typeof(int)); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(evalResult), EvalResult("X", "0", "int", "o.X", DkmEvaluationResultFlags.CanFavorite)); } [WorkItem(18581, "https://github.com/dotnet/roslyn/issues/18581")] [Fact] public void AccessibilityNotTrumpedByAttribute() { var source = @"using System.Diagnostics; class C { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private int[] _someArray = { 10, 20 }; private object SomethingPrivate = 3; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] internal object InternalCollapsed { get { return 1; } } [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] private object PrivateCollapsed { get { return 3; } } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] private int[] PrivateRootHidden { get { return _someArray; } } }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("new C()", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers)); Verify(evalResult, EvalResult("new C()", "{C}", "C", "new C()", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "10", "int", "(new C()).PrivateRootHidden[0]"), EvalResult("[1]", "20", "int", "(new C()).PrivateRootHidden[1]"), EvalResult("Non-Public members", null, "", "new C(), hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); var nonPublicChildren = GetChildren(children[2]); Verify(nonPublicChildren, EvalResult("InternalCollapsed", "1", "object {int}", "(new C()).InternalCollapsed", DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Internal), EvalResult("PrivateCollapsed", "3", "object {int}", "(new C()).PrivateCollapsed", DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Private), EvalResult("SomethingPrivate", "3", "object {int}", "(new C()).SomethingPrivate", DkmEvaluationResultFlags.None, DkmEvaluationResultCategory.Data, DkmEvaluationResultAccessType.Private)); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Compilers/CSharp/Portable/Utilities/ValueSetFactory.SByteTC.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { using static BinaryOperatorKind; internal static partial class ValueSetFactory { private struct SByteTC : INumericTC<sbyte> { sbyte INumericTC<sbyte>.MinValue => sbyte.MinValue; sbyte INumericTC<sbyte>.MaxValue => sbyte.MaxValue; sbyte INumericTC<sbyte>.Zero => 0; bool INumericTC<sbyte>.Related(BinaryOperatorKind relation, sbyte left, sbyte right) { switch (relation) { case Equal: return left == right; case GreaterThanOrEqual: return left >= right; case GreaterThan: return left > right; case LessThanOrEqual: return left <= right; case LessThan: return left < right; default: throw new ArgumentException("relation"); } } sbyte INumericTC<sbyte>.Next(sbyte value) { Debug.Assert(value != sbyte.MaxValue); return (sbyte)(value + 1); } sbyte INumericTC<sbyte>.Prev(sbyte value) { Debug.Assert(value != sbyte.MinValue); return (sbyte)(value - 1); } sbyte INumericTC<sbyte>.FromConstantValue(ConstantValue constantValue) => constantValue.IsBad ? (sbyte)0 : constantValue.SByteValue; public ConstantValue ToConstantValue(sbyte value) => ConstantValue.Create(value); string INumericTC<sbyte>.ToString(sbyte value) => value.ToString(); sbyte INumericTC<sbyte>.Random(Random random) { return (sbyte)random.Next(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { using static BinaryOperatorKind; internal static partial class ValueSetFactory { private struct SByteTC : INumericTC<sbyte> { sbyte INumericTC<sbyte>.MinValue => sbyte.MinValue; sbyte INumericTC<sbyte>.MaxValue => sbyte.MaxValue; sbyte INumericTC<sbyte>.Zero => 0; bool INumericTC<sbyte>.Related(BinaryOperatorKind relation, sbyte left, sbyte right) { switch (relation) { case Equal: return left == right; case GreaterThanOrEqual: return left >= right; case GreaterThan: return left > right; case LessThanOrEqual: return left <= right; case LessThan: return left < right; default: throw new ArgumentException("relation"); } } sbyte INumericTC<sbyte>.Next(sbyte value) { Debug.Assert(value != sbyte.MaxValue); return (sbyte)(value + 1); } sbyte INumericTC<sbyte>.Prev(sbyte value) { Debug.Assert(value != sbyte.MinValue); return (sbyte)(value - 1); } sbyte INumericTC<sbyte>.FromConstantValue(ConstantValue constantValue) => constantValue.IsBad ? (sbyte)0 : constantValue.SByteValue; public ConstantValue ToConstantValue(sbyte value) => ConstantValue.Create(value); string INumericTC<sbyte>.ToString(sbyte value) => value.ToString(); sbyte INumericTC<sbyte>.Random(Random random) { return (sbyte)random.Next(); } } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/EditorFeatures/Test2/Rename/VisualBasic/DeclarationConflictTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.VisualBasic <[UseExportProvider]> Public Class DeclarationConflictTests Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenFields(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module GooModule Dim [|$$goo|] As Integer Dim {|Conflict:bar|} As Integer End Module </Document> </Project> </Workspace>, host:=host, renameTo:="bar") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenFieldAndMethod(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module GooModule Dim [|$$goo|] As Integer Sub {|Conflict:bar|}() End Module </Document> </Project> </Workspace>, host:=host, renameTo:="bar") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenTwoMethodsWithSameSignature(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module GooModule Sub [|$$goo|]() End Sub Sub {|Conflict:bar|}() End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="bar") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenTwoParameters(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module GooModule Sub f([|$$goo|] As Integer, {|Conflict:bar|} As Integer) End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="bar") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub NoConflictBetweenMethodsWithDifferentSignatures(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module GooModule Sub [|$$goo|]() End Sub Sub bar(parameter As Integer) End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="bar") End Using End Sub <Theory> <WorkItem(543245, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543245")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenTwoLocals(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main(args As String()) Dim {|stmt1:$$i|} = 1 Dim {|Conflict:j|} = 2 End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="j") result.AssertLabeledSpansAre("stmt1", "j", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(543245, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543245")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenLocalAndParameter(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main({|Conflict:args|} As String()) Dim {|stmt1:$$i|} = 1 End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="args") result.AssertLabeledSpansAre("stmt1", "args", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(545859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545859")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenQueryVariableAndParameter(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main({|Conflict:args|} As String()) Dim z = From {|stmt1:$$x|} In args End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="args") result.AssertLabeledSpansAre("stmt1", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(545859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545859")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenTwoQueryVariables(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main(args As String()) Dim z = From {|Conflict:x|} In args From {|stmt1:$$y|} In args End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="x") result.AssertLabeledSpansAre("stmt1", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(543654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543654")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenLambdaParametersInsideMethod(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Module M1 Sub Main() Dim y = Sub({|Conflict:c|}) Call (Sub(a, {|stmt1:$$b|}) Exit Sub)(c) End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="c") result.AssertLabeledSpansAre("stmt1", "c", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(543654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543654")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenLambdaParametersInFieldInitializer(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Module M1 Dim y = Sub({|Conflict:c|}) Call (Sub({|stmt:$$b|}) Exit Sub)(c) End Module </Document> </Project> </Workspace>, host:=host, renameTo:="c") result.AssertLabeledSpansAre("stmt", "c", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(543654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543654")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub NoConflictBetweenLambdaParameterAndField(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Module M1 Dim y = Sub({|fieldinit:$$c|}) Exit Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="y") result.AssertLabeledSpansAre("fieldinit", "y", RelatedLocationType.NoConflict) End Using End Sub <Theory> <WorkItem(543407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543407")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenLabels(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Program Sub Main() {|Conflict:Goo|}: [|$$Bar|]: Dim f = Sub() Goo: End Sub End Sub End Class </Document> </Project> </Workspace>, host:=host, renameTo:="Goo") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(543308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543308")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenMethodsDifferingByByRef(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub {|Conflict:a|}(x As Integer) End Sub Sub [|$$c|](ByRef x As Integer) End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="a") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(543308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543308")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenMethodsDifferingByOptional(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub {|Conflict:a|}(x As Integer) End Sub Sub [|$$d|](x As Integer, Optional y As Integer = 0) End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="a") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(543308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543308")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub NoConflictBetweenMethodsDifferingByArity(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub a(Of T)(x As Integer) End Sub Sub [|$$d|](x As Integer, Optional y As Integer = 0) End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="a") End Using End Sub <Theory> <WorkItem(546902, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546902")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenImplicitlyDeclaredLocalAndNamespace(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Explicit Off Module Program Sub Main() __ = {|Conflict1:$$Google|} {|Conflict2:Google|} = __ End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="Microsoft") result.AssertLabeledSpansAre("Conflict1", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("Conflict2", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(529556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529556")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenImplicitlyDeclaredLocalAndAndGlobalFunction(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports Microsoft.VisualBasic Module Module1 Sub Main() Dim a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} Dim q = From i In a Where i Mod 2 = 0 Select Function() i * i For Each {|Conflict:$$sq|} In q Console.Write({|Conflict:sq|}()) Next End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="Write") result.AssertLabeledSpansAre("Conflict", "Write", RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(542217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542217")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenAliases(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports A = X.Something Imports {|Conflict:$$B|} = X.SomethingElse Namespace X Class Something End Class Class SomethingElse End Class End Namespace </Document> </Project> </Workspace>, host:=host, renameTo:="A") result.AssertLabeledSpansAre("Conflict", "A", RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(530125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530125")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenImplicitVariableAndClass(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Explicit Off Class X End Class Module M Sub Main() {|conflict:$$Y|} = 1 End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="X") result.AssertLabeledSpansAre("conflict", "X", RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(530038, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530038")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenEquallyNamedAlias(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports [|$$A|] = NS1.Something Imports {|conflict1:Something|} = NS1 Namespace NS1 Class Something Public Something() End Class End Namespace Class Program Dim a As {|noconflict:A|} Dim q As {|conflict2:Something|}.{|conflict3:Something|} End Class </Document> </Project> </Workspace>, host:=host, renameTo:="Something") result.AssertLabeledSpansAre("conflict1", "Something", RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("conflict2", "NS1", RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("conflict3", "Something", RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("noconflict", "Something", RelatedLocationType.NoConflict) End Using End Sub <Theory> <WorkItem(610120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610120")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenEquallyNamedPropertyAndItsParameter_1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class A Public Property [|$$X|]({|declconflict:Y|} As Integer) As Integer Get Return 0 End Get Set End Set End Property End Class </Document> </Project> </Workspace>, host:=host, renameTo:="Y") result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(610120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610120")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenEquallyNamedPropertyAndItsParameter_2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class A Public Overridable Property [|X|]({|declconflict:Y|} As Integer) As Integer Get Return 0 End Get Set End Set End Property End Class Public Class B Inherits A Public Overrides Property [|$$X|]({|declconflict:y|} As Integer) As Integer Get Return 0 End Get Set End Set End Property End Class Public Class C Inherits A Public Overrides Property [|X|]({|declconflict:y|} As Integer) As Integer Get Return 0 End Get Set End Set End Property End Class </Document> </Project> </Workspace>, host:=host, renameTo:="Y") result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(610120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610120")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenEquallyNamedPropertyAndItsParameter_3(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class A Public Overridable Property {|declconflict:X|}([|$$Y|] As Integer) As Integer Get Return 0 End Get Set End Set End Property End Class </Document> </Project> </Workspace>, host:=host, renameTo:="X") result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(608198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608198"), WorkItem(798375, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798375")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictInFieldInitializerOfFieldAndModuleNameResolvedThroughFullQualification(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Module [|$$M|] ' Rename M to X Dim x As Action = Sub() Console.WriteLine({|stmt1:M|}.x) End Module </Document> </Project> </Workspace>, host:=host, renameTo:="X") result.AssertLabeledSpansAre("stmt1", "Console.WriteLine(Global.X.x)", type:=RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory> <WorkItem(528706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528706")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForForEachLoopVariableNotBindingToTypeAnyMore(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Namespace X Module Program Sub Main For Each {|conflict:x|} In "" Next End Sub End Module End Namespace Namespace X Class [|$$X|] ' Rename X to M End Class End Namespace </Document> </Project> </Workspace>, host:=host, renameTo:="M") result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForForEachLoopVariableAndRangeVariable_1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Imports System.Linq Namespace X Module Program Sub Main For Each {|ctrlvar:goo|} In {1, 2, 3} Dim y As Integer = (From {|conflict:g|} In {{|broken:goo|}} Select g).First() Console.WriteLine({|stmt:$$goo|}) Next End Sub End Module End Namespace </Document> </Project> </Workspace>, host:=host, renameTo:="g") result.AssertLabeledSpansAre("ctrlvar", "g", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("broken", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt", "g", type:=RelatedLocationType.NoConflict) End Using End Sub <Theory> <WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForForEachLoopVariableAndRangeVariable_2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Imports System.Linq Namespace X Module Program Sub Main For Each {|ctrlvar:goo|} As Integer In {1, 2, 3} Dim y As Integer = (From {|conflict:g|} In {{|broken:goo|}} Select g).First() Console.WriteLine({|stmt:$$goo|}) Next End Sub End Module End Namespace </Document> </Project> </Workspace>, host:=host, renameTo:="g") result.AssertLabeledSpansAre("ctrlvar", "g", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("broken", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt", "g", type:=RelatedLocationType.NoConflict) End Using End Sub <Theory> <WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForForEachLoopVariableAndRangeVariable_3(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Imports System.Linq Namespace X Module Program Sub Main Dim {|stmt1:goo|} as Integer For Each {|ctrlvar:goo|} In {1, 2, 3} Dim y As Integer = (From {|conflict:g|} In {{|broken:goo|}} Select g).First() Console.WriteLine({|stmt2:$$goo|}) Next End Sub End Module End Namespace </Document> </Project> </Workspace>, host:=host, renameTo:="g") result.AssertLabeledSpansAre("stmt1", "g", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("ctrlvar", "g", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("broken", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", "g", type:=RelatedLocationType.NoConflict) End Using End Sub <Theory> <WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForForEachLoopVariableAndRangeVariable_4(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Imports System.Linq Namespace X Module Program Public [|goo|] as Integer Sub Main For Each Program.{|ctrlvar:goo|} In {1, 2, 3} Dim y As Integer = (From g In {{|query:goo|}} Select g).First() Console.WriteLine({|stmt:$$goo|}) Next End Sub End Module End Namespace </Document> </Project> </Workspace>, host:=host, renameTo:="g") result.AssertLabeledSpansAre("ctrlvar", "g", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("query", "g", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt", "g", type:=RelatedLocationType.NoConflict) End Using End Sub <Theory> <WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForUsingVariableAndRangeVariable_1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Imports System.Linq Namespace X Module Program Sub Main Using {|usingstmt:v1|} = new Object, v2 as Object = new Object(), v3, v4 as new Object() Dim o As Object = (From {|declconflict:c|} In {{|query:v1|}} Select c).First() Console.WriteLine({|stmt:$$v1|}) End Using End Sub End Module End Namespace </Document> </Project> </Workspace>, host:=host, renameTo:="c") result.AssertLabeledSpansAre("usingstmt", "c", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("query", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt", "c", type:=RelatedLocationType.NoConflict) End Using End Sub <Theory> <WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForUsingVariableAndRangeVariable_2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Namespace X Module Program Sub Main Using {|usingstmt:v3|}, {|declconflict:v4|} as new Object() Dim o As Object = (From c In {{|query:v3|}} Select c).First() Console.WriteLine({|stmt:$$v3|}) End Using End Sub End Module End Namespace </Document> </Project> </Workspace>, host:=host, renameTo:="v4") result.AssertLabeledSpansAre("usingstmt", "v4", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("query", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt", "v4", type:=RelatedLocationType.NoConflict) End Using End Sub <WpfTheory(Skip:="657210")> <WorkItem(653311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/653311")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForUsingVariableAndRangeVariable_3(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Namespace X Module Program Sub Main Using {|usingstmt:v3|} as new Object() Dim o As Object = (From c In {{|query:v3|}} Let {|declconflict:d|} = c Select {|declconflict:d|}).First() Console.WriteLine({|stmt:$$v3|}) End Using End Sub End Module End Namespace </Document> </Project> </Workspace>, host:=host, renameTo:="d") result.AssertLabeledSpansAre("usingstmt", "d", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("query", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt", "d", type:=RelatedLocationType.NoConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForCatchVariable_1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Namespace X Module Program Sub Main Try Catch {|catchstmt:$$x|} as Exception dim {|declconflict:y|} = 23 End Try End Sub End Module End Namespace </Document> </Project> </Workspace>, host:=host, renameTo:="y") result.AssertLabeledSpansAre("catchstmt", "y", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictBetweenTypeParametersInTypeDeclaration(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Goo(Of {|declconflict:T|} as {New}, [|$$U|]) End Class </Document> </Project> </Workspace>, host:=host, renameTo:="T") result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictBetweenTypeParametersInMethodDeclaration_1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Goo Public Sub M(Of {|declconflict:T|} as {New}, [|$$U|])() End Sub End Class </Document> </Project> </Workspace>, host:=host, renameTo:="T") result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictBetweenTypeParametersInMethodDeclaration_2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Goo Public Sub M(Of {|declconflict:[T]|} as {New}, [|$$U|])() End Sub End Class </Document> </Project> </Workspace>, host:=host, renameTo:="t") result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictBetweenTypeParameterAndMember_1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Goo(Of {|declconflict:[T]|}) Public Sub [|$$M|]() End Sub End Class </Document> </Project> </Workspace>, host:=host, renameTo:="t") result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictBetweenTypeParameterAndMember_2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Goo(Of {|declconflict:[T]|}) Public [|$$M|] as Integer = 23 End Class </Document> </Project> </Workspace>, host:=host, renameTo:="t") result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(658437, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658437")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictBetweenEscapedForEachControlVariableAndQueryRangeVariable(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System.Linq Module Program Sub Main(args As String()) For Each {|stmt1:goo|} In {1, 2, 3} Dim x As Integer = (From {|declconflict:g|} In {{|stmt3:goo|}} Select g).First() Console.WriteLine({|stmt2:$$goo|}) Next End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="[g]") result.AssertLabeledSpansAre("stmt1", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt3", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(658801, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658801")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_OverridingImplicitlyUsedMethod(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Option Infer On Imports System Class A Public Property current As Integer Public Function MOVENext() As Boolean Return False End Function Public Function GetEnumerator() As C Return Me End Function End Class Class C Inherits A Shared Sub Main() For Each x In New C() Next End Sub Public Sub {|possibleImplicitConflict:$$Goo|}() ' Rename Goo to MoveNext End Sub End Class ]]></Document> </Project> </Workspace>, host:=host, renameTo:="movenext") result.AssertLabeledSpansAre("possibleImplicitConflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(682669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682669")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_OverridingImplicitlyUsedMethod_1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Option Infer On Imports System Class A Public Property current As Integer Public Function MOVENext() As Boolean Return False End Function Public Function GetEnumerator() As C Return Me End Function End Class Class C Inherits A Shared Sub Main() For Each x In New C() Next End Sub Public Overloads Sub [|$$Goo|](of T)() ' Rename Goo to MoveNext End Sub End Class ]]></Document> </Project> </Workspace>, host:=host, renameTo:="movenext") End Using End Sub <WorkItem(682669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682669")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_OverridingImplicitlyUsedMethod_2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Option Infer On Imports System Class A Public Property current As Integer Public Function MOVENext(of T)() As Boolean Return False End Function Public Function GetEnumerator() As C Return Me End Function End Class Class C Inherits A Shared Sub Main() End Sub Public Sub [|$$Goo|]() ' Rename Goo to MoveNext End Sub End Class ]]></Document> </Project> </Workspace>, host:=host, renameTo:="movenext") End Using End Sub <WorkItem(851604, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/851604")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictInsideSimpleArgument(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System.ComponentModel Imports System.Reflection Class C Const {|first:$$M|} As MemberTypes = MemberTypes.Method Delegate Sub D(&lt;DefaultValue({|second:M|})> x As Object); End Class </Document> </Project> </Workspace>, host:=host, renameTo:="Method") result.AssertLabeledSpansAre("first", "Method", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("second", "C.Method", type:=RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(18566, "https://github.com/dotnet/roslyn/issues/18566")> Public Sub ParameterInPartialMethodDefinitionConflictingWithLocalInPartialMethodImplementation(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Partial Class C Partial Private Sub M({|parameter0:$$x|} As Integer) End Sub End Class </Document> <Document> Partial Class C Private Sub M({|parameter1:x|} As Integer) Dim {|local0:y|} = 1 End Sub End Class </Document> </Project> </Workspace>, host:=host, renameTo:="y") result.AssertLabeledSpansAre("parameter0", "y", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("parameter1", "y", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("local0", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(941271, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/941271")> Public Sub AsNewClauseSpeculationResolvesConflicts(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Main Private T As {|class0:$$Test|} = Nothing End Class Public Class {|class1:Test|} Private Rnd As New {|classConflict:Random|} End Class </Document> </Project> </Workspace>, host:=host, renameTo:="Random") result.AssertLabeledSpansAre("class0", "Random", RelatedLocationType.ResolvedReferenceConflict) result.AssertLabeledSpansAre("class1", "Random", RelatedLocationType.ResolvedReferenceConflict) result.AssertLabeledSpansAre("classConflict", "System.Random", type:=RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.VisualBasic <[UseExportProvider]> Public Class DeclarationConflictTests Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenFields(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module GooModule Dim [|$$goo|] As Integer Dim {|Conflict:bar|} As Integer End Module </Document> </Project> </Workspace>, host:=host, renameTo:="bar") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenFieldAndMethod(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module GooModule Dim [|$$goo|] As Integer Sub {|Conflict:bar|}() End Module </Document> </Project> </Workspace>, host:=host, renameTo:="bar") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenTwoMethodsWithSameSignature(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module GooModule Sub [|$$goo|]() End Sub Sub {|Conflict:bar|}() End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="bar") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenTwoParameters(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module GooModule Sub f([|$$goo|] As Integer, {|Conflict:bar|} As Integer) End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="bar") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub NoConflictBetweenMethodsWithDifferentSignatures(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module GooModule Sub [|$$goo|]() End Sub Sub bar(parameter As Integer) End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="bar") End Using End Sub <Theory> <WorkItem(543245, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543245")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenTwoLocals(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main(args As String()) Dim {|stmt1:$$i|} = 1 Dim {|Conflict:j|} = 2 End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="j") result.AssertLabeledSpansAre("stmt1", "j", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(543245, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543245")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenLocalAndParameter(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main({|Conflict:args|} As String()) Dim {|stmt1:$$i|} = 1 End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="args") result.AssertLabeledSpansAre("stmt1", "args", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(545859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545859")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenQueryVariableAndParameter(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main({|Conflict:args|} As String()) Dim z = From {|stmt1:$$x|} In args End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="args") result.AssertLabeledSpansAre("stmt1", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(545859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545859")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenTwoQueryVariables(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main(args As String()) Dim z = From {|Conflict:x|} In args From {|stmt1:$$y|} In args End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="x") result.AssertLabeledSpansAre("stmt1", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(543654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543654")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenLambdaParametersInsideMethod(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Module M1 Sub Main() Dim y = Sub({|Conflict:c|}) Call (Sub(a, {|stmt1:$$b|}) Exit Sub)(c) End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="c") result.AssertLabeledSpansAre("stmt1", "c", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(543654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543654")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenLambdaParametersInFieldInitializer(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Module M1 Dim y = Sub({|Conflict:c|}) Call (Sub({|stmt:$$b|}) Exit Sub)(c) End Module </Document> </Project> </Workspace>, host:=host, renameTo:="c") result.AssertLabeledSpansAre("stmt", "c", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(543654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543654")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub NoConflictBetweenLambdaParameterAndField(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Module M1 Dim y = Sub({|fieldinit:$$c|}) Exit Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="y") result.AssertLabeledSpansAre("fieldinit", "y", RelatedLocationType.NoConflict) End Using End Sub <Theory> <WorkItem(543407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543407")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenLabels(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Program Sub Main() {|Conflict:Goo|}: [|$$Bar|]: Dim f = Sub() Goo: End Sub End Sub End Class </Document> </Project> </Workspace>, host:=host, renameTo:="Goo") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(543308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543308")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenMethodsDifferingByByRef(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub {|Conflict:a|}(x As Integer) End Sub Sub [|$$c|](ByRef x As Integer) End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="a") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(543308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543308")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenMethodsDifferingByOptional(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub {|Conflict:a|}(x As Integer) End Sub Sub [|$$d|](x As Integer, Optional y As Integer = 0) End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="a") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(543308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543308")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub NoConflictBetweenMethodsDifferingByArity(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub a(Of T)(x As Integer) End Sub Sub [|$$d|](x As Integer, Optional y As Integer = 0) End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="a") End Using End Sub <Theory> <WorkItem(546902, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546902")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenImplicitlyDeclaredLocalAndNamespace(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Explicit Off Module Program Sub Main() __ = {|Conflict1:$$Google|} {|Conflict2:Google|} = __ End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="Microsoft") result.AssertLabeledSpansAre("Conflict1", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("Conflict2", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(529556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529556")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenImplicitlyDeclaredLocalAndAndGlobalFunction(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports Microsoft.VisualBasic Module Module1 Sub Main() Dim a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} Dim q = From i In a Where i Mod 2 = 0 Select Function() i * i For Each {|Conflict:$$sq|} In q Console.Write({|Conflict:sq|}()) Next End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="Write") result.AssertLabeledSpansAre("Conflict", "Write", RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(542217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542217")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenAliases(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports A = X.Something Imports {|Conflict:$$B|} = X.SomethingElse Namespace X Class Something End Class Class SomethingElse End Class End Namespace </Document> </Project> </Workspace>, host:=host, renameTo:="A") result.AssertLabeledSpansAre("Conflict", "A", RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(530125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530125")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenImplicitVariableAndClass(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Explicit Off Class X End Class Module M Sub Main() {|conflict:$$Y|} = 1 End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="X") result.AssertLabeledSpansAre("conflict", "X", RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(530038, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530038")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenEquallyNamedAlias(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports [|$$A|] = NS1.Something Imports {|conflict1:Something|} = NS1 Namespace NS1 Class Something Public Something() End Class End Namespace Class Program Dim a As {|noconflict:A|} Dim q As {|conflict2:Something|}.{|conflict3:Something|} End Class </Document> </Project> </Workspace>, host:=host, renameTo:="Something") result.AssertLabeledSpansAre("conflict1", "Something", RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("conflict2", "NS1", RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("conflict3", "Something", RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("noconflict", "Something", RelatedLocationType.NoConflict) End Using End Sub <Theory> <WorkItem(610120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610120")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenEquallyNamedPropertyAndItsParameter_1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class A Public Property [|$$X|]({|declconflict:Y|} As Integer) As Integer Get Return 0 End Get Set End Set End Property End Class </Document> </Project> </Workspace>, host:=host, renameTo:="Y") result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(610120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610120")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenEquallyNamedPropertyAndItsParameter_2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class A Public Overridable Property [|X|]({|declconflict:Y|} As Integer) As Integer Get Return 0 End Get Set End Set End Property End Class Public Class B Inherits A Public Overrides Property [|$$X|]({|declconflict:y|} As Integer) As Integer Get Return 0 End Get Set End Set End Property End Class Public Class C Inherits A Public Overrides Property [|X|]({|declconflict:y|} As Integer) As Integer Get Return 0 End Get Set End Set End Property End Class </Document> </Project> </Workspace>, host:=host, renameTo:="Y") result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(610120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610120")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenEquallyNamedPropertyAndItsParameter_3(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class A Public Overridable Property {|declconflict:X|}([|$$Y|] As Integer) As Integer Get Return 0 End Get Set End Set End Property End Class </Document> </Project> </Workspace>, host:=host, renameTo:="X") result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(608198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608198"), WorkItem(798375, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798375")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictInFieldInitializerOfFieldAndModuleNameResolvedThroughFullQualification(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Module [|$$M|] ' Rename M to X Dim x As Action = Sub() Console.WriteLine({|stmt1:M|}.x) End Module </Document> </Project> </Workspace>, host:=host, renameTo:="X") result.AssertLabeledSpansAre("stmt1", "Console.WriteLine(Global.X.x)", type:=RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory> <WorkItem(528706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528706")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForForEachLoopVariableNotBindingToTypeAnyMore(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Namespace X Module Program Sub Main For Each {|conflict:x|} In "" Next End Sub End Module End Namespace Namespace X Class [|$$X|] ' Rename X to M End Class End Namespace </Document> </Project> </Workspace>, host:=host, renameTo:="M") result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForForEachLoopVariableAndRangeVariable_1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Imports System.Linq Namespace X Module Program Sub Main For Each {|ctrlvar:goo|} In {1, 2, 3} Dim y As Integer = (From {|conflict:g|} In {{|broken:goo|}} Select g).First() Console.WriteLine({|stmt:$$goo|}) Next End Sub End Module End Namespace </Document> </Project> </Workspace>, host:=host, renameTo:="g") result.AssertLabeledSpansAre("ctrlvar", "g", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("broken", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt", "g", type:=RelatedLocationType.NoConflict) End Using End Sub <Theory> <WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForForEachLoopVariableAndRangeVariable_2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Imports System.Linq Namespace X Module Program Sub Main For Each {|ctrlvar:goo|} As Integer In {1, 2, 3} Dim y As Integer = (From {|conflict:g|} In {{|broken:goo|}} Select g).First() Console.WriteLine({|stmt:$$goo|}) Next End Sub End Module End Namespace </Document> </Project> </Workspace>, host:=host, renameTo:="g") result.AssertLabeledSpansAre("ctrlvar", "g", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("broken", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt", "g", type:=RelatedLocationType.NoConflict) End Using End Sub <Theory> <WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForForEachLoopVariableAndRangeVariable_3(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Imports System.Linq Namespace X Module Program Sub Main Dim {|stmt1:goo|} as Integer For Each {|ctrlvar:goo|} In {1, 2, 3} Dim y As Integer = (From {|conflict:g|} In {{|broken:goo|}} Select g).First() Console.WriteLine({|stmt2:$$goo|}) Next End Sub End Module End Namespace </Document> </Project> </Workspace>, host:=host, renameTo:="g") result.AssertLabeledSpansAre("stmt1", "g", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("ctrlvar", "g", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("broken", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", "g", type:=RelatedLocationType.NoConflict) End Using End Sub <Theory> <WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForForEachLoopVariableAndRangeVariable_4(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Imports System.Linq Namespace X Module Program Public [|goo|] as Integer Sub Main For Each Program.{|ctrlvar:goo|} In {1, 2, 3} Dim y As Integer = (From g In {{|query:goo|}} Select g).First() Console.WriteLine({|stmt:$$goo|}) Next End Sub End Module End Namespace </Document> </Project> </Workspace>, host:=host, renameTo:="g") result.AssertLabeledSpansAre("ctrlvar", "g", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("query", "g", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt", "g", type:=RelatedLocationType.NoConflict) End Using End Sub <Theory> <WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForUsingVariableAndRangeVariable_1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Imports System.Linq Namespace X Module Program Sub Main Using {|usingstmt:v1|} = new Object, v2 as Object = new Object(), v3, v4 as new Object() Dim o As Object = (From {|declconflict:c|} In {{|query:v1|}} Select c).First() Console.WriteLine({|stmt:$$v1|}) End Using End Sub End Module End Namespace </Document> </Project> </Workspace>, host:=host, renameTo:="c") result.AssertLabeledSpansAre("usingstmt", "c", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("query", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt", "c", type:=RelatedLocationType.NoConflict) End Using End Sub <Theory> <WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForUsingVariableAndRangeVariable_2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Namespace X Module Program Sub Main Using {|usingstmt:v3|}, {|declconflict:v4|} as new Object() Dim o As Object = (From c In {{|query:v3|}} Select c).First() Console.WriteLine({|stmt:$$v3|}) End Using End Sub End Module End Namespace </Document> </Project> </Workspace>, host:=host, renameTo:="v4") result.AssertLabeledSpansAre("usingstmt", "v4", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("query", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt", "v4", type:=RelatedLocationType.NoConflict) End Using End Sub <WpfTheory(Skip:="657210")> <WorkItem(653311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/653311")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForUsingVariableAndRangeVariable_3(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Namespace X Module Program Sub Main Using {|usingstmt:v3|} as new Object() Dim o As Object = (From c In {{|query:v3|}} Let {|declconflict:d|} = c Select {|declconflict:d|}).First() Console.WriteLine({|stmt:$$v3|}) End Using End Sub End Module End Namespace </Document> </Project> </Workspace>, host:=host, renameTo:="d") result.AssertLabeledSpansAre("usingstmt", "d", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("query", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt", "d", type:=RelatedLocationType.NoConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForCatchVariable_1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Namespace X Module Program Sub Main Try Catch {|catchstmt:$$x|} as Exception dim {|declconflict:y|} = 23 End Try End Sub End Module End Namespace </Document> </Project> </Workspace>, host:=host, renameTo:="y") result.AssertLabeledSpansAre("catchstmt", "y", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictBetweenTypeParametersInTypeDeclaration(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Goo(Of {|declconflict:T|} as {New}, [|$$U|]) End Class </Document> </Project> </Workspace>, host:=host, renameTo:="T") result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictBetweenTypeParametersInMethodDeclaration_1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Goo Public Sub M(Of {|declconflict:T|} as {New}, [|$$U|])() End Sub End Class </Document> </Project> </Workspace>, host:=host, renameTo:="T") result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictBetweenTypeParametersInMethodDeclaration_2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Goo Public Sub M(Of {|declconflict:[T]|} as {New}, [|$$U|])() End Sub End Class </Document> </Project> </Workspace>, host:=host, renameTo:="t") result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictBetweenTypeParameterAndMember_1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Goo(Of {|declconflict:[T]|}) Public Sub [|$$M|]() End Sub End Class </Document> </Project> </Workspace>, host:=host, renameTo:="t") result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictBetweenTypeParameterAndMember_2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Goo(Of {|declconflict:[T]|}) Public [|$$M|] as Integer = 23 End Class </Document> </Project> </Workspace>, host:=host, renameTo:="t") result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(658437, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658437")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictBetweenEscapedForEachControlVariableAndQueryRangeVariable(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System.Linq Module Program Sub Main(args As String()) For Each {|stmt1:goo|} In {1, 2, 3} Dim x As Integer = (From {|declconflict:g|} In {{|stmt3:goo|}} Select g).First() Console.WriteLine({|stmt2:$$goo|}) Next End Sub End Module </Document> </Project> </Workspace>, host:=host, renameTo:="[g]") result.AssertLabeledSpansAre("stmt1", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt3", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(658801, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658801")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_OverridingImplicitlyUsedMethod(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Option Infer On Imports System Class A Public Property current As Integer Public Function MOVENext() As Boolean Return False End Function Public Function GetEnumerator() As C Return Me End Function End Class Class C Inherits A Shared Sub Main() For Each x In New C() Next End Sub Public Sub {|possibleImplicitConflict:$$Goo|}() ' Rename Goo to MoveNext End Sub End Class ]]></Document> </Project> </Workspace>, host:=host, renameTo:="movenext") result.AssertLabeledSpansAre("possibleImplicitConflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(682669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682669")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_OverridingImplicitlyUsedMethod_1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Option Infer On Imports System Class A Public Property current As Integer Public Function MOVENext() As Boolean Return False End Function Public Function GetEnumerator() As C Return Me End Function End Class Class C Inherits A Shared Sub Main() For Each x In New C() Next End Sub Public Overloads Sub [|$$Goo|](of T)() ' Rename Goo to MoveNext End Sub End Class ]]></Document> </Project> </Workspace>, host:=host, renameTo:="movenext") End Using End Sub <WorkItem(682669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682669")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_OverridingImplicitlyUsedMethod_2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Option Infer On Imports System Class A Public Property current As Integer Public Function MOVENext(of T)() As Boolean Return False End Function Public Function GetEnumerator() As C Return Me End Function End Class Class C Inherits A Shared Sub Main() End Sub Public Sub [|$$Goo|]() ' Rename Goo to MoveNext End Sub End Class ]]></Document> </Project> </Workspace>, host:=host, renameTo:="movenext") End Using End Sub <WorkItem(851604, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/851604")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictInsideSimpleArgument(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System.ComponentModel Imports System.Reflection Class C Const {|first:$$M|} As MemberTypes = MemberTypes.Method Delegate Sub D(&lt;DefaultValue({|second:M|})> x As Object); End Class </Document> </Project> </Workspace>, host:=host, renameTo:="Method") result.AssertLabeledSpansAre("first", "Method", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("second", "C.Method", type:=RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(18566, "https://github.com/dotnet/roslyn/issues/18566")> Public Sub ParameterInPartialMethodDefinitionConflictingWithLocalInPartialMethodImplementation(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Partial Class C Partial Private Sub M({|parameter0:$$x|} As Integer) End Sub End Class </Document> <Document> Partial Class C Private Sub M({|parameter1:x|} As Integer) Dim {|local0:y|} = 1 End Sub End Class </Document> </Project> </Workspace>, host:=host, renameTo:="y") result.AssertLabeledSpansAre("parameter0", "y", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("parameter1", "y", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("local0", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(941271, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/941271")> Public Sub AsNewClauseSpeculationResolvesConflicts(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Main Private T As {|class0:$$Test|} = Nothing End Class Public Class {|class1:Test|} Private Rnd As New {|classConflict:Random|} End Class </Document> </Project> </Workspace>, host:=host, renameTo:="Random") result.AssertLabeledSpansAre("class0", "Random", RelatedLocationType.ResolvedReferenceConflict) result.AssertLabeledSpansAre("class1", "Random", RelatedLocationType.ResolvedReferenceConflict) result.AssertLabeledSpansAre("classConflict", "System.Random", type:=RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub End Class End Namespace
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Workspaces/Core/Portable/Workspace/Host/EventListener/IEventListener.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Host { /// <summary> /// provide a way for features to lazily subscribe to a service event for particular workspace /// /// see <see cref="WellKnownEventListeners"/> for supported services /// </summary> internal interface IEventListener { } }
// Licensed to the .NET Foundation under one or more 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 namespace Microsoft.CodeAnalysis.Host { /// <summary> /// provide a way for features to lazily subscribe to a service event for particular workspace /// /// see <see cref="WellKnownEventListeners"/> for supported services /// </summary> internal interface IEventListener { } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/VisualStudio/Core/Impl/CodeModel/AbstractCodeModelService.AbstractCodeModelEventCollector.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal partial class AbstractCodeModelService { protected abstract AbstractCodeModelEventCollector CreateCodeModelEventCollector(); protected abstract class AbstractCodeModelEventCollector { private const int MaxChildDelta = 5; protected readonly AbstractCodeModelService CodeModelService; protected AbstractCodeModelEventCollector(AbstractCodeModelService codeModelService) => this.CodeModelService = codeModelService; protected abstract void CollectCore(SyntaxNode oldRoot, SyntaxNode newRoot, CodeModelEventQueue eventQueue); protected abstract void EnqueueAddEvent(SyntaxNode node, SyntaxNode parent, CodeModelEventQueue eventQueue); protected abstract void EnqueueRemoveEvent(SyntaxNode node, SyntaxNode parent, CodeModelEventQueue eventQueue); protected abstract void EnqueueChangeEvent(SyntaxNode node, SyntaxNode parent, CodeModelEventType eventType, CodeModelEventQueue eventQueue); public Queue<CodeModelEvent> Collect(SyntaxTree oldTree, SyntaxTree newTree) { var queue = new Queue<CodeModelEvent>(); var eventQueue = new CodeModelEventQueue(queue); CollectCore(oldTree.GetRoot(CancellationToken.None), newTree.GetRoot(CancellationToken.None), eventQueue); return queue; } protected delegate bool NodeComparison<TNode, TParent>( TNode oldNode, TNode newNode, TParent newNodeParent, CodeModelEventQueue eventQueue) where TNode : SyntaxNode where TParent : SyntaxNode; protected enum DeclarationChange { WholeDeclaration, NameOnly } protected bool CompareChildren<TNode, TParent>( NodeComparison<TNode, TParent> compare, IReadOnlyList<TNode> oldChildren, IReadOnlyList<TNode> newChildren, TParent newNodeParent, CodeModelEventType eventType, CodeModelEventQueue eventQueue) where TNode : SyntaxNode where TParent : SyntaxNode { var oldCount = oldChildren.Count; var newCount = newChildren.Count; if (oldCount == newCount) { return FindDifferentChild(compare, oldChildren, newChildren, newNodeParent, eventQueue); } else if (Math.Abs(oldCount - newCount) > MaxChildDelta) { // We got two discrepancies, enqueue element changed node for containing node EnqueueChangeEvent(newNodeParent, null, eventType, eventQueue); } else { if (oldCount > newCount) { FindRemovedChild(compare, oldChildren, newChildren, newNodeParent, oldCount - newCount, eventQueue); } else { FindAddedChild(compare, oldChildren, newChildren, newNodeParent, newCount - oldCount, eventQueue); } } return false; } protected DeclarationChange CompareRenamedDeclarations<TNode, TParent>( NodeComparison<TNode, TParent> compare, IReadOnlyList<TNode> oldChildren, IReadOnlyList<TNode> newChildren, SyntaxNode oldNode, SyntaxNode newNode, TParent newNodeParent, CodeModelEventQueue eventQueue) where TNode : SyntaxNode where TParent : SyntaxNode { var oldCount = oldChildren.Count; var newCount = newChildren.Count; if (oldCount == newCount) { // We now check the children of the old and new types against each other. If any of them have changed, // it means that the old type has essentially been removed and a new one added. for (var i = 0; i < oldCount; i++) { if (!compare(oldChildren[i], newChildren[i], newNodeParent, null)) { EnqueueRemoveEvent(oldNode, newNodeParent, eventQueue); EnqueueAddEvent(newNode, newNodeParent, eventQueue); // Report that the whole declaration has changed return DeclarationChange.WholeDeclaration; } } // The children are all the same, so only the name has changed. return DeclarationChange.NameOnly; } else { // Since the number of members is different, essentially the old type has been removed, and a new one added. EnqueueRemoveEvent(oldNode, newNodeParent, eventQueue); EnqueueAddEvent(newNode, newNodeParent, eventQueue); // Report that the whole declaration has changed return DeclarationChange.WholeDeclaration; } } // Finds the child node which is different OR enqueues a unknown on containing node. private bool FindDifferentChild<TNode, TParent>( NodeComparison<TNode, TParent> compare, IReadOnlyList<TNode> oldChildren, IReadOnlyList<TNode> newChildren, TParent newNodeParent, CodeModelEventQueue eventQueue) where TNode : SyntaxNode where TParent : SyntaxNode { Debug.Assert(oldChildren.Count == newChildren.Count); var eventCount = eventQueue != null ? eventQueue.Count : 0; var hasChanges = false; // Find first child that is different. int i; for (i = 0; i < oldChildren.Count; i++) { if (!compare(oldChildren[i], newChildren[i], newNodeParent, eventQueue)) { hasChanges = true; i++; break; } } // Look for a second different child. If there is one, we'll throw away any events from // the first different child and enqueue an unknown event on the containing node. for (; i < oldChildren.Count; i++) { if (!compare(oldChildren[i], newChildren[i], newNodeParent, null)) { // rollback any events added by the first difference if (eventQueue != null) { while (eventQueue.Count > eventCount) { eventQueue.Discard(); } } EnqueueChangeEvent(newNodeParent, null, CodeModelEventType.Unknown, eventQueue); return false; } } return !hasChanges; } private void FindAddedChild<TNode, TParent>( NodeComparison<TNode, TParent> compare, IReadOnlyList<TNode> oldChildren, IReadOnlyList<TNode> newChildren, TParent newNodeParent, int delta, CodeModelEventQueue eventQueue) where TNode : SyntaxNode where TParent : SyntaxNode { Debug.Assert(oldChildren.Count + delta == newChildren.Count); // The strategy is to assume that all of the added children are contiguous. // If that turns out not to be the case, an unknown change event is raised // for the containing node. var firstAdded = -1; // Look for the first different child. If there is one, track that index as // the first added node. int oldIndex, newIndex; for (oldIndex = 0, newIndex = 0; newIndex < newChildren.Count; oldIndex++, newIndex++) { if (oldIndex >= oldChildren.Count || !compare(oldChildren[oldIndex], newChildren[newIndex], newNodeParent, null)) { firstAdded = newIndex; newIndex += delta; break; } } // Look for a second different child. If there is one, we'll throw away any events from // the first different child and enqueue an unknown event on the containing node. for (; newIndex < newChildren.Count; oldIndex++, newIndex++) { if (!compare(oldChildren[oldIndex], newChildren[newIndex], newNodeParent, null)) { EnqueueChangeEvent(newNodeParent, null, CodeModelEventType.Unknown, eventQueue); return; } } if (firstAdded >= 0) { for (var i = 0; i < delta; i++) { EnqueueAddEvent(newChildren[firstAdded + i], newNodeParent, eventQueue); } } } private void FindRemovedChild<TNode, TParent>( NodeComparison<TNode, TParent> compare, IReadOnlyList<TNode> oldChildren, IReadOnlyList<TNode> newChildren, TParent newNodeParent, int delta, CodeModelEventQueue eventQueue) where TNode : SyntaxNode where TParent : SyntaxNode { Debug.Assert(oldChildren.Count - delta == newChildren.Count); // The strategy is to assume that all of the removed children are contiguous. // If that turns out not to be the case, an unknown change event is raised // for the containing node. var firstRemoved = -1; // Look for the first different child. If there is one, track that index as // the first added node. int oldIndex, newIndex; for (oldIndex = 0, newIndex = 0; oldIndex < oldChildren.Count; oldIndex++, newIndex++) { if (newIndex >= newChildren.Count || !compare(oldChildren[oldIndex], newChildren[newIndex], newNodeParent, null)) { firstRemoved = oldIndex; oldIndex += delta; break; } } // Look for a second different child. If there is one, we'll throw away any events from // the first different child and enqueue an unknown event on the containing node. for (; oldIndex < oldChildren.Count; oldIndex++, newIndex++) { if (!compare(oldChildren[oldIndex], newChildren[newIndex], newNodeParent, null)) { EnqueueChangeEvent(newNodeParent, null, CodeModelEventType.Unknown, eventQueue); return; } } if (firstRemoved >= 0) { for (var i = 0; i < delta; i++) { EnqueueRemoveEvent(oldChildren[firstRemoved + i], newNodeParent, eventQueue); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal partial class AbstractCodeModelService { protected abstract AbstractCodeModelEventCollector CreateCodeModelEventCollector(); protected abstract class AbstractCodeModelEventCollector { private const int MaxChildDelta = 5; protected readonly AbstractCodeModelService CodeModelService; protected AbstractCodeModelEventCollector(AbstractCodeModelService codeModelService) => this.CodeModelService = codeModelService; protected abstract void CollectCore(SyntaxNode oldRoot, SyntaxNode newRoot, CodeModelEventQueue eventQueue); protected abstract void EnqueueAddEvent(SyntaxNode node, SyntaxNode parent, CodeModelEventQueue eventQueue); protected abstract void EnqueueRemoveEvent(SyntaxNode node, SyntaxNode parent, CodeModelEventQueue eventQueue); protected abstract void EnqueueChangeEvent(SyntaxNode node, SyntaxNode parent, CodeModelEventType eventType, CodeModelEventQueue eventQueue); public Queue<CodeModelEvent> Collect(SyntaxTree oldTree, SyntaxTree newTree) { var queue = new Queue<CodeModelEvent>(); var eventQueue = new CodeModelEventQueue(queue); CollectCore(oldTree.GetRoot(CancellationToken.None), newTree.GetRoot(CancellationToken.None), eventQueue); return queue; } protected delegate bool NodeComparison<TNode, TParent>( TNode oldNode, TNode newNode, TParent newNodeParent, CodeModelEventQueue eventQueue) where TNode : SyntaxNode where TParent : SyntaxNode; protected enum DeclarationChange { WholeDeclaration, NameOnly } protected bool CompareChildren<TNode, TParent>( NodeComparison<TNode, TParent> compare, IReadOnlyList<TNode> oldChildren, IReadOnlyList<TNode> newChildren, TParent newNodeParent, CodeModelEventType eventType, CodeModelEventQueue eventQueue) where TNode : SyntaxNode where TParent : SyntaxNode { var oldCount = oldChildren.Count; var newCount = newChildren.Count; if (oldCount == newCount) { return FindDifferentChild(compare, oldChildren, newChildren, newNodeParent, eventQueue); } else if (Math.Abs(oldCount - newCount) > MaxChildDelta) { // We got two discrepancies, enqueue element changed node for containing node EnqueueChangeEvent(newNodeParent, null, eventType, eventQueue); } else { if (oldCount > newCount) { FindRemovedChild(compare, oldChildren, newChildren, newNodeParent, oldCount - newCount, eventQueue); } else { FindAddedChild(compare, oldChildren, newChildren, newNodeParent, newCount - oldCount, eventQueue); } } return false; } protected DeclarationChange CompareRenamedDeclarations<TNode, TParent>( NodeComparison<TNode, TParent> compare, IReadOnlyList<TNode> oldChildren, IReadOnlyList<TNode> newChildren, SyntaxNode oldNode, SyntaxNode newNode, TParent newNodeParent, CodeModelEventQueue eventQueue) where TNode : SyntaxNode where TParent : SyntaxNode { var oldCount = oldChildren.Count; var newCount = newChildren.Count; if (oldCount == newCount) { // We now check the children of the old and new types against each other. If any of them have changed, // it means that the old type has essentially been removed and a new one added. for (var i = 0; i < oldCount; i++) { if (!compare(oldChildren[i], newChildren[i], newNodeParent, null)) { EnqueueRemoveEvent(oldNode, newNodeParent, eventQueue); EnqueueAddEvent(newNode, newNodeParent, eventQueue); // Report that the whole declaration has changed return DeclarationChange.WholeDeclaration; } } // The children are all the same, so only the name has changed. return DeclarationChange.NameOnly; } else { // Since the number of members is different, essentially the old type has been removed, and a new one added. EnqueueRemoveEvent(oldNode, newNodeParent, eventQueue); EnqueueAddEvent(newNode, newNodeParent, eventQueue); // Report that the whole declaration has changed return DeclarationChange.WholeDeclaration; } } // Finds the child node which is different OR enqueues a unknown on containing node. private bool FindDifferentChild<TNode, TParent>( NodeComparison<TNode, TParent> compare, IReadOnlyList<TNode> oldChildren, IReadOnlyList<TNode> newChildren, TParent newNodeParent, CodeModelEventQueue eventQueue) where TNode : SyntaxNode where TParent : SyntaxNode { Debug.Assert(oldChildren.Count == newChildren.Count); var eventCount = eventQueue != null ? eventQueue.Count : 0; var hasChanges = false; // Find first child that is different. int i; for (i = 0; i < oldChildren.Count; i++) { if (!compare(oldChildren[i], newChildren[i], newNodeParent, eventQueue)) { hasChanges = true; i++; break; } } // Look for a second different child. If there is one, we'll throw away any events from // the first different child and enqueue an unknown event on the containing node. for (; i < oldChildren.Count; i++) { if (!compare(oldChildren[i], newChildren[i], newNodeParent, null)) { // rollback any events added by the first difference if (eventQueue != null) { while (eventQueue.Count > eventCount) { eventQueue.Discard(); } } EnqueueChangeEvent(newNodeParent, null, CodeModelEventType.Unknown, eventQueue); return false; } } return !hasChanges; } private void FindAddedChild<TNode, TParent>( NodeComparison<TNode, TParent> compare, IReadOnlyList<TNode> oldChildren, IReadOnlyList<TNode> newChildren, TParent newNodeParent, int delta, CodeModelEventQueue eventQueue) where TNode : SyntaxNode where TParent : SyntaxNode { Debug.Assert(oldChildren.Count + delta == newChildren.Count); // The strategy is to assume that all of the added children are contiguous. // If that turns out not to be the case, an unknown change event is raised // for the containing node. var firstAdded = -1; // Look for the first different child. If there is one, track that index as // the first added node. int oldIndex, newIndex; for (oldIndex = 0, newIndex = 0; newIndex < newChildren.Count; oldIndex++, newIndex++) { if (oldIndex >= oldChildren.Count || !compare(oldChildren[oldIndex], newChildren[newIndex], newNodeParent, null)) { firstAdded = newIndex; newIndex += delta; break; } } // Look for a second different child. If there is one, we'll throw away any events from // the first different child and enqueue an unknown event on the containing node. for (; newIndex < newChildren.Count; oldIndex++, newIndex++) { if (!compare(oldChildren[oldIndex], newChildren[newIndex], newNodeParent, null)) { EnqueueChangeEvent(newNodeParent, null, CodeModelEventType.Unknown, eventQueue); return; } } if (firstAdded >= 0) { for (var i = 0; i < delta; i++) { EnqueueAddEvent(newChildren[firstAdded + i], newNodeParent, eventQueue); } } } private void FindRemovedChild<TNode, TParent>( NodeComparison<TNode, TParent> compare, IReadOnlyList<TNode> oldChildren, IReadOnlyList<TNode> newChildren, TParent newNodeParent, int delta, CodeModelEventQueue eventQueue) where TNode : SyntaxNode where TParent : SyntaxNode { Debug.Assert(oldChildren.Count - delta == newChildren.Count); // The strategy is to assume that all of the removed children are contiguous. // If that turns out not to be the case, an unknown change event is raised // for the containing node. var firstRemoved = -1; // Look for the first different child. If there is one, track that index as // the first added node. int oldIndex, newIndex; for (oldIndex = 0, newIndex = 0; oldIndex < oldChildren.Count; oldIndex++, newIndex++) { if (newIndex >= newChildren.Count || !compare(oldChildren[oldIndex], newChildren[newIndex], newNodeParent, null)) { firstRemoved = oldIndex; oldIndex += delta; break; } } // Look for a second different child. If there is one, we'll throw away any events from // the first different child and enqueue an unknown event on the containing node. for (; oldIndex < oldChildren.Count; oldIndex++, newIndex++) { if (!compare(oldChildren[oldIndex], newChildren[newIndex], newNodeParent, null)) { EnqueueChangeEvent(newNodeParent, null, CodeModelEventType.Unknown, eventQueue); return; } } if (firstRemoved >= 0) { for (var i = 0; i < delta; i++) { EnqueueRemoveEvent(oldChildren[firstRemoved + i], newNodeParent, eventQueue); } } } } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Analyzers/CSharp/Analyzers/UseInferredMemberName/CSharpUseInferredMemberNameDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Simplification; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UseInferredMemberName; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UseInferredMemberName { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpUseInferredMemberNameDiagnosticAnalyzer : AbstractUseInferredMemberNameDiagnosticAnalyzer { protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.NameColon, SyntaxKind.NameEquals); protected override void LanguageSpecificAnalyzeSyntax(SyntaxNodeAnalysisContext context, SyntaxTree syntaxTree, AnalyzerOptions options, CancellationToken cancellationToken) { switch (context.Node.Kind()) { case SyntaxKind.NameColon: ReportDiagnosticsIfNeeded((NameColonSyntax)context.Node, context, options, syntaxTree, cancellationToken); break; case SyntaxKind.NameEquals: ReportDiagnosticsIfNeeded((NameEqualsSyntax)context.Node, context, options, syntaxTree, cancellationToken); break; } } private void ReportDiagnosticsIfNeeded(NameColonSyntax nameColon, SyntaxNodeAnalysisContext context, AnalyzerOptions options, SyntaxTree syntaxTree, CancellationToken cancellationToken) { if (!nameColon.Parent.IsKind(SyntaxKind.Argument, out ArgumentSyntax? argument)) { return; } var parseOptions = (CSharpParseOptions)syntaxTree.Options; var preference = options.GetOption( CodeStyleOptions2.PreferInferredTupleNames, context.Compilation.Language, syntaxTree, cancellationToken); if (!preference.Value || !CSharpInferredMemberNameSimplifier.CanSimplifyTupleElementName(argument, parseOptions)) { return; } // Create a normal diagnostic var fadeSpan = TextSpan.FromBounds(nameColon.Name.SpanStart, nameColon.ColonToken.Span.End); context.ReportDiagnostic( DiagnosticHelper.CreateWithLocationTags( Descriptor, nameColon.GetLocation(), preference.Notification.Severity, additionalLocations: ImmutableArray<Location>.Empty, additionalUnnecessaryLocations: ImmutableArray.Create(syntaxTree.GetLocation(fadeSpan)))); } private void ReportDiagnosticsIfNeeded(NameEqualsSyntax nameEquals, SyntaxNodeAnalysisContext context, AnalyzerOptions options, SyntaxTree syntaxTree, CancellationToken cancellationToken) { if (!nameEquals.Parent.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator, out AnonymousObjectMemberDeclaratorSyntax? anonCtor)) { return; } var preference = options.GetOption( CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames, context.Compilation.Language, syntaxTree, cancellationToken); if (!preference.Value || !CSharpInferredMemberNameSimplifier.CanSimplifyAnonymousTypeMemberName(anonCtor)) { return; } // Create a normal diagnostic var fadeSpan = TextSpan.FromBounds(nameEquals.Name.SpanStart, nameEquals.EqualsToken.Span.End); context.ReportDiagnostic( DiagnosticHelper.CreateWithLocationTags( Descriptor, nameEquals.GetLocation(), preference.Notification.Severity, additionalLocations: ImmutableArray<Location>.Empty, additionalUnnecessaryLocations: ImmutableArray.Create(syntaxTree.GetLocation(fadeSpan)))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Simplification; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UseInferredMemberName; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UseInferredMemberName { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpUseInferredMemberNameDiagnosticAnalyzer : AbstractUseInferredMemberNameDiagnosticAnalyzer { protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.NameColon, SyntaxKind.NameEquals); protected override void LanguageSpecificAnalyzeSyntax(SyntaxNodeAnalysisContext context, SyntaxTree syntaxTree, AnalyzerOptions options, CancellationToken cancellationToken) { switch (context.Node.Kind()) { case SyntaxKind.NameColon: ReportDiagnosticsIfNeeded((NameColonSyntax)context.Node, context, options, syntaxTree, cancellationToken); break; case SyntaxKind.NameEquals: ReportDiagnosticsIfNeeded((NameEqualsSyntax)context.Node, context, options, syntaxTree, cancellationToken); break; } } private void ReportDiagnosticsIfNeeded(NameColonSyntax nameColon, SyntaxNodeAnalysisContext context, AnalyzerOptions options, SyntaxTree syntaxTree, CancellationToken cancellationToken) { if (!nameColon.Parent.IsKind(SyntaxKind.Argument, out ArgumentSyntax? argument)) { return; } var parseOptions = (CSharpParseOptions)syntaxTree.Options; var preference = options.GetOption( CodeStyleOptions2.PreferInferredTupleNames, context.Compilation.Language, syntaxTree, cancellationToken); if (!preference.Value || !CSharpInferredMemberNameSimplifier.CanSimplifyTupleElementName(argument, parseOptions)) { return; } // Create a normal diagnostic var fadeSpan = TextSpan.FromBounds(nameColon.Name.SpanStart, nameColon.ColonToken.Span.End); context.ReportDiagnostic( DiagnosticHelper.CreateWithLocationTags( Descriptor, nameColon.GetLocation(), preference.Notification.Severity, additionalLocations: ImmutableArray<Location>.Empty, additionalUnnecessaryLocations: ImmutableArray.Create(syntaxTree.GetLocation(fadeSpan)))); } private void ReportDiagnosticsIfNeeded(NameEqualsSyntax nameEquals, SyntaxNodeAnalysisContext context, AnalyzerOptions options, SyntaxTree syntaxTree, CancellationToken cancellationToken) { if (!nameEquals.Parent.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator, out AnonymousObjectMemberDeclaratorSyntax? anonCtor)) { return; } var preference = options.GetOption( CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames, context.Compilation.Language, syntaxTree, cancellationToken); if (!preference.Value || !CSharpInferredMemberNameSimplifier.CanSimplifyAnonymousTypeMemberName(anonCtor)) { return; } // Create a normal diagnostic var fadeSpan = TextSpan.FromBounds(nameEquals.Name.SpanStart, nameEquals.EqualsToken.Span.End); context.ReportDiagnostic( DiagnosticHelper.CreateWithLocationTags( Descriptor, nameEquals.GetLocation(), preference.Notification.Severity, additionalLocations: ImmutableArray<Location>.Empty, additionalUnnecessaryLocations: ImmutableArray.Create(syntaxTree.GetLocation(fadeSpan)))); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Workspaces/CSharpTest/CodeGeneration/SymbolEditorTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Editing { [UseExportProvider] public class SymbolEditorTests { private SyntaxGenerator _g; private SyntaxGenerator Generator => _g ?? (_g = SyntaxGenerator.GetGenerator(new AdhocWorkspace(), LanguageNames.CSharp)); private static Solution GetSolution(params string[] sources) { var ws = new AdhocWorkspace(); var pid = ProjectId.CreateNewId(); var docs = sources.Select((s, i) => DocumentInfo.Create( DocumentId.CreateNewId(pid), name: "code" + i, loader: TextLoader.From(TextAndVersion.Create(SourceText.From(s), VersionStamp.Default)))).ToList(); var proj = ProjectInfo.Create(pid, VersionStamp.Default, "test", "test.dll", LanguageNames.CSharp, documents: docs, metadataReferences: new[] { TestMetadata.Net451.mscorlib }); return ws.AddProject(proj).Solution; } private static async Task<IEnumerable<ISymbol>> GetSymbolsAsync(Solution solution, string name) { var compilation = await solution.Projects.First().GetCompilationAsync(); return compilation.GlobalNamespace.GetMembers(name); } private static async Task<string> GetActualAsync(Document document) { document = await Simplifier.ReduceAsync(document); document = await Formatter.FormatAsync(document, Formatter.Annotation); document = await Formatter.FormatAsync(document, SyntaxAnnotation.ElasticAnnotation); return (await document.GetSyntaxRootAsync()).ToFullString(); } [Fact] public async Task TestEditOneDeclaration() { var code = @"class C { }"; var expected = @"class C { void m() { } }"; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbol, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m"))); Assert.Equal(1, newSymbol.GetMembers("m").Length); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestSequentialEdits() { var code = @"class C { }"; var expected = @"class C { void m() { } void m2() { } }"; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbol, (e, d) => e.AddMember(d, Generator.MethodDeclaration("m"))); Assert.Equal(1, newSymbol.GetMembers("m").Length); Assert.Equal(0, newSymbol.GetMembers("m2").Length); newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbol, (e, d) => e.AddMember(d, Generator.MethodDeclaration("m2"))); Assert.Equal(1, newSymbol.GetMembers("m").Length); Assert.Equal(1, newSymbol.GetMembers("m2").Length); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestSequentialEdit_NewSymbols() { var code = @"class C { }"; var expected = @"class C { void m() { } void m2() { } }"; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbol, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m"))); Assert.Equal(1, newSymbol.GetMembers("m").Length); Assert.Equal(0, newSymbol.GetMembers("m2").Length); newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(newSymbol, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m2"))); Assert.Equal(1, newSymbol.GetMembers("m").Length); Assert.Equal(1, newSymbol.GetMembers("m2").Length); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestSequentialEdits_SeparateSymbols() { var code = @"class A { } class B { }"; var expected = @"class A { void ma() { } } class B { void mb() { } }"; var solution = GetSolution(code); var comp = await solution.Projects.First().GetCompilationAsync(); var symbolA = comp.GlobalNamespace.GetMembers("A").First(); var symbolB = comp.GlobalNamespace.GetMembers("B").First(); var editor = SymbolEditor.Create(solution); var newSymbolA = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbolA, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("ma"))); Assert.Equal(1, newSymbolA.GetMembers("ma").Length); var newSymbolB = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbolB, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("mb"))); Assert.Equal(1, newSymbolB.GetMembers("mb").Length); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestSequentialEdits_SeparateSymbolsAndFiles() { var code1 = @"class A { }"; var code2 = @"class B { }"; var expected1 = @"class A { void ma() { } }"; var expected2 = @"class B { void mb() { } }"; var solution = GetSolution(code1, code2); var comp = await solution.Projects.First().GetCompilationAsync(); var symbolA = comp.GlobalNamespace.GetMembers("A").First(); var symbolB = comp.GlobalNamespace.GetMembers("B").First(); var editor = SymbolEditor.Create(solution); var newSymbolA = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbolA, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("ma"))); Assert.Equal(1, newSymbolA.GetMembers("ma").Length); var newSymbolB = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbolB, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("mb"))); Assert.Equal(1, newSymbolB.GetMembers("mb").Length); var docs = editor.GetChangedDocuments().ToList(); var actual1 = await GetActualAsync(docs[0]); var actual2 = await GetActualAsync(docs[1]); Assert.Equal(expected1, actual1); Assert.Equal(expected2, actual2); } [Fact] public async Task TestEditAllDeclarations_SameFile() { var code = @"public partial class C { } public partial class C { }"; var expected = @"internal partial class C { } internal partial class C { }"; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditAllDeclarationsAsync(symbol, (e, d) => e.SetAccessibility(d, Accessibility.Internal)); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestEditAllDeclarations_MultipleFiles() { var code1 = @"class C { }"; var code2 = @"class C { void M() {} }"; var expected1 = @"public class C { }"; var expected2 = @"public class C { void M() {} }"; var solution = GetSolution(code1, code2); var comp = await solution.Projects.First().GetCompilationAsync(); var symbol = comp.GlobalNamespace.GetMembers("C").First(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditAllDeclarationsAsync(symbol, (e, d) => e.SetAccessibility(d, Accessibility.Public)); var docs = editor.GetChangedDocuments().ToList(); var actual1 = await GetActualAsync(docs[0]); var actual2 = await GetActualAsync(docs[1]); Assert.Equal(expected1, actual1); Assert.Equal(expected2, actual2); } [Fact] public async Task TestEditDeclarationWithLocation_Last() { var code = @"partial class C { } partial class C { }"; var expected = @"partial class C { } partial class C { void m() { } }"; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var location = symbol.Locations.Last(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbol, location, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m"))); Assert.Equal(1, newSymbol.GetMembers("m").Length); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestEditDeclarationWithLocation_First() { var code = @"partial class C { } partial class C { }"; var expected = @"partial class C { void m() { } } partial class C { }"; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var location = symbol.Locations.First(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbol, location, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m"))); Assert.Equal(1, newSymbol.GetMembers("m").Length); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestEditDeclarationWithLocation_SequentialEdits_SameLocation() { var code = @"partial class C { } partial class C { }"; var expected = @"partial class C { } partial class C { void m() { } void m2() { } }"; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var location = symbol.Locations.Last(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbol, location, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m"))); Assert.Equal(1, newSymbol.GetMembers("m").Length); // reuse location from original symbol/solution var newSymbol2 = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(newSymbol, location, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m2"))); Assert.Equal(1, newSymbol2.GetMembers("m").Length); Assert.Equal(1, newSymbol2.GetMembers("m2").Length); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestEditDeclarationWithLocation_SequentialEdits_NewLocation() { var code = @"partial class C { } partial class C { }"; var expected = @"partial class C { } partial class C { void m() { } void m2() { } }"; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var location = symbol.Locations.Last(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbol, location, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m"))); Assert.Equal(1, newSymbol.GetMembers("m").Length); // use location from new symbol var newLocation = newSymbol.Locations.Last(); var newSymbol2 = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(newSymbol, newLocation, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m2"))); Assert.Equal(1, newSymbol2.GetMembers("m").Length); Assert.Equal(1, newSymbol2.GetMembers("m2").Length); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestEditDeclarationWithMember() { var code = @"partial class C { } partial class C { void m() { } }"; var expected = @"partial class C { } partial class C { void m() { } void m2() { } }"; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); var member = symbol.GetMembers("m").First(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbol, member, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m2"))); Assert.Equal(1, newSymbol.GetMembers("m").Length); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestChangeLogicalIdentityReturnsCorrectSymbol_OneDeclaration() { // proves that APIs return the correct new symbol even after a change that changes the symbol's logical identity. var code = @"class C { }"; var expected = @"class X { }"; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbol, (e, d) => e.SetName(d, "X")); Assert.Equal("X", newSymbol.Name); // original symbols cannot be rebound after identity change. var reboundSymbol = await editor.GetCurrentSymbolAsync(symbol); Assert.Null(reboundSymbol); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestChangeLogicalIdentityReturnsCorrectSymbol_AllDeclarations() { // proves that APIs return the correct new symbol even after a change that changes the symbol's logical identity. var code = @"partial class C { } partial class C { }"; var expected = @"partial class X { } partial class X { }"; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditAllDeclarationsAsync(symbol, (e, d) => e.SetName(d, "X")); Assert.Equal("X", newSymbol.Name); // original symbols cannot be rebound after identity change. var reboundSymbol = await editor.GetCurrentSymbolAsync(symbol); Assert.Null(reboundSymbol); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestRemovedDeclarationReturnsNull() { var code = @"class C { }"; var expected = @""; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbol, (e, d) => e.RemoveNode(d)); Assert.Null(newSymbol); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestRemovedOneOfManyDeclarationsReturnsChangedSymbol() { var code = @"partial class C { } partial class C { }"; var expected = @" partial class C { }"; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbol, (e, d) => e.RemoveNode(d)); Assert.NotNull(newSymbol); Assert.Equal("C", newSymbol.Name); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestRemoveAllOfManyDeclarationsReturnsNull() { var code = @"partial class C { } partial class C { }"; var expected = @" "; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditAllDeclarationsAsync(symbol, (e, d) => e.RemoveNode(d)); Assert.Null(newSymbol); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestRemoveFieldFromMultiFieldDeclaration() { var code = @"class C { public int X, Y; }"; var expected = @"class C { public int Y; }"; var expected2 = @"class C { }"; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); var symbolX = symbol.GetMembers("X").First(); var symbolY = symbol.GetMembers("Y").First(); var editor = SymbolEditor.Create(solution); // remove X -- should remove only part of the field declaration. var newSymbolX = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbolX, (e, d) => e.RemoveNode(d)); Assert.Null(newSymbolX); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); // now remove Y -- should remove entire remaining field declaration var newSymbolY = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbolY, (e, d) => e.RemoveNode(d)); Assert.Null(newSymbolY); actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected2, actual); } [Fact] public async Task TestSetBaseType_ExistingBase() { var code = @"class C : B { } class A { } class B { }"; var expected = @"class C : A { } class A { } class B { }"; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); // set base to A var newSymbolC = await editor.SetBaseTypeAsync(symbol, g => g.IdentifierName("A")); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestSetBaseType_ExistingInterface() { var code = @"class C : I { } class A { } interface I { }"; var expected = @"class C : A, I { } class A { } interface I { }"; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); // set base to A var newSymbolC = await editor.SetBaseTypeAsync(symbol, g => g.IdentifierName("A")); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestSetBaseType_NoBaseOrInterface() { var code = @"class C { } class A { }"; var expected = @"class C : A { } class A { }"; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); // set base to A var newSymbolC = await editor.SetBaseTypeAsync(symbol, g => g.IdentifierName("A")); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestSetBaseType_UnknownBase() { var code = @"class C : X { } class A { }"; var expected = @"class C : A { } class A { }"; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); // set base to A var newSymbolC = editor.SetBaseTypeAsync(symbol, g => g.IdentifierName("A")); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestSetBaseType_Null_ExistingBase() { var code = @"class C : A { } class A { }"; var expected = @"class C { } class A { }"; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); // set base to null var newSymbolC = await editor.SetBaseTypeAsync(symbol, g => null); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestSetBaseType_Null_ExistingBaseAndInterface() { var code = @"class C : A, I { } class A { } interface I { }"; var expected = @"class C : I { } class A { } interface I { }"; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); // set base to null var newSymbolC = await editor.SetBaseTypeAsync(symbol, g => null); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestSetBaseType_Null_ExistingInterface() { var code = @"class C : I { } interface I { }"; var expected = @"class C : I { } interface I { }"; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); // set base to null var newSymbolC = await editor.SetBaseTypeAsync(symbol, g => null); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestSetBaseType_Null_UnknownBase() { var code = @"class C : X { }"; var expected = @"class C { }"; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); // set base to null var newSymbolC = await editor.SetBaseTypeAsync(symbol, g => null); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] [WorkItem(2650, "https://github.com/dotnet/roslyn/issues/2650")] public async Task TestEditExplicitInterfaceIndexer() { var code = @"public interface I { int this[int item] { get; } } public class C : I { int I.this[int item] { get { return item; } } }"; var solution = GetSolution(code); var typeC = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); var property = typeC.GetMembers().First(m => m.Kind == SymbolKind.Property); var editor = SymbolEditor.Create(solution); var newProperty = editor.EditOneDeclarationAsync(property, (e, d) => { // nothing }); var typeI = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "I")).First(); var iproperty = typeI.GetMembers().First(m => m.Kind == SymbolKind.Property); var newIProperty = editor.EditOneDeclarationAsync(iproperty, (e, d) => { // nothing; }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Editing { [UseExportProvider] public class SymbolEditorTests { private SyntaxGenerator _g; private SyntaxGenerator Generator => _g ?? (_g = SyntaxGenerator.GetGenerator(new AdhocWorkspace(), LanguageNames.CSharp)); private static Solution GetSolution(params string[] sources) { var ws = new AdhocWorkspace(); var pid = ProjectId.CreateNewId(); var docs = sources.Select((s, i) => DocumentInfo.Create( DocumentId.CreateNewId(pid), name: "code" + i, loader: TextLoader.From(TextAndVersion.Create(SourceText.From(s), VersionStamp.Default)))).ToList(); var proj = ProjectInfo.Create(pid, VersionStamp.Default, "test", "test.dll", LanguageNames.CSharp, documents: docs, metadataReferences: new[] { TestMetadata.Net451.mscorlib }); return ws.AddProject(proj).Solution; } private static async Task<IEnumerable<ISymbol>> GetSymbolsAsync(Solution solution, string name) { var compilation = await solution.Projects.First().GetCompilationAsync(); return compilation.GlobalNamespace.GetMembers(name); } private static async Task<string> GetActualAsync(Document document) { document = await Simplifier.ReduceAsync(document); document = await Formatter.FormatAsync(document, Formatter.Annotation); document = await Formatter.FormatAsync(document, SyntaxAnnotation.ElasticAnnotation); return (await document.GetSyntaxRootAsync()).ToFullString(); } [Fact] public async Task TestEditOneDeclaration() { var code = @"class C { }"; var expected = @"class C { void m() { } }"; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbol, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m"))); Assert.Equal(1, newSymbol.GetMembers("m").Length); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestSequentialEdits() { var code = @"class C { }"; var expected = @"class C { void m() { } void m2() { } }"; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbol, (e, d) => e.AddMember(d, Generator.MethodDeclaration("m"))); Assert.Equal(1, newSymbol.GetMembers("m").Length); Assert.Equal(0, newSymbol.GetMembers("m2").Length); newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbol, (e, d) => e.AddMember(d, Generator.MethodDeclaration("m2"))); Assert.Equal(1, newSymbol.GetMembers("m").Length); Assert.Equal(1, newSymbol.GetMembers("m2").Length); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestSequentialEdit_NewSymbols() { var code = @"class C { }"; var expected = @"class C { void m() { } void m2() { } }"; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbol, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m"))); Assert.Equal(1, newSymbol.GetMembers("m").Length); Assert.Equal(0, newSymbol.GetMembers("m2").Length); newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(newSymbol, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m2"))); Assert.Equal(1, newSymbol.GetMembers("m").Length); Assert.Equal(1, newSymbol.GetMembers("m2").Length); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestSequentialEdits_SeparateSymbols() { var code = @"class A { } class B { }"; var expected = @"class A { void ma() { } } class B { void mb() { } }"; var solution = GetSolution(code); var comp = await solution.Projects.First().GetCompilationAsync(); var symbolA = comp.GlobalNamespace.GetMembers("A").First(); var symbolB = comp.GlobalNamespace.GetMembers("B").First(); var editor = SymbolEditor.Create(solution); var newSymbolA = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbolA, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("ma"))); Assert.Equal(1, newSymbolA.GetMembers("ma").Length); var newSymbolB = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbolB, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("mb"))); Assert.Equal(1, newSymbolB.GetMembers("mb").Length); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestSequentialEdits_SeparateSymbolsAndFiles() { var code1 = @"class A { }"; var code2 = @"class B { }"; var expected1 = @"class A { void ma() { } }"; var expected2 = @"class B { void mb() { } }"; var solution = GetSolution(code1, code2); var comp = await solution.Projects.First().GetCompilationAsync(); var symbolA = comp.GlobalNamespace.GetMembers("A").First(); var symbolB = comp.GlobalNamespace.GetMembers("B").First(); var editor = SymbolEditor.Create(solution); var newSymbolA = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbolA, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("ma"))); Assert.Equal(1, newSymbolA.GetMembers("ma").Length); var newSymbolB = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbolB, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("mb"))); Assert.Equal(1, newSymbolB.GetMembers("mb").Length); var docs = editor.GetChangedDocuments().ToList(); var actual1 = await GetActualAsync(docs[0]); var actual2 = await GetActualAsync(docs[1]); Assert.Equal(expected1, actual1); Assert.Equal(expected2, actual2); } [Fact] public async Task TestEditAllDeclarations_SameFile() { var code = @"public partial class C { } public partial class C { }"; var expected = @"internal partial class C { } internal partial class C { }"; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditAllDeclarationsAsync(symbol, (e, d) => e.SetAccessibility(d, Accessibility.Internal)); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestEditAllDeclarations_MultipleFiles() { var code1 = @"class C { }"; var code2 = @"class C { void M() {} }"; var expected1 = @"public class C { }"; var expected2 = @"public class C { void M() {} }"; var solution = GetSolution(code1, code2); var comp = await solution.Projects.First().GetCompilationAsync(); var symbol = comp.GlobalNamespace.GetMembers("C").First(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditAllDeclarationsAsync(symbol, (e, d) => e.SetAccessibility(d, Accessibility.Public)); var docs = editor.GetChangedDocuments().ToList(); var actual1 = await GetActualAsync(docs[0]); var actual2 = await GetActualAsync(docs[1]); Assert.Equal(expected1, actual1); Assert.Equal(expected2, actual2); } [Fact] public async Task TestEditDeclarationWithLocation_Last() { var code = @"partial class C { } partial class C { }"; var expected = @"partial class C { } partial class C { void m() { } }"; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var location = symbol.Locations.Last(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbol, location, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m"))); Assert.Equal(1, newSymbol.GetMembers("m").Length); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestEditDeclarationWithLocation_First() { var code = @"partial class C { } partial class C { }"; var expected = @"partial class C { void m() { } } partial class C { }"; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var location = symbol.Locations.First(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbol, location, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m"))); Assert.Equal(1, newSymbol.GetMembers("m").Length); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestEditDeclarationWithLocation_SequentialEdits_SameLocation() { var code = @"partial class C { } partial class C { }"; var expected = @"partial class C { } partial class C { void m() { } void m2() { } }"; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var location = symbol.Locations.Last(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbol, location, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m"))); Assert.Equal(1, newSymbol.GetMembers("m").Length); // reuse location from original symbol/solution var newSymbol2 = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(newSymbol, location, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m2"))); Assert.Equal(1, newSymbol2.GetMembers("m").Length); Assert.Equal(1, newSymbol2.GetMembers("m2").Length); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestEditDeclarationWithLocation_SequentialEdits_NewLocation() { var code = @"partial class C { } partial class C { }"; var expected = @"partial class C { } partial class C { void m() { } void m2() { } }"; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var location = symbol.Locations.Last(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbol, location, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m"))); Assert.Equal(1, newSymbol.GetMembers("m").Length); // use location from new symbol var newLocation = newSymbol.Locations.Last(); var newSymbol2 = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(newSymbol, newLocation, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m2"))); Assert.Equal(1, newSymbol2.GetMembers("m").Length); Assert.Equal(1, newSymbol2.GetMembers("m2").Length); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestEditDeclarationWithMember() { var code = @"partial class C { } partial class C { void m() { } }"; var expected = @"partial class C { } partial class C { void m() { } void m2() { } }"; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); var member = symbol.GetMembers("m").First(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbol, member, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m2"))); Assert.Equal(1, newSymbol.GetMembers("m").Length); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestChangeLogicalIdentityReturnsCorrectSymbol_OneDeclaration() { // proves that APIs return the correct new symbol even after a change that changes the symbol's logical identity. var code = @"class C { }"; var expected = @"class X { }"; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbol, (e, d) => e.SetName(d, "X")); Assert.Equal("X", newSymbol.Name); // original symbols cannot be rebound after identity change. var reboundSymbol = await editor.GetCurrentSymbolAsync(symbol); Assert.Null(reboundSymbol); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestChangeLogicalIdentityReturnsCorrectSymbol_AllDeclarations() { // proves that APIs return the correct new symbol even after a change that changes the symbol's logical identity. var code = @"partial class C { } partial class C { }"; var expected = @"partial class X { } partial class X { }"; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditAllDeclarationsAsync(symbol, (e, d) => e.SetName(d, "X")); Assert.Equal("X", newSymbol.Name); // original symbols cannot be rebound after identity change. var reboundSymbol = await editor.GetCurrentSymbolAsync(symbol); Assert.Null(reboundSymbol); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestRemovedDeclarationReturnsNull() { var code = @"class C { }"; var expected = @""; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbol, (e, d) => e.RemoveNode(d)); Assert.Null(newSymbol); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestRemovedOneOfManyDeclarationsReturnsChangedSymbol() { var code = @"partial class C { } partial class C { }"; var expected = @" partial class C { }"; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbol, (e, d) => e.RemoveNode(d)); Assert.NotNull(newSymbol); Assert.Equal("C", newSymbol.Name); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestRemoveAllOfManyDeclarationsReturnsNull() { var code = @"partial class C { } partial class C { }"; var expected = @" "; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); var newSymbol = (INamedTypeSymbol)await editor.EditAllDeclarationsAsync(symbol, (e, d) => e.RemoveNode(d)); Assert.Null(newSymbol); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestRemoveFieldFromMultiFieldDeclaration() { var code = @"class C { public int X, Y; }"; var expected = @"class C { public int Y; }"; var expected2 = @"class C { }"; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); var symbolX = symbol.GetMembers("X").First(); var symbolY = symbol.GetMembers("Y").First(); var editor = SymbolEditor.Create(solution); // remove X -- should remove only part of the field declaration. var newSymbolX = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbolX, (e, d) => e.RemoveNode(d)); Assert.Null(newSymbolX); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); // now remove Y -- should remove entire remaining field declaration var newSymbolY = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbolY, (e, d) => e.RemoveNode(d)); Assert.Null(newSymbolY); actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected2, actual); } [Fact] public async Task TestSetBaseType_ExistingBase() { var code = @"class C : B { } class A { } class B { }"; var expected = @"class C : A { } class A { } class B { }"; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); // set base to A var newSymbolC = await editor.SetBaseTypeAsync(symbol, g => g.IdentifierName("A")); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestSetBaseType_ExistingInterface() { var code = @"class C : I { } class A { } interface I { }"; var expected = @"class C : A, I { } class A { } interface I { }"; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); // set base to A var newSymbolC = await editor.SetBaseTypeAsync(symbol, g => g.IdentifierName("A")); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestSetBaseType_NoBaseOrInterface() { var code = @"class C { } class A { }"; var expected = @"class C : A { } class A { }"; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); // set base to A var newSymbolC = await editor.SetBaseTypeAsync(symbol, g => g.IdentifierName("A")); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestSetBaseType_UnknownBase() { var code = @"class C : X { } class A { }"; var expected = @"class C : A { } class A { }"; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); // set base to A var newSymbolC = editor.SetBaseTypeAsync(symbol, g => g.IdentifierName("A")); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestSetBaseType_Null_ExistingBase() { var code = @"class C : A { } class A { }"; var expected = @"class C { } class A { }"; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); // set base to null var newSymbolC = await editor.SetBaseTypeAsync(symbol, g => null); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestSetBaseType_Null_ExistingBaseAndInterface() { var code = @"class C : A, I { } class A { } interface I { }"; var expected = @"class C : I { } class A { } interface I { }"; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); // set base to null var newSymbolC = await editor.SetBaseTypeAsync(symbol, g => null); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestSetBaseType_Null_ExistingInterface() { var code = @"class C : I { } interface I { }"; var expected = @"class C : I { } interface I { }"; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); // set base to null var newSymbolC = await editor.SetBaseTypeAsync(symbol, g => null); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] public async Task TestSetBaseType_Null_UnknownBase() { var code = @"class C : X { }"; var expected = @"class C { }"; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); // set base to null var newSymbolC = await editor.SetBaseTypeAsync(symbol, g => null); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); Assert.Equal(expected, actual); } [Fact] [WorkItem(2650, "https://github.com/dotnet/roslyn/issues/2650")] public async Task TestEditExplicitInterfaceIndexer() { var code = @"public interface I { int this[int item] { get; } } public class C : I { int I.this[int item] { get { return item; } } }"; var solution = GetSolution(code); var typeC = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); var property = typeC.GetMembers().First(m => m.Kind == SymbolKind.Property); var editor = SymbolEditor.Create(solution); var newProperty = editor.EditOneDeclarationAsync(property, (e, d) => { // nothing }); var typeI = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "I")).First(); var iproperty = typeI.GetMembers().First(m => m.Kind == SymbolKind.Property); var newIProperty = editor.EditOneDeclarationAsync(iproperty, (e, d) => { // nothing; }); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Features/Core/Portable/GenerateConstructorFromMembers/GenerateConstructorFromMembersOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.GenerateConstructorFromMembers { internal static class GenerateConstructorFromMembersOptions { public static readonly PerLanguageOption2<bool> AddNullChecks = new( nameof(GenerateConstructorFromMembersOptions), nameof(AddNullChecks), defaultValue: false, storageLocation: new RoamingProfileStorageLocation( $"TextEditor.%LANGUAGE%.Specific.{nameof(GenerateConstructorFromMembersOptions)}.{nameof(AddNullChecks)}")); } }
// Licensed to the .NET Foundation under one or more 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.GenerateConstructorFromMembers { internal static class GenerateConstructorFromMembersOptions { public static readonly PerLanguageOption2<bool> AddNullChecks = new( nameof(GenerateConstructorFromMembersOptions), nameof(AddNullChecks), defaultValue: false, storageLocation: new RoamingProfileStorageLocation( $"TextEditor.%LANGUAGE%.Specific.{nameof(GenerateConstructorFromMembersOptions)}.{nameof(AddNullChecks)}")); } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Compilers/CSharp/Portable/Syntax/LookupPosition.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax { /// <summary> /// This class contains a variety of helper methods for determining whether a /// position is within the scope (and not just the span) of a node. In general, /// general, the scope extends from the first token up to, but not including, /// the last token. For example, the open brace of a block is within the scope /// of the block, but the close brace is not. /// </summary> internal static class LookupPosition { /// <summary> /// A position is considered to be inside a block if it is on or after /// the open brace and strictly before the close brace. /// </summary> internal static bool IsInBlock(int position, BlockSyntax? blockOpt) { return blockOpt != null && IsBeforeToken(position, blockOpt, blockOpt.CloseBraceToken); } internal static bool IsInExpressionBody( int position, ArrowExpressionClauseSyntax? expressionBodyOpt, SyntaxToken semicolonToken) { return expressionBodyOpt != null && IsBeforeToken(position, expressionBodyOpt, semicolonToken); } private static bool IsInBody(int position, BlockSyntax? blockOpt, ArrowExpressionClauseSyntax? exprOpt, SyntaxToken semiOpt) { return IsInExpressionBody(position, exprOpt, semiOpt) || IsInBlock(position, blockOpt); } /// <summary> /// A position is inside a property body only if it is inside an expression body. /// All block bodies for properties are part of the accessor declaration (a type /// of BaseMethodDeclaration), not the property declaration. /// </summary> internal static bool IsInBody(int position, PropertyDeclarationSyntax property) => IsInBody(position, blockOpt: null, property.GetExpressionBodySyntax(), property.SemicolonToken); /// <summary> /// A position is inside a property body only if it is inside an expression body. /// All block bodies for properties are part of the accessor declaration (a type /// of BaseMethodDeclaration), not the property declaration. /// </summary> internal static bool IsInBody(int position, IndexerDeclarationSyntax indexer) => IsInBody(position, blockOpt: null, indexer.GetExpressionBodySyntax(), indexer.SemicolonToken); /// <summary> /// A position is inside an accessor body if it is inside the block or expression /// body. /// </summary> internal static bool IsInBody(int position, AccessorDeclarationSyntax method) => IsInBody(position, method.Body, method.GetExpressionBodySyntax(), method.SemicolonToken); /// <summary> /// A position is inside a body if it is inside the block or expression /// body. /// /// A position is considered to be inside a block if it is on or after /// the open brace and strictly before the close brace. A position is /// considered to be inside an expression body if it is on or after /// the '=>' and strictly before the semicolon. /// </summary> internal static bool IsInBody(int position, BaseMethodDeclarationSyntax method) => IsInBody(position, method.Body, method.GetExpressionBodySyntax(), method.SemicolonToken); internal static bool IsBetweenTokens(int position, SyntaxToken firstIncluded, SyntaxToken firstExcluded) { return position >= firstIncluded.SpanStart && IsBeforeToken(position, firstExcluded); } /// <summary> /// Returns true if position is within the given node and before the first excluded token. /// </summary> private static bool IsBeforeToken(int position, CSharpSyntaxNode node, SyntaxToken firstExcluded) { return IsBeforeToken(position, firstExcluded) && position >= node.SpanStart; } private static bool IsBeforeToken(int position, SyntaxToken firstExcluded) { return firstExcluded.Kind() == SyntaxKind.None || position < firstExcluded.SpanStart; } internal static bool IsInAttributeSpecification(int position, SyntaxList<AttributeListSyntax> attributesSyntaxList) { int count = attributesSyntaxList.Count; if (count == 0) { return false; } var startToken = attributesSyntaxList[0].OpenBracketToken; var endToken = attributesSyntaxList[count - 1].CloseBracketToken; return IsBetweenTokens(position, startToken, endToken); } internal static bool IsInTypeParameterList(int position, TypeDeclarationSyntax typeDecl) { var typeParameterListOpt = typeDecl.TypeParameterList; return typeParameterListOpt != null && IsBeforeToken(position, typeParameterListOpt, typeParameterListOpt.GreaterThanToken); } internal static bool IsInParameterList(int position, BaseMethodDeclarationSyntax methodDecl) { var parameterList = methodDecl.ParameterList; return IsBeforeToken(position, parameterList, parameterList.CloseParenToken); } internal static bool IsInParameterList(int position, ParameterListSyntax parameterList) => parameterList != null && IsBeforeToken(position, parameterList, parameterList.CloseParenToken); internal static bool IsInMethodDeclaration(int position, BaseMethodDeclarationSyntax methodDecl) { Debug.Assert(methodDecl != null); var body = methodDecl.Body; if (body == null) { return IsBeforeToken(position, methodDecl, methodDecl.SemicolonToken); } return IsBeforeToken(position, methodDecl, body.CloseBraceToken) || IsInExpressionBody(position, methodDecl.GetExpressionBodySyntax(), methodDecl.SemicolonToken); } internal static bool IsInMethodDeclaration(int position, AccessorDeclarationSyntax accessorDecl) { Debug.Assert(accessorDecl != null); var body = accessorDecl.Body; SyntaxToken lastToken = body == null ? accessorDecl.SemicolonToken : body.CloseBraceToken; return IsBeforeToken(position, accessorDecl, lastToken); } internal static bool IsInDelegateDeclaration(int position, DelegateDeclarationSyntax delegateDecl) { Debug.Assert(delegateDecl != null); return IsBeforeToken(position, delegateDecl, delegateDecl.SemicolonToken); } internal static bool IsInTypeDeclaration(int position, BaseTypeDeclarationSyntax typeDecl) { Debug.Assert(typeDecl != null); return IsBeforeToken(position, typeDecl, typeDecl.CloseBraceToken); } internal static bool IsInNamespaceDeclaration(int position, NamespaceDeclarationSyntax namespaceDecl) { Debug.Assert(namespaceDecl != null); return IsBetweenTokens(position, namespaceDecl.NamespaceKeyword, namespaceDecl.CloseBraceToken); } internal static bool IsInNamespaceDeclaration(int position, FileScopedNamespaceDeclarationSyntax namespaceDecl) { Debug.Assert(namespaceDecl != null); return position >= namespaceDecl.SpanStart; } internal static bool IsInConstructorParameterScope(int position, ConstructorDeclarationSyntax constructorDecl) { Debug.Assert(constructorDecl != null); var initializerOpt = constructorDecl.Initializer; var hasBody = constructorDecl.Body != null || constructorDecl.ExpressionBody != null; if (!hasBody) { var nextToken = (SyntaxToken)SyntaxNavigator.Instance.GetNextToken(constructorDecl, predicate: null, stepInto: null); return initializerOpt == null ? position >= constructorDecl.ParameterList.CloseParenToken.Span.End && IsBeforeToken(position, nextToken) : IsBetweenTokens(position, initializerOpt.ColonToken, nextToken); } return initializerOpt == null ? IsInBody(position, constructorDecl) : IsBetweenTokens(position, initializerOpt.ColonToken, constructorDecl.SemicolonToken.Kind() == SyntaxKind.None ? constructorDecl.Body!.CloseBraceToken : constructorDecl.SemicolonToken); } internal static bool IsInMethodTypeParameterScope(int position, MethodDeclarationSyntax methodDecl) { Debug.Assert(methodDecl != null); Debug.Assert(IsInMethodDeclaration(position, methodDecl)); if (methodDecl.TypeParameterList == null) { // no type parameters => nothing can be in their scope return false; } // optimization for a common case - when position is in the ReturnType, we can see type parameters if (methodDecl.ReturnType.FullSpan.Contains(position)) { return true; } // Must be in the method, but not in an attribute on the method. if (IsInAttributeSpecification(position, methodDecl.AttributeLists)) { return false; } var explicitInterfaceSpecifier = methodDecl.ExplicitInterfaceSpecifier; var firstNameToken = explicitInterfaceSpecifier == null ? methodDecl.Identifier : explicitInterfaceSpecifier.GetFirstToken(); var typeParams = methodDecl.TypeParameterList; var firstPostNameToken = typeParams == null ? methodDecl.ParameterList.OpenParenToken : typeParams.LessThanToken; // Scope does not include method name. return !IsBetweenTokens(position, firstNameToken, firstPostNameToken); } /// <remarks> /// Used to determine whether it would be appropriate to use the binder for the statement (if any). /// Not used to determine whether the position is syntactically within the statement. /// </remarks> internal static bool IsInStatementScope(int position, StatementSyntax statement) { Debug.Assert(statement != null); if (statement.Kind() == SyntaxKind.EmptyStatement) { return false; } // CONSIDER: the check for default(SyntaxToken) could go in IsBetweenTokens, // but this is where it has special meaning. SyntaxToken firstIncludedToken = GetFirstIncludedToken(statement); return firstIncludedToken != default(SyntaxToken) && IsBetweenTokens(position, firstIncludedToken, GetFirstExcludedToken(statement)); } /// <remarks> /// Used to determine whether it would be appropriate to use the binder for the switch section (if any). /// Not used to determine whether the position is syntactically within the statement. /// </remarks> internal static bool IsInSwitchSectionScope(int position, SwitchSectionSyntax section) { Debug.Assert(section != null); return section.Span.Contains(position); } /// <remarks> /// Used to determine whether it would be appropriate to use the binder for the statement (if any). /// Not used to determine whether the position is syntactically within the statement. /// </remarks> internal static bool IsInCatchBlockScope(int position, CatchClauseSyntax catchClause) { Debug.Assert(catchClause != null); return IsBetweenTokens(position, catchClause.Block.OpenBraceToken, catchClause.Block.CloseBraceToken); } /// <remarks> /// Used to determine whether it would be appropriate to use the binder for the statement (if any). /// Not used to determine whether the position is syntactically within the statement. /// </remarks> internal static bool IsInCatchFilterScope(int position, CatchFilterClauseSyntax filterClause) { Debug.Assert(filterClause != null); return IsBetweenTokens(position, filterClause.OpenParenToken, filterClause.CloseParenToken); } private static SyntaxToken GetFirstIncludedToken(StatementSyntax statement) { Debug.Assert(statement != null); switch (statement.Kind()) { case SyntaxKind.Block: return ((BlockSyntax)statement).OpenBraceToken; case SyntaxKind.BreakStatement: return ((BreakStatementSyntax)statement).BreakKeyword; case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return ((CheckedStatementSyntax)statement).Keyword; case SyntaxKind.ContinueStatement: return ((ContinueStatementSyntax)statement).ContinueKeyword; case SyntaxKind.ExpressionStatement: case SyntaxKind.LocalDeclarationStatement: return statement.GetFirstToken(); case SyntaxKind.DoStatement: return ((DoStatementSyntax)statement).DoKeyword; case SyntaxKind.EmptyStatement: return default(SyntaxToken); //The caller will have to check for this. case SyntaxKind.FixedStatement: return ((FixedStatementSyntax)statement).FixedKeyword; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: return ((CommonForEachStatementSyntax)statement).OpenParenToken.GetNextToken(); case SyntaxKind.ForStatement: return ((ForStatementSyntax)statement).OpenParenToken.GetNextToken(); case SyntaxKind.GotoDefaultStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoStatement: return ((GotoStatementSyntax)statement).GotoKeyword; case SyntaxKind.IfStatement: return ((IfStatementSyntax)statement).IfKeyword; case SyntaxKind.LabeledStatement: return ((LabeledStatementSyntax)statement).Identifier; case SyntaxKind.LockStatement: return ((LockStatementSyntax)statement).LockKeyword; case SyntaxKind.ReturnStatement: return ((ReturnStatementSyntax)statement).ReturnKeyword; case SyntaxKind.SwitchStatement: return ((SwitchStatementSyntax)statement).Expression.GetFirstToken(); case SyntaxKind.ThrowStatement: return ((ThrowStatementSyntax)statement).ThrowKeyword; case SyntaxKind.TryStatement: return ((TryStatementSyntax)statement).TryKeyword; case SyntaxKind.UnsafeStatement: return ((UnsafeStatementSyntax)statement).UnsafeKeyword; case SyntaxKind.UsingStatement: return ((UsingStatementSyntax)statement).UsingKeyword; case SyntaxKind.WhileStatement: return ((WhileStatementSyntax)statement).WhileKeyword; case SyntaxKind.YieldReturnStatement: case SyntaxKind.YieldBreakStatement: return ((YieldStatementSyntax)statement).YieldKeyword; case SyntaxKind.LocalFunctionStatement: return statement.GetFirstToken(); default: throw ExceptionUtilities.UnexpectedValue(statement.Kind()); } } internal static SyntaxToken GetFirstExcludedToken(StatementSyntax statement) { Debug.Assert(statement != null); switch (statement.Kind()) { case SyntaxKind.Block: return ((BlockSyntax)statement).CloseBraceToken; case SyntaxKind.BreakStatement: return ((BreakStatementSyntax)statement).SemicolonToken; case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return ((CheckedStatementSyntax)statement).Block.CloseBraceToken; case SyntaxKind.ContinueStatement: return ((ContinueStatementSyntax)statement).SemicolonToken; case SyntaxKind.LocalDeclarationStatement: return ((LocalDeclarationStatementSyntax)statement).SemicolonToken; case SyntaxKind.DoStatement: return ((DoStatementSyntax)statement).SemicolonToken; case SyntaxKind.EmptyStatement: return ((EmptyStatementSyntax)statement).SemicolonToken; case SyntaxKind.ExpressionStatement: return ((ExpressionStatementSyntax)statement).SemicolonToken; case SyntaxKind.FixedStatement: return GetFirstExcludedToken(((FixedStatementSyntax)statement).Statement); case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: return GetFirstExcludedToken(((CommonForEachStatementSyntax)statement).Statement); case SyntaxKind.ForStatement: return GetFirstExcludedToken(((ForStatementSyntax)statement).Statement); case SyntaxKind.GotoDefaultStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoStatement: return ((GotoStatementSyntax)statement).SemicolonToken; case SyntaxKind.IfStatement: IfStatementSyntax ifStmt = (IfStatementSyntax)statement; ElseClauseSyntax? elseOpt = ifStmt.Else; return GetFirstExcludedToken(elseOpt == null ? ifStmt.Statement : elseOpt.Statement); case SyntaxKind.LabeledStatement: return GetFirstExcludedToken(((LabeledStatementSyntax)statement).Statement); case SyntaxKind.LockStatement: return GetFirstExcludedToken(((LockStatementSyntax)statement).Statement); case SyntaxKind.ReturnStatement: return ((ReturnStatementSyntax)statement).SemicolonToken; case SyntaxKind.SwitchStatement: return ((SwitchStatementSyntax)statement).CloseBraceToken; case SyntaxKind.ThrowStatement: return ((ThrowStatementSyntax)statement).SemicolonToken; case SyntaxKind.TryStatement: TryStatementSyntax tryStmt = (TryStatementSyntax)statement; FinallyClauseSyntax? finallyClause = tryStmt.Finally; if (finallyClause != null) { return finallyClause.Block.CloseBraceToken; } CatchClauseSyntax? lastCatch = tryStmt.Catches.LastOrDefault(); if (lastCatch != null) { return lastCatch.Block.CloseBraceToken; } return tryStmt.Block.CloseBraceToken; case SyntaxKind.UnsafeStatement: return ((UnsafeStatementSyntax)statement).Block.CloseBraceToken; case SyntaxKind.UsingStatement: return GetFirstExcludedToken(((UsingStatementSyntax)statement).Statement); case SyntaxKind.WhileStatement: return GetFirstExcludedToken(((WhileStatementSyntax)statement).Statement); case SyntaxKind.YieldReturnStatement: case SyntaxKind.YieldBreakStatement: return ((YieldStatementSyntax)statement).SemicolonToken; case SyntaxKind.LocalFunctionStatement: LocalFunctionStatementSyntax localFunctionStmt = (LocalFunctionStatementSyntax)statement; if (localFunctionStmt.Body != null) return GetFirstExcludedToken(localFunctionStmt.Body); if (localFunctionStmt.SemicolonToken != default(SyntaxToken)) return localFunctionStmt.SemicolonToken; return localFunctionStmt.ParameterList.GetLastToken(); default: throw ExceptionUtilities.UnexpectedValue(statement.Kind()); } } internal static bool IsInAnonymousFunctionOrQuery(int position, SyntaxNode lambdaExpressionOrQueryNode) { Debug.Assert(lambdaExpressionOrQueryNode.IsAnonymousFunction() || lambdaExpressionOrQueryNode.IsQuery()); SyntaxToken firstIncluded; CSharpSyntaxNode body; switch (lambdaExpressionOrQueryNode.Kind()) { case SyntaxKind.SimpleLambdaExpression: SimpleLambdaExpressionSyntax simple = (SimpleLambdaExpressionSyntax)lambdaExpressionOrQueryNode; firstIncluded = simple.ArrowToken; body = simple.Body; break; case SyntaxKind.ParenthesizedLambdaExpression: ParenthesizedLambdaExpressionSyntax parenthesized = (ParenthesizedLambdaExpressionSyntax)lambdaExpressionOrQueryNode; firstIncluded = parenthesized.ArrowToken; body = parenthesized.Body; break; case SyntaxKind.AnonymousMethodExpression: AnonymousMethodExpressionSyntax anon = (AnonymousMethodExpressionSyntax)lambdaExpressionOrQueryNode; body = anon.Block; firstIncluded = body.GetFirstToken(includeZeroWidth: true); break; default: // OK, so we have some kind of query clause. They all start with a keyword token, so we'll skip that. firstIncluded = lambdaExpressionOrQueryNode.GetFirstToken().GetNextToken(); return IsBetweenTokens(position, firstIncluded, lambdaExpressionOrQueryNode.GetLastToken().GetNextToken()); } var bodyStatement = body as StatementSyntax; var firstExcluded = bodyStatement != null ? GetFirstExcludedToken(bodyStatement) : (SyntaxToken)SyntaxNavigator.Instance.GetNextToken(body, predicate: null, stepInto: null); return IsBetweenTokens(position, firstIncluded, firstExcluded); } internal static bool IsInXmlAttributeValue(int position, XmlAttributeSyntax attribute) { return IsBetweenTokens(position, attribute.StartQuoteToken, attribute.EndQuoteToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax { /// <summary> /// This class contains a variety of helper methods for determining whether a /// position is within the scope (and not just the span) of a node. In general, /// general, the scope extends from the first token up to, but not including, /// the last token. For example, the open brace of a block is within the scope /// of the block, but the close brace is not. /// </summary> internal static class LookupPosition { /// <summary> /// A position is considered to be inside a block if it is on or after /// the open brace and strictly before the close brace. /// </summary> internal static bool IsInBlock(int position, BlockSyntax? blockOpt) { return blockOpt != null && IsBeforeToken(position, blockOpt, blockOpt.CloseBraceToken); } internal static bool IsInExpressionBody( int position, ArrowExpressionClauseSyntax? expressionBodyOpt, SyntaxToken semicolonToken) { return expressionBodyOpt != null && IsBeforeToken(position, expressionBodyOpt, semicolonToken); } private static bool IsInBody(int position, BlockSyntax? blockOpt, ArrowExpressionClauseSyntax? exprOpt, SyntaxToken semiOpt) { return IsInExpressionBody(position, exprOpt, semiOpt) || IsInBlock(position, blockOpt); } /// <summary> /// A position is inside a property body only if it is inside an expression body. /// All block bodies for properties are part of the accessor declaration (a type /// of BaseMethodDeclaration), not the property declaration. /// </summary> internal static bool IsInBody(int position, PropertyDeclarationSyntax property) => IsInBody(position, blockOpt: null, property.GetExpressionBodySyntax(), property.SemicolonToken); /// <summary> /// A position is inside a property body only if it is inside an expression body. /// All block bodies for properties are part of the accessor declaration (a type /// of BaseMethodDeclaration), not the property declaration. /// </summary> internal static bool IsInBody(int position, IndexerDeclarationSyntax indexer) => IsInBody(position, blockOpt: null, indexer.GetExpressionBodySyntax(), indexer.SemicolonToken); /// <summary> /// A position is inside an accessor body if it is inside the block or expression /// body. /// </summary> internal static bool IsInBody(int position, AccessorDeclarationSyntax method) => IsInBody(position, method.Body, method.GetExpressionBodySyntax(), method.SemicolonToken); /// <summary> /// A position is inside a body if it is inside the block or expression /// body. /// /// A position is considered to be inside a block if it is on or after /// the open brace and strictly before the close brace. A position is /// considered to be inside an expression body if it is on or after /// the '=>' and strictly before the semicolon. /// </summary> internal static bool IsInBody(int position, BaseMethodDeclarationSyntax method) => IsInBody(position, method.Body, method.GetExpressionBodySyntax(), method.SemicolonToken); internal static bool IsBetweenTokens(int position, SyntaxToken firstIncluded, SyntaxToken firstExcluded) { return position >= firstIncluded.SpanStart && IsBeforeToken(position, firstExcluded); } /// <summary> /// Returns true if position is within the given node and before the first excluded token. /// </summary> private static bool IsBeforeToken(int position, CSharpSyntaxNode node, SyntaxToken firstExcluded) { return IsBeforeToken(position, firstExcluded) && position >= node.SpanStart; } private static bool IsBeforeToken(int position, SyntaxToken firstExcluded) { return firstExcluded.Kind() == SyntaxKind.None || position < firstExcluded.SpanStart; } internal static bool IsInAttributeSpecification(int position, SyntaxList<AttributeListSyntax> attributesSyntaxList) { int count = attributesSyntaxList.Count; if (count == 0) { return false; } var startToken = attributesSyntaxList[0].OpenBracketToken; var endToken = attributesSyntaxList[count - 1].CloseBracketToken; return IsBetweenTokens(position, startToken, endToken); } internal static bool IsInTypeParameterList(int position, TypeDeclarationSyntax typeDecl) { var typeParameterListOpt = typeDecl.TypeParameterList; return typeParameterListOpt != null && IsBeforeToken(position, typeParameterListOpt, typeParameterListOpt.GreaterThanToken); } internal static bool IsInParameterList(int position, BaseMethodDeclarationSyntax methodDecl) { var parameterList = methodDecl.ParameterList; return IsBeforeToken(position, parameterList, parameterList.CloseParenToken); } internal static bool IsInParameterList(int position, ParameterListSyntax parameterList) => parameterList != null && IsBeforeToken(position, parameterList, parameterList.CloseParenToken); internal static bool IsInMethodDeclaration(int position, BaseMethodDeclarationSyntax methodDecl) { Debug.Assert(methodDecl != null); var body = methodDecl.Body; if (body == null) { return IsBeforeToken(position, methodDecl, methodDecl.SemicolonToken); } return IsBeforeToken(position, methodDecl, body.CloseBraceToken) || IsInExpressionBody(position, methodDecl.GetExpressionBodySyntax(), methodDecl.SemicolonToken); } internal static bool IsInMethodDeclaration(int position, AccessorDeclarationSyntax accessorDecl) { Debug.Assert(accessorDecl != null); var body = accessorDecl.Body; SyntaxToken lastToken = body == null ? accessorDecl.SemicolonToken : body.CloseBraceToken; return IsBeforeToken(position, accessorDecl, lastToken); } internal static bool IsInDelegateDeclaration(int position, DelegateDeclarationSyntax delegateDecl) { Debug.Assert(delegateDecl != null); return IsBeforeToken(position, delegateDecl, delegateDecl.SemicolonToken); } internal static bool IsInTypeDeclaration(int position, BaseTypeDeclarationSyntax typeDecl) { Debug.Assert(typeDecl != null); return IsBeforeToken(position, typeDecl, typeDecl.CloseBraceToken); } internal static bool IsInNamespaceDeclaration(int position, NamespaceDeclarationSyntax namespaceDecl) { Debug.Assert(namespaceDecl != null); return IsBetweenTokens(position, namespaceDecl.NamespaceKeyword, namespaceDecl.CloseBraceToken); } internal static bool IsInNamespaceDeclaration(int position, FileScopedNamespaceDeclarationSyntax namespaceDecl) { Debug.Assert(namespaceDecl != null); return position >= namespaceDecl.SpanStart; } internal static bool IsInConstructorParameterScope(int position, ConstructorDeclarationSyntax constructorDecl) { Debug.Assert(constructorDecl != null); var initializerOpt = constructorDecl.Initializer; var hasBody = constructorDecl.Body != null || constructorDecl.ExpressionBody != null; if (!hasBody) { var nextToken = (SyntaxToken)SyntaxNavigator.Instance.GetNextToken(constructorDecl, predicate: null, stepInto: null); return initializerOpt == null ? position >= constructorDecl.ParameterList.CloseParenToken.Span.End && IsBeforeToken(position, nextToken) : IsBetweenTokens(position, initializerOpt.ColonToken, nextToken); } return initializerOpt == null ? IsInBody(position, constructorDecl) : IsBetweenTokens(position, initializerOpt.ColonToken, constructorDecl.SemicolonToken.Kind() == SyntaxKind.None ? constructorDecl.Body!.CloseBraceToken : constructorDecl.SemicolonToken); } internal static bool IsInMethodTypeParameterScope(int position, MethodDeclarationSyntax methodDecl) { Debug.Assert(methodDecl != null); Debug.Assert(IsInMethodDeclaration(position, methodDecl)); if (methodDecl.TypeParameterList == null) { // no type parameters => nothing can be in their scope return false; } // optimization for a common case - when position is in the ReturnType, we can see type parameters if (methodDecl.ReturnType.FullSpan.Contains(position)) { return true; } // Must be in the method, but not in an attribute on the method. if (IsInAttributeSpecification(position, methodDecl.AttributeLists)) { return false; } var explicitInterfaceSpecifier = methodDecl.ExplicitInterfaceSpecifier; var firstNameToken = explicitInterfaceSpecifier == null ? methodDecl.Identifier : explicitInterfaceSpecifier.GetFirstToken(); var typeParams = methodDecl.TypeParameterList; var firstPostNameToken = typeParams == null ? methodDecl.ParameterList.OpenParenToken : typeParams.LessThanToken; // Scope does not include method name. return !IsBetweenTokens(position, firstNameToken, firstPostNameToken); } /// <remarks> /// Used to determine whether it would be appropriate to use the binder for the statement (if any). /// Not used to determine whether the position is syntactically within the statement. /// </remarks> internal static bool IsInStatementScope(int position, StatementSyntax statement) { Debug.Assert(statement != null); if (statement.Kind() == SyntaxKind.EmptyStatement) { return false; } // CONSIDER: the check for default(SyntaxToken) could go in IsBetweenTokens, // but this is where it has special meaning. SyntaxToken firstIncludedToken = GetFirstIncludedToken(statement); return firstIncludedToken != default(SyntaxToken) && IsBetweenTokens(position, firstIncludedToken, GetFirstExcludedToken(statement)); } /// <remarks> /// Used to determine whether it would be appropriate to use the binder for the switch section (if any). /// Not used to determine whether the position is syntactically within the statement. /// </remarks> internal static bool IsInSwitchSectionScope(int position, SwitchSectionSyntax section) { Debug.Assert(section != null); return section.Span.Contains(position); } /// <remarks> /// Used to determine whether it would be appropriate to use the binder for the statement (if any). /// Not used to determine whether the position is syntactically within the statement. /// </remarks> internal static bool IsInCatchBlockScope(int position, CatchClauseSyntax catchClause) { Debug.Assert(catchClause != null); return IsBetweenTokens(position, catchClause.Block.OpenBraceToken, catchClause.Block.CloseBraceToken); } /// <remarks> /// Used to determine whether it would be appropriate to use the binder for the statement (if any). /// Not used to determine whether the position is syntactically within the statement. /// </remarks> internal static bool IsInCatchFilterScope(int position, CatchFilterClauseSyntax filterClause) { Debug.Assert(filterClause != null); return IsBetweenTokens(position, filterClause.OpenParenToken, filterClause.CloseParenToken); } private static SyntaxToken GetFirstIncludedToken(StatementSyntax statement) { Debug.Assert(statement != null); switch (statement.Kind()) { case SyntaxKind.Block: return ((BlockSyntax)statement).OpenBraceToken; case SyntaxKind.BreakStatement: return ((BreakStatementSyntax)statement).BreakKeyword; case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return ((CheckedStatementSyntax)statement).Keyword; case SyntaxKind.ContinueStatement: return ((ContinueStatementSyntax)statement).ContinueKeyword; case SyntaxKind.ExpressionStatement: case SyntaxKind.LocalDeclarationStatement: return statement.GetFirstToken(); case SyntaxKind.DoStatement: return ((DoStatementSyntax)statement).DoKeyword; case SyntaxKind.EmptyStatement: return default(SyntaxToken); //The caller will have to check for this. case SyntaxKind.FixedStatement: return ((FixedStatementSyntax)statement).FixedKeyword; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: return ((CommonForEachStatementSyntax)statement).OpenParenToken.GetNextToken(); case SyntaxKind.ForStatement: return ((ForStatementSyntax)statement).OpenParenToken.GetNextToken(); case SyntaxKind.GotoDefaultStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoStatement: return ((GotoStatementSyntax)statement).GotoKeyword; case SyntaxKind.IfStatement: return ((IfStatementSyntax)statement).IfKeyword; case SyntaxKind.LabeledStatement: return ((LabeledStatementSyntax)statement).Identifier; case SyntaxKind.LockStatement: return ((LockStatementSyntax)statement).LockKeyword; case SyntaxKind.ReturnStatement: return ((ReturnStatementSyntax)statement).ReturnKeyword; case SyntaxKind.SwitchStatement: return ((SwitchStatementSyntax)statement).Expression.GetFirstToken(); case SyntaxKind.ThrowStatement: return ((ThrowStatementSyntax)statement).ThrowKeyword; case SyntaxKind.TryStatement: return ((TryStatementSyntax)statement).TryKeyword; case SyntaxKind.UnsafeStatement: return ((UnsafeStatementSyntax)statement).UnsafeKeyword; case SyntaxKind.UsingStatement: return ((UsingStatementSyntax)statement).UsingKeyword; case SyntaxKind.WhileStatement: return ((WhileStatementSyntax)statement).WhileKeyword; case SyntaxKind.YieldReturnStatement: case SyntaxKind.YieldBreakStatement: return ((YieldStatementSyntax)statement).YieldKeyword; case SyntaxKind.LocalFunctionStatement: return statement.GetFirstToken(); default: throw ExceptionUtilities.UnexpectedValue(statement.Kind()); } } internal static SyntaxToken GetFirstExcludedToken(StatementSyntax statement) { Debug.Assert(statement != null); switch (statement.Kind()) { case SyntaxKind.Block: return ((BlockSyntax)statement).CloseBraceToken; case SyntaxKind.BreakStatement: return ((BreakStatementSyntax)statement).SemicolonToken; case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return ((CheckedStatementSyntax)statement).Block.CloseBraceToken; case SyntaxKind.ContinueStatement: return ((ContinueStatementSyntax)statement).SemicolonToken; case SyntaxKind.LocalDeclarationStatement: return ((LocalDeclarationStatementSyntax)statement).SemicolonToken; case SyntaxKind.DoStatement: return ((DoStatementSyntax)statement).SemicolonToken; case SyntaxKind.EmptyStatement: return ((EmptyStatementSyntax)statement).SemicolonToken; case SyntaxKind.ExpressionStatement: return ((ExpressionStatementSyntax)statement).SemicolonToken; case SyntaxKind.FixedStatement: return GetFirstExcludedToken(((FixedStatementSyntax)statement).Statement); case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: return GetFirstExcludedToken(((CommonForEachStatementSyntax)statement).Statement); case SyntaxKind.ForStatement: return GetFirstExcludedToken(((ForStatementSyntax)statement).Statement); case SyntaxKind.GotoDefaultStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoStatement: return ((GotoStatementSyntax)statement).SemicolonToken; case SyntaxKind.IfStatement: IfStatementSyntax ifStmt = (IfStatementSyntax)statement; ElseClauseSyntax? elseOpt = ifStmt.Else; return GetFirstExcludedToken(elseOpt == null ? ifStmt.Statement : elseOpt.Statement); case SyntaxKind.LabeledStatement: return GetFirstExcludedToken(((LabeledStatementSyntax)statement).Statement); case SyntaxKind.LockStatement: return GetFirstExcludedToken(((LockStatementSyntax)statement).Statement); case SyntaxKind.ReturnStatement: return ((ReturnStatementSyntax)statement).SemicolonToken; case SyntaxKind.SwitchStatement: return ((SwitchStatementSyntax)statement).CloseBraceToken; case SyntaxKind.ThrowStatement: return ((ThrowStatementSyntax)statement).SemicolonToken; case SyntaxKind.TryStatement: TryStatementSyntax tryStmt = (TryStatementSyntax)statement; FinallyClauseSyntax? finallyClause = tryStmt.Finally; if (finallyClause != null) { return finallyClause.Block.CloseBraceToken; } CatchClauseSyntax? lastCatch = tryStmt.Catches.LastOrDefault(); if (lastCatch != null) { return lastCatch.Block.CloseBraceToken; } return tryStmt.Block.CloseBraceToken; case SyntaxKind.UnsafeStatement: return ((UnsafeStatementSyntax)statement).Block.CloseBraceToken; case SyntaxKind.UsingStatement: return GetFirstExcludedToken(((UsingStatementSyntax)statement).Statement); case SyntaxKind.WhileStatement: return GetFirstExcludedToken(((WhileStatementSyntax)statement).Statement); case SyntaxKind.YieldReturnStatement: case SyntaxKind.YieldBreakStatement: return ((YieldStatementSyntax)statement).SemicolonToken; case SyntaxKind.LocalFunctionStatement: LocalFunctionStatementSyntax localFunctionStmt = (LocalFunctionStatementSyntax)statement; if (localFunctionStmt.Body != null) return GetFirstExcludedToken(localFunctionStmt.Body); if (localFunctionStmt.SemicolonToken != default(SyntaxToken)) return localFunctionStmt.SemicolonToken; return localFunctionStmt.ParameterList.GetLastToken(); default: throw ExceptionUtilities.UnexpectedValue(statement.Kind()); } } internal static bool IsInAnonymousFunctionOrQuery(int position, SyntaxNode lambdaExpressionOrQueryNode) { Debug.Assert(lambdaExpressionOrQueryNode.IsAnonymousFunction() || lambdaExpressionOrQueryNode.IsQuery()); SyntaxToken firstIncluded; CSharpSyntaxNode body; switch (lambdaExpressionOrQueryNode.Kind()) { case SyntaxKind.SimpleLambdaExpression: SimpleLambdaExpressionSyntax simple = (SimpleLambdaExpressionSyntax)lambdaExpressionOrQueryNode; firstIncluded = simple.ArrowToken; body = simple.Body; break; case SyntaxKind.ParenthesizedLambdaExpression: ParenthesizedLambdaExpressionSyntax parenthesized = (ParenthesizedLambdaExpressionSyntax)lambdaExpressionOrQueryNode; firstIncluded = parenthesized.ArrowToken; body = parenthesized.Body; break; case SyntaxKind.AnonymousMethodExpression: AnonymousMethodExpressionSyntax anon = (AnonymousMethodExpressionSyntax)lambdaExpressionOrQueryNode; body = anon.Block; firstIncluded = body.GetFirstToken(includeZeroWidth: true); break; default: // OK, so we have some kind of query clause. They all start with a keyword token, so we'll skip that. firstIncluded = lambdaExpressionOrQueryNode.GetFirstToken().GetNextToken(); return IsBetweenTokens(position, firstIncluded, lambdaExpressionOrQueryNode.GetLastToken().GetNextToken()); } var bodyStatement = body as StatementSyntax; var firstExcluded = bodyStatement != null ? GetFirstExcludedToken(bodyStatement) : (SyntaxToken)SyntaxNavigator.Instance.GetNextToken(body, predicate: null, stepInto: null); return IsBetweenTokens(position, firstIncluded, firstExcluded); } internal static bool IsInXmlAttributeValue(int position, XmlAttributeSyntax attribute) { return IsBetweenTokens(position, attribute.StartQuoteToken, attribute.EndQuoteToken); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Tools/ExternalAccess/Razor/Remote/RazorRemoteHostClient.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { internal sealed class RazorRemoteHostClient { private readonly ServiceHubRemoteHostClient _client; private readonly RazorServiceDescriptorsWrapper _serviceDescriptors; private readonly RazorRemoteServiceCallbackDispatcherRegistry _callbackDispatchers; internal RazorRemoteHostClient(ServiceHubRemoteHostClient client, RazorServiceDescriptorsWrapper serviceDescriptors, RazorRemoteServiceCallbackDispatcherRegistry callbackDispatchers) { _client = client; _serviceDescriptors = serviceDescriptors; _callbackDispatchers = callbackDispatchers; } public static async Task<RazorRemoteHostClient?> TryGetClientAsync(HostWorkspaceServices services, RazorServiceDescriptorsWrapper serviceDescriptors, RazorRemoteServiceCallbackDispatcherRegistry callbackDispatchers, CancellationToken cancellationToken = default) { var client = await RemoteHostClient.TryGetClientAsync(services, cancellationToken).ConfigureAwait(false); if (client is null) return null; return new RazorRemoteHostClient((ServiceHubRemoteHostClient)client, serviceDescriptors, callbackDispatchers); } public RazorRemoteServiceConnectionWrapper<TService> CreateConnection<TService>(object? callbackTarget) where TService : class => new(_client.CreateConnection<TService>(_serviceDescriptors.UnderlyingObject, _callbackDispatchers, callbackTarget)); // no solution, no callback: public async ValueTask<bool> TryInvokeAsync<TService>(Func<TService, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Func<TService, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } // no solution, callback: public async ValueTask<bool> TryInvokeAsync<TService>(Func<TService, RazorRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Func<TService, RazorRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask<TResult>> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } // solution, no callback: public async ValueTask<bool> TryInvokeAsync<TService>(Solution solution, Func<TService, RazorPinnedSolutionInfoWrapper, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Solution solution, Func<TService, RazorPinnedSolutionInfoWrapper, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } // solution, callback: public async ValueTask<bool> TryInvokeAsync<TService>(Solution solution, Func<TService, RazorPinnedSolutionInfoWrapper, RazorRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Solution solution, Func<TService, RazorPinnedSolutionInfoWrapper, RazorRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask<TResult>> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { internal sealed class RazorRemoteHostClient { private readonly ServiceHubRemoteHostClient _client; private readonly RazorServiceDescriptorsWrapper _serviceDescriptors; private readonly RazorRemoteServiceCallbackDispatcherRegistry _callbackDispatchers; internal RazorRemoteHostClient(ServiceHubRemoteHostClient client, RazorServiceDescriptorsWrapper serviceDescriptors, RazorRemoteServiceCallbackDispatcherRegistry callbackDispatchers) { _client = client; _serviceDescriptors = serviceDescriptors; _callbackDispatchers = callbackDispatchers; } public static async Task<RazorRemoteHostClient?> TryGetClientAsync(HostWorkspaceServices services, RazorServiceDescriptorsWrapper serviceDescriptors, RazorRemoteServiceCallbackDispatcherRegistry callbackDispatchers, CancellationToken cancellationToken = default) { var client = await RemoteHostClient.TryGetClientAsync(services, cancellationToken).ConfigureAwait(false); if (client is null) return null; return new RazorRemoteHostClient((ServiceHubRemoteHostClient)client, serviceDescriptors, callbackDispatchers); } public RazorRemoteServiceConnectionWrapper<TService> CreateConnection<TService>(object? callbackTarget) where TService : class => new(_client.CreateConnection<TService>(_serviceDescriptors.UnderlyingObject, _callbackDispatchers, callbackTarget)); // no solution, no callback: public async ValueTask<bool> TryInvokeAsync<TService>(Func<TService, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Func<TService, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } // no solution, callback: public async ValueTask<bool> TryInvokeAsync<TService>(Func<TService, RazorRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Func<TService, RazorRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask<TResult>> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } // solution, no callback: public async ValueTask<bool> TryInvokeAsync<TService>(Solution solution, Func<TService, RazorPinnedSolutionInfoWrapper, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Solution solution, Func<TService, RazorPinnedSolutionInfoWrapper, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } // solution, callback: public async ValueTask<bool> TryInvokeAsync<TService>(Solution solution, Func<TService, RazorPinnedSolutionInfoWrapper, RazorRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Solution solution, Func<TService, RazorPinnedSolutionInfoWrapper, RazorRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask<TResult>> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Compilers/CSharp/Portable/Binder/SwitchExpressionBinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { internal class SwitchExpressionBinder : Binder { private readonly SwitchExpressionSyntax SwitchExpressionSyntax; internal SwitchExpressionBinder(SwitchExpressionSyntax switchExpressionSyntax, Binder next) : base(next) { SwitchExpressionSyntax = switchExpressionSyntax; } internal override BoundExpression BindSwitchExpressionCore(SwitchExpressionSyntax node, Binder originalBinder, BindingDiagnosticBag diagnostics) { Debug.Assert(node == SwitchExpressionSyntax); // Bind switch expression and set the switch governing type. var boundInputExpression = BindSwitchGoverningExpression(diagnostics); ImmutableArray<BoundSwitchExpressionArm> switchArms = BindSwitchExpressionArms(node, originalBinder, boundInputExpression, diagnostics); TypeSymbol? naturalType = InferResultType(switchArms, diagnostics); bool reportedNotExhaustive = CheckSwitchExpressionExhaustive(node, boundInputExpression, switchArms, out BoundDecisionDag decisionDag, out LabelSymbol? defaultLabel, diagnostics); // When the input is constant, we use that to reshape the decision dag that is returned // so that flow analysis will see that some of the cases may be unreachable. decisionDag = decisionDag.SimplifyDecisionDagIfConstantInput(boundInputExpression); return new BoundUnconvertedSwitchExpression( node, boundInputExpression, switchArms, decisionDag, defaultLabel: defaultLabel, reportedNotExhaustive: reportedNotExhaustive, type: naturalType); } /// <summary> /// Build the decision dag, giving an error if some cases are subsumed and a warning if the switch expression is not exhaustive. /// </summary> /// <param name="node"></param> /// <param name="boundInputExpression"></param> /// <param name="switchArms"></param> /// <param name="decisionDag"></param> /// <param name="diagnostics"></param> /// <returns>true if there was a non-exhaustive warning reported</returns> private bool CheckSwitchExpressionExhaustive( SwitchExpressionSyntax node, BoundExpression boundInputExpression, ImmutableArray<BoundSwitchExpressionArm> switchArms, out BoundDecisionDag decisionDag, [NotNullWhen(true)] out LabelSymbol? defaultLabel, BindingDiagnosticBag diagnostics) { defaultLabel = new GeneratedLabelSymbol("default"); decisionDag = DecisionDagBuilder.CreateDecisionDagForSwitchExpression(this.Compilation, node, boundInputExpression, switchArms, defaultLabel, diagnostics); var reachableLabels = decisionDag.ReachableLabels; bool hasErrors = false; foreach (BoundSwitchExpressionArm arm in switchArms) { hasErrors |= arm.HasErrors; if (!hasErrors && !reachableLabels.Contains(arm.Label)) { diagnostics.Add(ErrorCode.ERR_SwitchArmSubsumed, arm.Pattern.Syntax.Location); } } if (!reachableLabels.Contains(defaultLabel)) { // switch expression is exhaustive; no default label needed. defaultLabel = null; return false; } if (hasErrors) return true; // We only report exhaustive warnings when the default label is reachable through some series of // tests that do not include a test in which the value is known to be null. Handling paths with // nulls is the job of the nullable walker. bool wasAcyclic = TopologicalSort.TryIterativeSort<BoundDecisionDagNode>(new[] { decisionDag.RootNode }, nonNullSuccessors, out var nodes); // Since decisionDag.RootNode is acyclic by construction, its subset of nodes sorted here cannot be cyclic Debug.Assert(wasAcyclic); foreach (var n in nodes) { if (n is BoundLeafDecisionDagNode leaf && leaf.Label == defaultLabel) { var samplePattern = PatternExplainer.SamplePatternForPathToDagNode( BoundDagTemp.ForOriginalInput(boundInputExpression), nodes, n, nullPaths: false, out bool requiresFalseWhenClause, out bool unnamedEnumValue); ErrorCode warningCode = requiresFalseWhenClause ? ErrorCode.WRN_SwitchExpressionNotExhaustiveWithWhen : unnamedEnumValue ? ErrorCode.WRN_SwitchExpressionNotExhaustiveWithUnnamedEnumValue : ErrorCode.WRN_SwitchExpressionNotExhaustive; diagnostics.Add( warningCode, node.SwitchKeyword.GetLocation(), samplePattern); return true; } } return false; ImmutableArray<BoundDecisionDagNode> nonNullSuccessors(BoundDecisionDagNode n) { switch (n) { case BoundTestDecisionDagNode p: switch (p.Test) { case BoundDagNonNullTest t: // checks that the input is not null return ImmutableArray.Create(p.WhenTrue); case BoundDagExplicitNullTest t: // checks that the input is null return ImmutableArray.Create(p.WhenFalse); default: return BoundDecisionDag.Successors(n); } default: return BoundDecisionDag.Successors(n); } } } /// <summary> /// Infer the result type of the switch expression by looking for a common type /// to which every arm's expression can be converted. /// </summary> private TypeSymbol? InferResultType(ImmutableArray<BoundSwitchExpressionArm> switchCases, BindingDiagnosticBag diagnostics) { var seenTypes = Symbols.SpecializedSymbolCollections.GetPooledSymbolHashSetInstance<TypeSymbol>(); var typesInOrder = ArrayBuilder<TypeSymbol>.GetInstance(); foreach (var @case in switchCases) { var type = @case.Value.Type; if (type is object && seenTypes.Add(type)) { typesInOrder.Add(type); } } seenTypes.Free(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var commonType = BestTypeInferrer.GetBestType(typesInOrder, Conversions, ref useSiteInfo); typesInOrder.Free(); // We've found a candidate common type among those arms that have a type. Also check that every arm's // expression (even those without a type) can be converted to that type. if (commonType is object) { foreach (var @case in switchCases) { if (!this.Conversions.ClassifyImplicitConversionFromExpression(@case.Value, commonType, ref useSiteInfo).Exists) { commonType = null; break; } } } diagnostics.Add(SwitchExpressionSyntax, useSiteInfo); return commonType; } private ImmutableArray<BoundSwitchExpressionArm> BindSwitchExpressionArms(SwitchExpressionSyntax node, Binder originalBinder, BoundExpression inputExpression, BindingDiagnosticBag diagnostics) { var builder = ArrayBuilder<BoundSwitchExpressionArm>.GetInstance(); (TypeSymbol inputType, uint valEscape) = GetInputTypeAndValEscape(inputExpression); foreach (var arm in node.Arms) { var armBinder = originalBinder.GetRequiredBinder(arm); Debug.Assert(inputExpression.Type is not null); var boundArm = armBinder.BindSwitchExpressionArm(arm, inputType, valEscape, diagnostics); builder.Add(boundArm); } return builder.ToImmutableAndFree(); } internal (TypeSymbol GoverningType, uint GoverningValEscape) GetInputTypeAndValEscape(BoundExpression? inputExpression = null) { inputExpression ??= BindSwitchGoverningExpression(BindingDiagnosticBag.Discarded); Debug.Assert(inputExpression.Type is not null); return (inputExpression.Type, GetValEscape(inputExpression, LocalScopeDepth)); } private BoundExpression BindSwitchGoverningExpression(BindingDiagnosticBag diagnostics) { var switchGoverningExpression = BindRValueWithoutTargetType(SwitchExpressionSyntax.GoverningExpression, diagnostics); if (switchGoverningExpression.Type == (object?)null || switchGoverningExpression.Type.IsVoidType()) { diagnostics.Add(ErrorCode.ERR_BadPatternExpression, SwitchExpressionSyntax.GoverningExpression.Location, switchGoverningExpression.Display); switchGoverningExpression = this.GenerateConversionForAssignment(CreateErrorType(), switchGoverningExpression, diagnostics); } return switchGoverningExpression; } } }
// Licensed to the .NET Foundation under one or more 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 System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { internal class SwitchExpressionBinder : Binder { private readonly SwitchExpressionSyntax SwitchExpressionSyntax; internal SwitchExpressionBinder(SwitchExpressionSyntax switchExpressionSyntax, Binder next) : base(next) { SwitchExpressionSyntax = switchExpressionSyntax; } internal override BoundExpression BindSwitchExpressionCore(SwitchExpressionSyntax node, Binder originalBinder, BindingDiagnosticBag diagnostics) { Debug.Assert(node == SwitchExpressionSyntax); // Bind switch expression and set the switch governing type. var boundInputExpression = BindSwitchGoverningExpression(diagnostics); ImmutableArray<BoundSwitchExpressionArm> switchArms = BindSwitchExpressionArms(node, originalBinder, boundInputExpression, diagnostics); TypeSymbol? naturalType = InferResultType(switchArms, diagnostics); bool reportedNotExhaustive = CheckSwitchExpressionExhaustive(node, boundInputExpression, switchArms, out BoundDecisionDag decisionDag, out LabelSymbol? defaultLabel, diagnostics); // When the input is constant, we use that to reshape the decision dag that is returned // so that flow analysis will see that some of the cases may be unreachable. decisionDag = decisionDag.SimplifyDecisionDagIfConstantInput(boundInputExpression); return new BoundUnconvertedSwitchExpression( node, boundInputExpression, switchArms, decisionDag, defaultLabel: defaultLabel, reportedNotExhaustive: reportedNotExhaustive, type: naturalType); } /// <summary> /// Build the decision dag, giving an error if some cases are subsumed and a warning if the switch expression is not exhaustive. /// </summary> /// <param name="node"></param> /// <param name="boundInputExpression"></param> /// <param name="switchArms"></param> /// <param name="decisionDag"></param> /// <param name="diagnostics"></param> /// <returns>true if there was a non-exhaustive warning reported</returns> private bool CheckSwitchExpressionExhaustive( SwitchExpressionSyntax node, BoundExpression boundInputExpression, ImmutableArray<BoundSwitchExpressionArm> switchArms, out BoundDecisionDag decisionDag, [NotNullWhen(true)] out LabelSymbol? defaultLabel, BindingDiagnosticBag diagnostics) { defaultLabel = new GeneratedLabelSymbol("default"); decisionDag = DecisionDagBuilder.CreateDecisionDagForSwitchExpression(this.Compilation, node, boundInputExpression, switchArms, defaultLabel, diagnostics); var reachableLabels = decisionDag.ReachableLabels; bool hasErrors = false; foreach (BoundSwitchExpressionArm arm in switchArms) { hasErrors |= arm.HasErrors; if (!hasErrors && !reachableLabels.Contains(arm.Label)) { diagnostics.Add(ErrorCode.ERR_SwitchArmSubsumed, arm.Pattern.Syntax.Location); } } if (!reachableLabels.Contains(defaultLabel)) { // switch expression is exhaustive; no default label needed. defaultLabel = null; return false; } if (hasErrors) return true; // We only report exhaustive warnings when the default label is reachable through some series of // tests that do not include a test in which the value is known to be null. Handling paths with // nulls is the job of the nullable walker. bool wasAcyclic = TopologicalSort.TryIterativeSort<BoundDecisionDagNode>(new[] { decisionDag.RootNode }, nonNullSuccessors, out var nodes); // Since decisionDag.RootNode is acyclic by construction, its subset of nodes sorted here cannot be cyclic Debug.Assert(wasAcyclic); foreach (var n in nodes) { if (n is BoundLeafDecisionDagNode leaf && leaf.Label == defaultLabel) { var samplePattern = PatternExplainer.SamplePatternForPathToDagNode( BoundDagTemp.ForOriginalInput(boundInputExpression), nodes, n, nullPaths: false, out bool requiresFalseWhenClause, out bool unnamedEnumValue); ErrorCode warningCode = requiresFalseWhenClause ? ErrorCode.WRN_SwitchExpressionNotExhaustiveWithWhen : unnamedEnumValue ? ErrorCode.WRN_SwitchExpressionNotExhaustiveWithUnnamedEnumValue : ErrorCode.WRN_SwitchExpressionNotExhaustive; diagnostics.Add( warningCode, node.SwitchKeyword.GetLocation(), samplePattern); return true; } } return false; ImmutableArray<BoundDecisionDagNode> nonNullSuccessors(BoundDecisionDagNode n) { switch (n) { case BoundTestDecisionDagNode p: switch (p.Test) { case BoundDagNonNullTest t: // checks that the input is not null return ImmutableArray.Create(p.WhenTrue); case BoundDagExplicitNullTest t: // checks that the input is null return ImmutableArray.Create(p.WhenFalse); default: return BoundDecisionDag.Successors(n); } default: return BoundDecisionDag.Successors(n); } } } /// <summary> /// Infer the result type of the switch expression by looking for a common type /// to which every arm's expression can be converted. /// </summary> private TypeSymbol? InferResultType(ImmutableArray<BoundSwitchExpressionArm> switchCases, BindingDiagnosticBag diagnostics) { var seenTypes = Symbols.SpecializedSymbolCollections.GetPooledSymbolHashSetInstance<TypeSymbol>(); var typesInOrder = ArrayBuilder<TypeSymbol>.GetInstance(); foreach (var @case in switchCases) { var type = @case.Value.Type; if (type is object && seenTypes.Add(type)) { typesInOrder.Add(type); } } seenTypes.Free(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var commonType = BestTypeInferrer.GetBestType(typesInOrder, Conversions, ref useSiteInfo); typesInOrder.Free(); // We've found a candidate common type among those arms that have a type. Also check that every arm's // expression (even those without a type) can be converted to that type. if (commonType is object) { foreach (var @case in switchCases) { if (!this.Conversions.ClassifyImplicitConversionFromExpression(@case.Value, commonType, ref useSiteInfo).Exists) { commonType = null; break; } } } diagnostics.Add(SwitchExpressionSyntax, useSiteInfo); return commonType; } private ImmutableArray<BoundSwitchExpressionArm> BindSwitchExpressionArms(SwitchExpressionSyntax node, Binder originalBinder, BoundExpression inputExpression, BindingDiagnosticBag diagnostics) { var builder = ArrayBuilder<BoundSwitchExpressionArm>.GetInstance(); (TypeSymbol inputType, uint valEscape) = GetInputTypeAndValEscape(inputExpression); foreach (var arm in node.Arms) { var armBinder = originalBinder.GetRequiredBinder(arm); Debug.Assert(inputExpression.Type is not null); var boundArm = armBinder.BindSwitchExpressionArm(arm, inputType, valEscape, diagnostics); builder.Add(boundArm); } return builder.ToImmutableAndFree(); } internal (TypeSymbol GoverningType, uint GoverningValEscape) GetInputTypeAndValEscape(BoundExpression? inputExpression = null) { inputExpression ??= BindSwitchGoverningExpression(BindingDiagnosticBag.Discarded); Debug.Assert(inputExpression.Type is not null); return (inputExpression.Type, GetValEscape(inputExpression, LocalScopeDepth)); } private BoundExpression BindSwitchGoverningExpression(BindingDiagnosticBag diagnostics) { var switchGoverningExpression = BindRValueWithoutTargetType(SwitchExpressionSyntax.GoverningExpression, diagnostics); if (switchGoverningExpression.Type == (object?)null || switchGoverningExpression.Type.IsVoidType()) { diagnostics.Add(ErrorCode.ERR_BadPatternExpression, SwitchExpressionSyntax.GoverningExpression.Location, switchGoverningExpression.Display); switchGoverningExpression = this.GenerateConversionForAssignment(CreateErrorType(), switchGoverningExpression, diagnostics); } return switchGoverningExpression; } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/CommitManager.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; using AsyncCompletionData = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { internal sealed class CommitManager : ForegroundThreadAffinitizedObject, IAsyncCompletionCommitManager { private static readonly AsyncCompletionData.CommitResult CommitResultUnhandled = new(isHandled: false, AsyncCompletionData.CommitBehavior.None); private readonly RecentItemsManager _recentItemsManager; private readonly ITextView _textView; public IEnumerable<char> PotentialCommitCharacters { get { if (_textView.Properties.TryGetProperty(CompletionSource.PotentialCommitCharacters, out ImmutableArray<char> potentialCommitCharacters)) { return potentialCommitCharacters; } else { // If we were not initialized with a CompletionService or are called for a wrong textView, we should not make a commit. return ImmutableArray<char>.Empty; } } } internal CommitManager(ITextView textView, RecentItemsManager recentItemsManager, IThreadingContext threadingContext) : base(threadingContext) { _recentItemsManager = recentItemsManager; _textView = textView; } /// <summary> /// The method performs a preliminarily filtering of commit availability. /// In case of a doubt, it should respond with true. /// We will be able to cancel later in /// <see cref="TryCommit(IAsyncCompletionSession, ITextBuffer, VSCompletionItem, char, CancellationToken)"/> /// based on <see cref="VSCompletionItem"/> item, e.g. based on <see cref="CompletionItemRules"/>. /// </summary> public bool ShouldCommitCompletion( IAsyncCompletionSession session, SnapshotPoint location, char typedChar, CancellationToken cancellationToken) { if (!PotentialCommitCharacters.Contains(typedChar)) { return false; } return !(session.Properties.TryGetProperty(CompletionSource.ExcludedCommitCharacters, out ImmutableArray<char> excludedCommitCharacter) && excludedCommitCharacter.Contains(typedChar)); } public AsyncCompletionData.CommitResult TryCommit( IAsyncCompletionSession session, ITextBuffer subjectBuffer, VSCompletionItem item, char typeChar, CancellationToken cancellationToken) { // We can make changes to buffers. We would like to be sure nobody can change them at the same time. AssertIsForeground(); var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return CommitResultUnhandled; } var completionService = document.GetLanguageService<CompletionService>(); if (completionService == null) { return CommitResultUnhandled; } if (!item.Properties.TryGetProperty(CompletionSource.RoslynItem, out RoslynCompletionItem roslynItem)) { // Roslyn should not be called if the item committing was not provided by Roslyn. return CommitResultUnhandled; } var filterText = session.ApplicableToSpan.GetText(session.ApplicableToSpan.TextBuffer.CurrentSnapshot) + typeChar; if (Helpers.IsFilterCharacter(roslynItem, typeChar, filterText)) { // Returning Cancel means we keep the current session and consider the character for further filtering. return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.CancelCommit); } var serviceRules = completionService.GetRules(); // We can be called before for ShouldCommitCompletion. However, that call does not provide rules applied for the completion item. // Now we check for the commit charcter in the context of Rules that could change the list of commit characters. if (!Helpers.IsStandardCommitCharacter(typeChar) && !IsCommitCharacter(serviceRules, roslynItem, typeChar)) { // Returning None means we complete the current session with a void commit. // The Editor then will try to trigger a new completion session for the character. return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } if (!item.Properties.TryGetProperty(CompletionSource.TriggerLocation, out SnapshotPoint triggerLocation)) { // Need the trigger snapshot to calculate the span when the commit changes to be applied. // They should always be available from items provided by Roslyn CompletionSource. // Just to be defensive, if it's not found here, Roslyn should not make a commit. return CommitResultUnhandled; } if (!session.Properties.TryGetProperty(CompletionSource.CompletionListSpan, out TextSpan completionListSpan)) { return CommitResultUnhandled; } var triggerDocument = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (triggerDocument == null) { return CommitResultUnhandled; } // Telemetry if (session.TextView.Properties.TryGetProperty(CompletionSource.TypeImportCompletionEnabled, out bool isTyperImportCompletionEnabled) && isTyperImportCompletionEnabled) { AsyncCompletionLogger.LogCommitWithTypeImportCompletionEnabled(); } if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isExperimentEnabled) && isExperimentEnabled) { // Capture the % of committed completion items that would have appeared in the "Target type matches" filter // (regardless of whether that filter button was active at the time of commit). AsyncCompletionLogger.LogCommitWithTargetTypeCompletionExperimentEnabled(); if (item.Filters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches)) { AsyncCompletionLogger.LogCommitItemWithTargetTypeFilter(); } } // Commit with completion service assumes that null is provided is case of invoke. VS provides '\0' in the case. var commitChar = typeChar == '\0' ? null : (char?)typeChar; return Commit( session, triggerDocument, completionService, subjectBuffer, roslynItem, completionListSpan, commitChar, triggerLocation.Snapshot, serviceRules, filterText, cancellationToken); } private AsyncCompletionData.CommitResult Commit( IAsyncCompletionSession session, Document document, CompletionService completionService, ITextBuffer subjectBuffer, RoslynCompletionItem roslynItem, TextSpan completionListSpan, char? commitCharacter, ITextSnapshot triggerSnapshot, CompletionRules rules, string filterText, CancellationToken cancellationToken) { AssertIsForeground(); bool includesCommitCharacter; if (!subjectBuffer.CheckEditAccess()) { // We are on the wrong thread. FatalError.ReportAndCatch(new InvalidOperationException("Subject buffer did not provide Edit Access")); return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } if (subjectBuffer.EditInProgress) { FatalError.ReportAndCatch(new InvalidOperationException("Subject buffer is editing by someone else.")); return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } CompletionChange change; // We met an issue when external code threw an OperationCanceledException and the cancellationToken is not cancelled. // Catching this scenario for further investigations. // See https://github.com/dotnet/roslyn/issues/38455. try { // Cached items have a span computed at the point they were created. This span may no // longer be valid when used again. In that case, override the span with the latest span // for the completion list itself. if (roslynItem.Flags.IsCached()) roslynItem.Span = completionListSpan; change = completionService.GetChangeAsync(document, roslynItem, commitCharacter, cancellationToken).WaitAndGetResult(cancellationToken); } catch (OperationCanceledException e) when (e.CancellationToken != cancellationToken && FatalError.ReportAndCatch(e)) { return CommitResultUnhandled; } cancellationToken.ThrowIfCancellationRequested(); var view = session.TextView; var provider = GetCompletionProvider(completionService, roslynItem); if (provider is ICustomCommitCompletionProvider customCommitProvider) { customCommitProvider.Commit(roslynItem, view, subjectBuffer, triggerSnapshot, commitCharacter); return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } var textChange = change.TextChange; var triggerSnapshotSpan = new SnapshotSpan(triggerSnapshot, textChange.Span.ToSpan()); var mappedSpan = triggerSnapshotSpan.TranslateTo(subjectBuffer.CurrentSnapshot, SpanTrackingMode.EdgeInclusive); using (var edit = subjectBuffer.CreateEdit(EditOptions.DefaultMinimalChange, reiteratedVersionNumber: null, editTag: null)) { edit.Replace(mappedSpan.Span, change.TextChange.NewText); // edit.Apply() may trigger changes made by extensions. // updatedCurrentSnapshot will contain changes made by Roslyn but not by other extensions. var updatedCurrentSnapshot = edit.Apply(); if (change.NewPosition.HasValue) { // Roslyn knows how to positionate the caret in the snapshot we just created. // If there were more edits made by extensions, TryMoveCaretToAndEnsureVisible maps the snapshot point to the most recent one. view.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(updatedCurrentSnapshot, change.NewPosition.Value)); } else { // Or, If we're doing a minimal change, then the edit that we make to the // buffer may not make the total text change that places the caret where we // would expect it to go based on the requested change. In this case, // determine where the item should go and set the care manually. // Note: we only want to move the caret if the caret would have been moved // by the edit. i.e. if the caret was actually in the mapped span that // we're replacing. var caretPositionInBuffer = view.GetCaretPoint(subjectBuffer); if (caretPositionInBuffer.HasValue && mappedSpan.IntersectsWith(caretPositionInBuffer.Value)) { view.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(subjectBuffer.CurrentSnapshot, mappedSpan.Start.Position + textChange.NewText?.Length ?? 0)); } else { view.Caret.EnsureVisible(); } } includesCommitCharacter = change.IncludesCommitCharacter; if (roslynItem.Rules.FormatOnCommit) { // The edit updates the snapshot however other extensions may make changes there. // Therefore, it is required to use subjectBuffer.CurrentSnapshot for further calculations rather than the updated current snapsot defined above. var currentDocument = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); var formattingService = currentDocument?.GetRequiredLanguageService<IFormattingInteractionService>(); if (currentDocument != null && formattingService != null) { var spanToFormat = triggerSnapshotSpan.TranslateTo(subjectBuffer.CurrentSnapshot, SpanTrackingMode.EdgeInclusive); var changes = formattingService.GetFormattingChangesAsync( currentDocument, spanToFormat.Span.ToTextSpan(), documentOptions: null, CancellationToken.None).WaitAndGetResult(CancellationToken.None); currentDocument.Project.Solution.Workspace.ApplyTextChanges(currentDocument.Id, changes, CancellationToken.None); } } } _recentItemsManager.MakeMostRecentItem(roslynItem.FilterText); if (provider is INotifyCommittingItemCompletionProvider notifyProvider) { _ = ThreadingContext.JoinableTaskFactory.RunAsync(async () => { // Make sure the notification isn't sent on UI thread. await TaskScheduler.Default; _ = notifyProvider.NotifyCommittingItemAsync(document, roslynItem, commitCharacter, cancellationToken).ReportNonFatalErrorAsync(); }); } if (includesCommitCharacter) { return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.SuppressFurtherTypeCharCommandHandlers); } if (commitCharacter == '\n' && SendEnterThroughToEditor(rules, roslynItem, filterText)) { return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.RaiseFurtherReturnKeyAndTabKeyCommandHandlers); } return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } internal static bool IsCommitCharacter(CompletionRules completionRules, CompletionItem item, char ch) { // First see if the item has any specifc commit rules it wants followed. foreach (var rule in item.Rules.CommitCharacterRules) { switch (rule.Kind) { case CharacterSetModificationKind.Add: if (rule.Characters.Contains(ch)) { return true; } continue; case CharacterSetModificationKind.Remove: if (rule.Characters.Contains(ch)) { return false; } continue; case CharacterSetModificationKind.Replace: return rule.Characters.Contains(ch); } } // Fall back to the default rules for this language's completion service. return completionRules.DefaultCommitCharacters.IndexOf(ch) >= 0; } internal static bool SendEnterThroughToEditor(CompletionRules rules, RoslynCompletionItem item, string textTypedSoFar) { var rule = item.Rules.EnterKeyRule; if (rule == EnterKeyRule.Default) { rule = rules.DefaultEnterKeyRule; } switch (rule) { default: case EnterKeyRule.Default: case EnterKeyRule.Never: return false; case EnterKeyRule.Always: return true; case EnterKeyRule.AfterFullyTypedWord: // textTypedSoFar is concatenated from individual chars typed. // '\n' is the enter char. // That is why, there is no need to check for '\r\n'. if (textTypedSoFar.LastOrDefault() == '\n') { textTypedSoFar = textTypedSoFar.Substring(0, textTypedSoFar.Length - 1); } return item.GetEntireDisplayText() == textTypedSoFar; } } private static CompletionProvider? GetCompletionProvider(CompletionService completionService, CompletionItem item) { if (completionService is CompletionServiceWithProviders completionServiceWithProviders) { return completionServiceWithProviders.GetProvider(item); } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; using AsyncCompletionData = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { internal sealed class CommitManager : ForegroundThreadAffinitizedObject, IAsyncCompletionCommitManager { private static readonly AsyncCompletionData.CommitResult CommitResultUnhandled = new(isHandled: false, AsyncCompletionData.CommitBehavior.None); private readonly RecentItemsManager _recentItemsManager; private readonly ITextView _textView; public IEnumerable<char> PotentialCommitCharacters { get { if (_textView.Properties.TryGetProperty(CompletionSource.PotentialCommitCharacters, out ImmutableArray<char> potentialCommitCharacters)) { return potentialCommitCharacters; } else { // If we were not initialized with a CompletionService or are called for a wrong textView, we should not make a commit. return ImmutableArray<char>.Empty; } } } internal CommitManager(ITextView textView, RecentItemsManager recentItemsManager, IThreadingContext threadingContext) : base(threadingContext) { _recentItemsManager = recentItemsManager; _textView = textView; } /// <summary> /// The method performs a preliminarily filtering of commit availability. /// In case of a doubt, it should respond with true. /// We will be able to cancel later in /// <see cref="TryCommit(IAsyncCompletionSession, ITextBuffer, VSCompletionItem, char, CancellationToken)"/> /// based on <see cref="VSCompletionItem"/> item, e.g. based on <see cref="CompletionItemRules"/>. /// </summary> public bool ShouldCommitCompletion( IAsyncCompletionSession session, SnapshotPoint location, char typedChar, CancellationToken cancellationToken) { if (!PotentialCommitCharacters.Contains(typedChar)) { return false; } return !(session.Properties.TryGetProperty(CompletionSource.ExcludedCommitCharacters, out ImmutableArray<char> excludedCommitCharacter) && excludedCommitCharacter.Contains(typedChar)); } public AsyncCompletionData.CommitResult TryCommit( IAsyncCompletionSession session, ITextBuffer subjectBuffer, VSCompletionItem item, char typeChar, CancellationToken cancellationToken) { // We can make changes to buffers. We would like to be sure nobody can change them at the same time. AssertIsForeground(); var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return CommitResultUnhandled; } var completionService = document.GetLanguageService<CompletionService>(); if (completionService == null) { return CommitResultUnhandled; } if (!item.Properties.TryGetProperty(CompletionSource.RoslynItem, out RoslynCompletionItem roslynItem)) { // Roslyn should not be called if the item committing was not provided by Roslyn. return CommitResultUnhandled; } var filterText = session.ApplicableToSpan.GetText(session.ApplicableToSpan.TextBuffer.CurrentSnapshot) + typeChar; if (Helpers.IsFilterCharacter(roslynItem, typeChar, filterText)) { // Returning Cancel means we keep the current session and consider the character for further filtering. return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.CancelCommit); } var serviceRules = completionService.GetRules(); // We can be called before for ShouldCommitCompletion. However, that call does not provide rules applied for the completion item. // Now we check for the commit charcter in the context of Rules that could change the list of commit characters. if (!Helpers.IsStandardCommitCharacter(typeChar) && !IsCommitCharacter(serviceRules, roslynItem, typeChar)) { // Returning None means we complete the current session with a void commit. // The Editor then will try to trigger a new completion session for the character. return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } if (!item.Properties.TryGetProperty(CompletionSource.TriggerLocation, out SnapshotPoint triggerLocation)) { // Need the trigger snapshot to calculate the span when the commit changes to be applied. // They should always be available from items provided by Roslyn CompletionSource. // Just to be defensive, if it's not found here, Roslyn should not make a commit. return CommitResultUnhandled; } if (!session.Properties.TryGetProperty(CompletionSource.CompletionListSpan, out TextSpan completionListSpan)) { return CommitResultUnhandled; } var triggerDocument = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (triggerDocument == null) { return CommitResultUnhandled; } // Telemetry if (session.TextView.Properties.TryGetProperty(CompletionSource.TypeImportCompletionEnabled, out bool isTyperImportCompletionEnabled) && isTyperImportCompletionEnabled) { AsyncCompletionLogger.LogCommitWithTypeImportCompletionEnabled(); } if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isExperimentEnabled) && isExperimentEnabled) { // Capture the % of committed completion items that would have appeared in the "Target type matches" filter // (regardless of whether that filter button was active at the time of commit). AsyncCompletionLogger.LogCommitWithTargetTypeCompletionExperimentEnabled(); if (item.Filters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches)) { AsyncCompletionLogger.LogCommitItemWithTargetTypeFilter(); } } // Commit with completion service assumes that null is provided is case of invoke. VS provides '\0' in the case. var commitChar = typeChar == '\0' ? null : (char?)typeChar; return Commit( session, triggerDocument, completionService, subjectBuffer, roslynItem, completionListSpan, commitChar, triggerLocation.Snapshot, serviceRules, filterText, cancellationToken); } private AsyncCompletionData.CommitResult Commit( IAsyncCompletionSession session, Document document, CompletionService completionService, ITextBuffer subjectBuffer, RoslynCompletionItem roslynItem, TextSpan completionListSpan, char? commitCharacter, ITextSnapshot triggerSnapshot, CompletionRules rules, string filterText, CancellationToken cancellationToken) { AssertIsForeground(); bool includesCommitCharacter; if (!subjectBuffer.CheckEditAccess()) { // We are on the wrong thread. FatalError.ReportAndCatch(new InvalidOperationException("Subject buffer did not provide Edit Access")); return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } if (subjectBuffer.EditInProgress) { FatalError.ReportAndCatch(new InvalidOperationException("Subject buffer is editing by someone else.")); return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } CompletionChange change; // We met an issue when external code threw an OperationCanceledException and the cancellationToken is not cancelled. // Catching this scenario for further investigations. // See https://github.com/dotnet/roslyn/issues/38455. try { // Cached items have a span computed at the point they were created. This span may no // longer be valid when used again. In that case, override the span with the latest span // for the completion list itself. if (roslynItem.Flags.IsCached()) roslynItem.Span = completionListSpan; change = completionService.GetChangeAsync(document, roslynItem, commitCharacter, cancellationToken).WaitAndGetResult(cancellationToken); } catch (OperationCanceledException e) when (e.CancellationToken != cancellationToken && FatalError.ReportAndCatch(e)) { return CommitResultUnhandled; } cancellationToken.ThrowIfCancellationRequested(); var view = session.TextView; var provider = GetCompletionProvider(completionService, roslynItem); if (provider is ICustomCommitCompletionProvider customCommitProvider) { customCommitProvider.Commit(roslynItem, view, subjectBuffer, triggerSnapshot, commitCharacter); return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } var textChange = change.TextChange; var triggerSnapshotSpan = new SnapshotSpan(triggerSnapshot, textChange.Span.ToSpan()); var mappedSpan = triggerSnapshotSpan.TranslateTo(subjectBuffer.CurrentSnapshot, SpanTrackingMode.EdgeInclusive); using (var edit = subjectBuffer.CreateEdit(EditOptions.DefaultMinimalChange, reiteratedVersionNumber: null, editTag: null)) { edit.Replace(mappedSpan.Span, change.TextChange.NewText); // edit.Apply() may trigger changes made by extensions. // updatedCurrentSnapshot will contain changes made by Roslyn but not by other extensions. var updatedCurrentSnapshot = edit.Apply(); if (change.NewPosition.HasValue) { // Roslyn knows how to positionate the caret in the snapshot we just created. // If there were more edits made by extensions, TryMoveCaretToAndEnsureVisible maps the snapshot point to the most recent one. view.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(updatedCurrentSnapshot, change.NewPosition.Value)); } else { // Or, If we're doing a minimal change, then the edit that we make to the // buffer may not make the total text change that places the caret where we // would expect it to go based on the requested change. In this case, // determine where the item should go and set the care manually. // Note: we only want to move the caret if the caret would have been moved // by the edit. i.e. if the caret was actually in the mapped span that // we're replacing. var caretPositionInBuffer = view.GetCaretPoint(subjectBuffer); if (caretPositionInBuffer.HasValue && mappedSpan.IntersectsWith(caretPositionInBuffer.Value)) { view.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(subjectBuffer.CurrentSnapshot, mappedSpan.Start.Position + textChange.NewText?.Length ?? 0)); } else { view.Caret.EnsureVisible(); } } includesCommitCharacter = change.IncludesCommitCharacter; if (roslynItem.Rules.FormatOnCommit) { // The edit updates the snapshot however other extensions may make changes there. // Therefore, it is required to use subjectBuffer.CurrentSnapshot for further calculations rather than the updated current snapsot defined above. var currentDocument = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); var formattingService = currentDocument?.GetRequiredLanguageService<IFormattingInteractionService>(); if (currentDocument != null && formattingService != null) { var spanToFormat = triggerSnapshotSpan.TranslateTo(subjectBuffer.CurrentSnapshot, SpanTrackingMode.EdgeInclusive); var changes = formattingService.GetFormattingChangesAsync( currentDocument, spanToFormat.Span.ToTextSpan(), documentOptions: null, CancellationToken.None).WaitAndGetResult(CancellationToken.None); currentDocument.Project.Solution.Workspace.ApplyTextChanges(currentDocument.Id, changes, CancellationToken.None); } } } _recentItemsManager.MakeMostRecentItem(roslynItem.FilterText); if (provider is INotifyCommittingItemCompletionProvider notifyProvider) { _ = ThreadingContext.JoinableTaskFactory.RunAsync(async () => { // Make sure the notification isn't sent on UI thread. await TaskScheduler.Default; _ = notifyProvider.NotifyCommittingItemAsync(document, roslynItem, commitCharacter, cancellationToken).ReportNonFatalErrorAsync(); }); } if (includesCommitCharacter) { return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.SuppressFurtherTypeCharCommandHandlers); } if (commitCharacter == '\n' && SendEnterThroughToEditor(rules, roslynItem, filterText)) { return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.RaiseFurtherReturnKeyAndTabKeyCommandHandlers); } return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } internal static bool IsCommitCharacter(CompletionRules completionRules, CompletionItem item, char ch) { // First see if the item has any specifc commit rules it wants followed. foreach (var rule in item.Rules.CommitCharacterRules) { switch (rule.Kind) { case CharacterSetModificationKind.Add: if (rule.Characters.Contains(ch)) { return true; } continue; case CharacterSetModificationKind.Remove: if (rule.Characters.Contains(ch)) { return false; } continue; case CharacterSetModificationKind.Replace: return rule.Characters.Contains(ch); } } // Fall back to the default rules for this language's completion service. return completionRules.DefaultCommitCharacters.IndexOf(ch) >= 0; } internal static bool SendEnterThroughToEditor(CompletionRules rules, RoslynCompletionItem item, string textTypedSoFar) { var rule = item.Rules.EnterKeyRule; if (rule == EnterKeyRule.Default) { rule = rules.DefaultEnterKeyRule; } switch (rule) { default: case EnterKeyRule.Default: case EnterKeyRule.Never: return false; case EnterKeyRule.Always: return true; case EnterKeyRule.AfterFullyTypedWord: // textTypedSoFar is concatenated from individual chars typed. // '\n' is the enter char. // That is why, there is no need to check for '\r\n'. if (textTypedSoFar.LastOrDefault() == '\n') { textTypedSoFar = textTypedSoFar.Substring(0, textTypedSoFar.Length - 1); } return item.GetEntireDisplayText() == textTypedSoFar; } } private static CompletionProvider? GetCompletionProvider(CompletionService completionService, CompletionItem item) { if (completionService is CompletionServiceWithProviders completionServiceWithProviders) { return completionServiceWithProviders.GetProvider(item); } return null; } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Compilers/VisualBasic/Portable/CodeGen/Optimizer/StackScheduler.Analyzer.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGen Partial Friend Class StackScheduler ''' <summary> ''' context of expression evaluation. ''' it will affect inference of stack behavior ''' it will also affect when expressions can be dup-reused ''' Example: ''' Goo(x, ref x) x cannot be duped as it is used in different context ''' </summary> Private Enum ExprContext None Sideeffects Value Address AssignmentTarget Box End Enum ''' <summary> ''' Analyzes the tree trying to figure which locals may live on stack. It is ''' a fairly delicate process and must be very familiar with how CodeGen works. ''' It is essentially a part of CodeGen. ''' ''' NOTE: It is always safe to mark a local as not eligible as a stack local ''' so when situation gets complicated we just refuse to schedule and move on. ''' </summary> Private NotInheritable Class Analyzer Inherits BoundTreeRewriter Private ReadOnly _container As Symbol Private _counter As Integer = 0 Private ReadOnly _evalStack As ArrayBuilder(Of (expression As BoundExpression, context As ExprContext)) Private ReadOnly _debugFriendly As Boolean Private _context As ExprContext = ExprContext.None Private _assignmentLocal As BoundLocal = Nothing Private ReadOnly _locals As New Dictionary(Of LocalSymbol, LocalDefUseInfo) ''' <summary> ''' fake local that represents the eval stack. when we need to ensure that eval ''' stack is not blocked by stack Locals, we record an access to empty. ''' </summary> Private ReadOnly _empty As DummyLocal ' we need to guarantee same stack patterns at branches and labels. we do that by placing ' a fake dummy local at one end of a branch and force that it is accessible at another. ' if any stack local tries to intervene and misbalance the stack, it will clash with ' the dummy and will be rejected. Private ReadOnly _dummyVariables As New Dictionary(Of Object, DummyLocal) Private _recursionDepth As Integer Private Sub New(container As Symbol, evalStack As ArrayBuilder(Of ValueTuple(Of BoundExpression, ExprContext)), debugFriendly As Boolean) Me._container = container Me._evalStack = evalStack Me._debugFriendly = debugFriendly Me._empty = New DummyLocal(container) ' this is the top of eval stack DeclareLocal(_empty, 0) RecordDummyWrite(_empty) End Sub Public Shared Function Analyze( container As Symbol, node As BoundNode, debugFriendly As Boolean, <Out> ByRef locals As Dictionary(Of LocalSymbol, LocalDefUseInfo)) As BoundNode Dim evalStack = ArrayBuilder(Of ValueTuple(Of BoundExpression, ExprContext)).GetInstance() Dim analyzer = New Analyzer(container, evalStack, debugFriendly) Dim rewritten As BoundNode = analyzer.Visit(node) evalStack.Free() locals = analyzer._locals Return rewritten End Function Public Overrides Function Visit(node As BoundNode) As BoundNode Dim result As BoundNode Dim expr = TryCast(node, BoundExpression) If expr IsNot Nothing Then Debug.Assert(expr.Kind <> BoundKind.Label) result = VisitExpression(expr, ExprContext.Value) Else result = VisitStatement(node) End If Return result End Function Private Function VisitExpressionCore(node As BoundExpression, context As ExprContext) As BoundExpression If node Is Nothing Then Me._counter += 1 Return node End If Dim prevContext As ExprContext = Me._context Dim prevStack As Integer = Me.StackDepth() Me._context = context ' Don not recurse into constant expressions. Their children do Not push any values. Dim result = If(node.ConstantValueOpt Is Nothing, DirectCast(MyBase.Visit(node), BoundExpression), node) _context = prevContext _counter += 1 Select Case context Case ExprContext.Sideeffects SetStackDepth(prevStack) Case ExprContext.AssignmentTarget Exit Select Case ExprContext.Value, ExprContext.Address, ExprContext.Box SetStackDepth(prevStack) PushEvalStack(node, context) Case Else Throw ExceptionUtilities.UnexpectedValue(context) End Select Return result End Function Private Sub PushEvalStack(result As BoundExpression, context As ExprContext) Debug.Assert(result IsNot Nothing OrElse context = ExprContext.None) _evalStack.Add((result, context)) End Sub Private Function StackDepth() As Integer Return _evalStack.Count End Function Private Function EvalStackIsEmpty() As Boolean Return StackDepth() = 0 End Function Private Sub SetStackDepth(depth As Integer) _evalStack.Clip(depth) End Sub Private Sub PopEvalStack() SetStackDepth(_evalStack.Count - 1) End Sub Private Sub ClearEvalStack() _evalStack.Clear() End Sub Private Function VisitExpression(node As BoundExpression, context As ExprContext) As BoundExpression Dim result As BoundExpression _recursionDepth += 1 If _recursionDepth > 1 Then StackGuard.EnsureSufficientExecutionStack(_recursionDepth) result = VisitExpressionCore(node, context) Else result = VisitExpressionCoreWithStackGuard(node, context) End If _recursionDepth -= 1 Return result End Function Private Function VisitExpressionCoreWithStackGuard(node As BoundExpression, context As ExprContext) As BoundExpression Debug.Assert(_recursionDepth = 1) Try Dim result = VisitExpressionCore(node, context) Debug.Assert(_recursionDepth = 1) Return result Catch ex As InsufficientExecutionStackException Throw New CancelledByStackGuardException(ex, node) End Try End Function Protected Overrides Function VisitExpressionWithoutStackGuard(node As BoundExpression) As BoundExpression Throw ExceptionUtilities.Unreachable End Function Public Overrides Function VisitSpillSequence(node As BoundSpillSequence) As BoundNode Throw ExceptionUtilities.Unreachable End Function Private Function VisitStatement(node As BoundNode) As BoundNode Debug.Assert(node Is Nothing OrElse EvalStackIsEmpty()) Dim origStack = StackDepth() Dim prevContext As ExprContext = Me._context Dim result As BoundNode = MyBase.Visit(node) ' prevent cross-statement local optimizations ' when emitting debug-friendly code. If _debugFriendly Then EnsureOnlyEvalStack() End If Me._context = prevContext SetStackDepth(origStack) _counter += 1 Return result End Function ''' <summary> ''' here we have a case of indirect assignment: *t1 = expr; ''' normally we would need to push t1 and that will cause spilling of t2 ''' ''' TODO: an interesting case arises in unused x[i]++ and ++x[i] : ''' we have trees that look like: ''' ''' t1 = &amp;(x[0]) ''' t2 = *t1 ''' *t1 = t2 + 1 ''' ''' t1 = &amp;(x[0]) ''' t2 = *t1 + 1 ''' *t1 = t2 ''' ''' in these cases, we could keep t2 on stack (dev10 does). ''' we are dealing with exactly 2 locals and access them in strict order ''' t1, t2, t1, t2 and we are not using t2 after that. ''' We may consider detecting exactly these cases and pretend that we do not need ''' to push either t1 or t2 in this case. ''' </summary> Private Function LhsUsesStackWhenAssignedTo(node As BoundNode, context As ExprContext) As Boolean Debug.Assert(context = ExprContext.AssignmentTarget) If node Is Nothing Then Return Nothing End If Select Case node.Kind Case BoundKind.Local, BoundKind.Parameter Return False Case BoundKind.FieldAccess Return Not DirectCast(node, BoundFieldAccess).FieldSymbol.IsShared Case BoundKind.Sequence Return LhsUsesStackWhenAssignedTo(DirectCast(node, BoundSequence).ValueOpt, context) End Select Return True End Function Public Overrides Function VisitBlock(node As BoundBlock) As BoundNode Debug.Assert(EvalStackIsEmpty(), "entering blocks when evaluation stack is not empty?") ' normally we would not allow stack locals ' when evaluation stack is not empty. DeclareLocals(node.Locals, 0) Return MyBase.VisitBlock(node) End Function Public Overrides Function VisitSequence(node As BoundSequence) As BoundNode ' Normally we can only use stack for local scheduling if stack is not used for evaluation. ' In a context of a regular block that simply means that eval stack must be empty. ' Sequences, can be entered on a nonempty evaluation stack ' Ex: ' a.b = Seq{var y, y = 1, y} // a is on the stack for the duration of the sequence. ' ' However evaluation stack at the entry cannot be used inside the sequence, so such stack ' works as effective "empty" for locals declared in sequence. ' Therefore sequence locals can be stack scheduled at same stack as at the entry to the sequence. ' it may seem attractive to relax the stack requirement to be: ' "all uses must agree on stack depth". ' The following example illustrates a case where x is safely used at "declarationStack + 1" ' Ex: ' Seq{var x; y.a = Seq{x = 1; x}; y} // x is used while y is on the eval stack ' ' It is, however not safe assumption in general since eval stack may be accessed between usages. ' Ex: ' Seq{var x; y.a = Seq{x = 1; x}; y.z = x; y} // x blocks access to y ' ' ' --------------------------------------------------- ' NOTE: The following is not implemented in VB ' ' There is one case where we want to tweak the "use at declaration stack" rule - in the case of ' compound assignment that involves ByRef operand captures (like: x[y]++ ) . ' ' Those cases produce specific sequences of the shapes: ' ' prefix: Seq{var temp, ref operand; operand initializers; *operand = Seq{temp = (T)(operand + 1); temp;} result: temp} ' postfix: Seq{var temp, ref operand; operand initializers; *operand = Seq{temp = operand; ; (T)(temp + 1);} result: temp} ' ' 1) temp is used as the result of the sequence (and that is the only reason why it is declared in the outer sequence). ' 2) all side-effects except the last one do not use the temp. ' 3) last side-effect is an indirect assignment of a sequence (and target does not involve the temp). ' ' Note that in a case of side-effects context, the result value will be ignored and therefore ' all usages of the nested temp will be confined to the nested sequence that is executed at +1 stack. ' ' We will detect such case and indicate +1 as the desired stack depth at local accesses. ' --------------------------------------------------- ' Dim declarationStack As Integer = Me.StackDepth() Dim locals = node.Locals If Not locals.IsEmpty Then If Me._context = ExprContext.Sideeffects Then DeclareLocals(locals, declarationStack) ' --------------------------------------------------- ' NOTE: not implemented workaround from above ' foreach (var local in locals) ' { ' if (IsNestedLocalOfCompoundOperator(local, node)) ' { ' // special case ' DeclareLocal(local, declarationStack + 1); ' } ' else ' { ' DeclareLocal(local, declarationStack); ' } ' } ' } ' --------------------------------------------------- Else DeclareLocals(locals, declarationStack) End If End If ' rewrite operands Dim origContext As ExprContext = Me._context Dim sideeffects As ImmutableArray(Of BoundExpression) = node.SideEffects Dim rewrittenSideeffects As ArrayBuilder(Of BoundExpression) = Nothing If Not sideeffects.IsDefault Then For i = 0 To sideeffects.Length - 1 Dim sideeffect As BoundExpression = sideeffects(i) Dim rewrittenSideeffect As BoundExpression = Me.VisitExpression(sideeffect, ExprContext.Sideeffects) If rewrittenSideeffects Is Nothing AndAlso rewrittenSideeffect IsNot sideeffect Then rewrittenSideeffects = ArrayBuilder(Of BoundExpression).GetInstance() rewrittenSideeffects.AddRange(sideeffects, i) End If If rewrittenSideeffects IsNot Nothing Then rewrittenSideeffects.Add(rewrittenSideeffect) End If Next End If Dim value As BoundExpression = Me.VisitExpression(node.ValueOpt, origContext) Return node.Update(node.Locals, If(rewrittenSideeffects IsNot Nothing, rewrittenSideeffects.ToImmutableAndFree(), sideeffects), value, node.Type) End Function #If False Then '// detect a pattern used in compound operators '// where a temp is declared in the outer sequence '// only because it must be returned, otherwise all uses are '// confined to the nested sequence that is indirectly assigned (and therefore has +1 stack) '// in such case the desired stack for this local is +1 'private bool IsNestedLocalOfCompoundOperator(LocalSymbol local, BoundSequence node) '{ ' var value = node.Value; ' // local must be used as the value of the sequence. ' if (value != null && value.Kind == BoundKind.Local && ((BoundLocal)value).LocalSymbol == local) ' { ' var sideeffects = node.SideEffects; ' var lastSideeffect = sideeffects.LastOrDefault(); ' if (lastSideeffect != null) ' { ' // last side-effect must be an indirect assignment of a sequence. ' if (lastSideeffect.Kind == BoundKind.AssignmentOperator) ' { ' var assignment = (BoundAssignmentOperator)lastSideeffect; ' if (IsIndirectAssignment(assignment) && ' assignment.Right.Kind == BoundKind.Sequence) ' { ' // and no other side-effects should use the variable ' var localUsedWalker = new LocalUsedWalker(local); ' for (int i = 0; i < sideeffects.Count - 1; i++) ' { ' if (localUsedWalker.IsLocalUsedIn(sideeffects[i])) ' { ' return false; ' } ' } ' // and local is not used on the left of the assignment ' // (extra check, but better be safe) ' if (localUsedWalker.IsLocalUsedIn(assignment.Left)) ' { ' return false; ' } ' // it should be used somewhere ' Debug.Assert(localUsedWalker.IsLocalUsedIn(assignment.Right), "who assigns the temp?"); ' return true; ' } ' } ' } ' } ' return false; '} 'private class LocalUsedWalker : BoundTreeWalker '{ ' private readonly LocalSymbol local; ' private bool found; ' internal LocalUsedWalker(LocalSymbol local) ' { ' this.local = local; ' } ' public bool IsLocalUsedIn(BoundExpression node) ' { ' this.found = false; ' this.Visit(node); ' return found; ' } ' public override BoundNode Visit(BoundNode node) ' { ' if (!found) ' { ' return base.Visit(node); ' } ' return null; ' } ' public override BoundNode VisitLocal(BoundLocal node) ' { ' if (node.LocalSymbol == local) ' { ' this.found = true; ' } ' return null; ' } '} #End If Public Overrides Function VisitExpressionStatement(node As BoundExpressionStatement) As BoundNode Return node.Update(Me.VisitExpression(node.Expression, ExprContext.Sideeffects)) End Function Public Overrides Function VisitLocal(node As BoundLocal) As BoundNode If node.ConstantValueOpt Is Nothing Then Select Case Me._context Case ExprContext.Address If node.LocalSymbol.IsByRef Then RecordVarRead(node.LocalSymbol) Else RecordVarRef(node.LocalSymbol) End If Case ExprContext.AssignmentTarget Debug.Assert(Me._assignmentLocal Is Nothing) ' actual assignment will happen later, after Right is evaluated ' just remember what we are assigning to. Me._assignmentLocal = node Case ExprContext.Sideeffects ' do nothing Case ExprContext.Value, ExprContext.Box RecordVarRead(node.LocalSymbol) End Select End If Return MyBase.VisitLocal(node) End Function Public Overrides Function VisitReferenceAssignment(node As BoundReferenceAssignment) As BoundNode ' Visit a local in context of regular assignment Dim left = DirectCast(VisitExpression(node.ByRefLocal, ExprContext.AssignmentTarget), BoundLocal) Dim storedAssignmentLocal = Me._assignmentLocal Me._assignmentLocal = Nothing ' Visit a l-value expression in context of 'address' Dim right As BoundExpression = VisitExpression(node.LValue, ExprContext.Address) ' record the Write to the local Debug.Assert(storedAssignmentLocal IsNot Nothing) ' this assert will fire if code relies on implicit CLR coercions ' - i.e assigns int value to a short local. ' in that case we should force lhs to be a real local Debug.Assert(node.ByRefLocal.Type.IsSameTypeIgnoringAll(node.LValue.Type), "cannot use stack when assignment involves implicit coercion of the value") RecordVarWrite(storedAssignmentLocal.LocalSymbol) Return node.Update(left, right, node.IsLValue, node.Type) End Function Public Overrides Function VisitAssignmentOperator(node As BoundAssignmentOperator) As BoundNode Dim isIndirect As Boolean = IsIndirectAssignment(node) Dim left As BoundExpression = VisitExpression(node.Left, If(isIndirect, ExprContext.Address, ExprContext.AssignmentTarget)) ' must delay recording a write until after RHS is evaluated Dim storedAssignmentLocal = Me._assignmentLocal Me._assignmentLocal = Nothing Debug.Assert(Me._context <> ExprContext.AssignmentTarget, "assignment expression cannot be a target of another assignment") ' Left on the right should be Nothing by this time Debug.Assert(node.LeftOnTheRightOpt Is Nothing) ' Do not visit "Left on the right" 'Me.counter += 1 Dim rhsContext As ExprContext If Me._context = ExprContext.Address Then ' we need the address of rhs so we cannot have it on the stack. rhsContext = ExprContext.Address Else Debug.Assert(Me._context = ExprContext.Value OrElse Me._context = ExprContext.Box OrElse Me._context = ExprContext.Sideeffects, "assignment expression cannot be a target of another assignment") ' we only need a value of rhs, so if otherwise possible it can be a stack value. rhsContext = ExprContext.Value End If Dim right As BoundExpression = node.Right ' if right is a struct ctor, it may be optimized into in-place call ' Such call will push the receiver ref before the arguments ' so we need to ensure that arguments cannot use stack temps Dim leftType As TypeSymbol = left.Type Dim mayPushReceiver As Boolean = False If right.Kind = BoundKind.ObjectCreationExpression Then Dim ctor = DirectCast(right, BoundObjectCreationExpression).ConstructorOpt If ctor IsNot Nothing AndAlso ctor.ParameterCount <> 0 Then mayPushReceiver = True End If End If If mayPushReceiver Then 'push unknown value just to prevent access to stack locals. PushEvalStack(Nothing, ExprContext.None) End If right = VisitExpression(node.Right, rhsContext) If mayPushReceiver Then PopEvalStack() End If ' if assigning to a local, now it is the time to record the Write If storedAssignmentLocal IsNot Nothing Then ' this assert will fire if code relies on implicit CLR coercions ' - i.e assigns int value to a short local. ' in that case we should force lhs to be a real local Debug.Assert(node.Left.Type.IsSameTypeIgnoringAll(node.Right.Type), "cannot use stack when assignment involves implicit coercion of the value") Debug.Assert(Not isIndirect, "indirect assignment is a read, not a write") RecordVarWrite(storedAssignmentLocal.LocalSymbol) End If Return node.Update(left, Nothing, right, node.SuppressObjectClone, node.Type) End Function ''' <summary> ''' VB uses a special node to assign references. ''' BoundAssignment is used only to assign values. ''' therefore an indirect assignment may only happen if lhs is a reference ''' </summary> Private Shared Function IsIndirectAssignment(node As BoundAssignmentOperator) As Boolean Return IsByRefVariable(node.Left) End Function Private Shared Function IsByRefVariable(node As BoundExpression) As Boolean Select Case node.Kind Case BoundKind.Parameter Return DirectCast(node, BoundParameter).ParameterSymbol.IsByRef Case BoundKind.Local Return DirectCast(node, BoundLocal).LocalSymbol.IsByRef Case BoundKind.Call Return DirectCast(node, BoundCall).Method.ReturnsByRef Case BoundKind.Sequence Debug.Assert(Not IsByRefVariable(DirectCast(node, BoundSequence).ValueOpt)) Return False Case BoundKind.PseudoVariable Return True Case BoundKind.ReferenceAssignment Return True Case BoundKind.ValueTypeMeReference Return True Case BoundKind.ModuleVersionId, BoundKind.InstrumentationPayloadRoot ' same as static fields Return False Case BoundKind.FieldAccess, BoundKind.ArrayAccess ' fields are never byref Return False Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select End Function Private Shared Function IsVerifierRef(type As TypeSymbol) As Boolean Return Not type.TypeKind = TypeKind.TypeParameter AndAlso type.IsReferenceType End Function Private Shared Function IsVerifierVal(type As TypeSymbol) As Boolean Return Not type.TypeKind = TypeKind.TypeParameter AndAlso type.IsValueType End Function Public Overrides Function VisitCall(node As BoundCall) As BoundNode Dim receiver = node.ReceiverOpt ' matches or a bit stronger than EmitReceiverRef ' if there are any doubts that receiver is a ref type, ' assume we will need an address (that will prevent scheduling of receiver). If Not node.Method.IsShared Then Dim receiverType = receiver.Type Dim context As ExprContext If receiverType.IsReferenceType Then If (receiverType.IsTypeParameter()) Then ' type param receiver that we statically know Is a reference will be boxed context = ExprContext.Box Else ' reference receivers will be used as values context = ExprContext.Value End If Else ' everything else will get an address taken context = ExprContext.Address End If receiver = VisitExpression(receiver, context) Else Me._counter += 1 Debug.Assert(receiver Is Nothing OrElse receiver.Kind = BoundKind.TypeExpression) End If Dim method As MethodSymbol = node.Method Dim rewrittenArguments As ImmutableArray(Of BoundExpression) = VisitArguments(node.Arguments, method.Parameters) Debug.Assert(node.MethodGroupOpt Is Nothing) Return node.Update( method, node.MethodGroupOpt, receiver, rewrittenArguments, node.DefaultArguments, node.ConstantValueOpt, isLValue:=node.IsLValue, suppressObjectClone:=node.SuppressObjectClone, type:=node.Type) End Function Private Function VisitArguments(arguments As ImmutableArray(Of BoundExpression), parameters As ImmutableArray(Of ParameterSymbol)) As ImmutableArray(Of BoundExpression) Debug.Assert(Not arguments.IsDefault) Debug.Assert(Not parameters.IsDefault) ' If this is a varargs method then there will be one additional argument for the __arglist(). Debug.Assert(arguments.Length = parameters.Length OrElse arguments.Length = parameters.Length + 1) Dim rewrittenArguments As ArrayBuilder(Of BoundExpression) = Nothing For i = 0 To arguments.Length - 1 ' Treat the __arglist() as a value parameter. Dim context As ExprContext = If(i = parameters.Length OrElse Not parameters(i).IsByRef, ExprContext.Value, ExprContext.Address) Dim arg As BoundExpression = arguments(i) Dim rewrittenArg As BoundExpression = VisitExpression(arg, context) If rewrittenArguments Is Nothing AndAlso arg IsNot rewrittenArg Then rewrittenArguments = ArrayBuilder(Of BoundExpression).GetInstance() rewrittenArguments.AddRange(arguments, i) End If If rewrittenArguments IsNot Nothing Then rewrittenArguments.Add(rewrittenArg) End If Next Return If(rewrittenArguments IsNot Nothing, rewrittenArguments.ToImmutableAndFree, arguments) End Function Public Overrides Function VisitObjectCreationExpression(node As BoundObjectCreationExpression) As BoundNode Dim constructor As MethodSymbol = node.ConstructorOpt Debug.Assert(constructor IsNot Nothing OrElse node.Arguments.Length = 0) Dim rewrittenArguments As ImmutableArray(Of BoundExpression) = If(constructor Is Nothing, node.Arguments, VisitArguments(node.Arguments, constructor.Parameters)) Debug.Assert(node.InitializerOpt Is Nothing) Me._counter += 1 Return node.Update(constructor, rewrittenArguments, node.DefaultArguments, Nothing, node.Type) End Function Public Overrides Function VisitArrayAccess(node As BoundArrayAccess) As BoundNode ' regardless of purpose, array access visits its children as values ' TODO: do we need to save/restore old context here? Dim oldContext = Me._context Me._context = ExprContext.Value Dim result As BoundNode = MyBase.VisitArrayAccess(node) Me._context = oldContext Return result End Function Public Overrides Function VisitFieldAccess(node As BoundFieldAccess) As BoundNode Dim field As FieldSymbol = node.FieldSymbol Dim receiver As BoundExpression = node.ReceiverOpt ' if there are any doubts that receiver is a ref type, assume we will ' need an address. (that will prevent scheduling of receiver). If Not field.IsShared Then If receiver.Type.IsTypeParameter Then ' type parameters must be boxed to access fields. receiver = VisitExpression(receiver, ExprContext.Box) Else ' need address when assigning to a field and receiver is not a reference ' when accessing a field of a struct unless we only need Value and Value is preferred. If receiver.Type.IsValueType AndAlso (_context = ExprContext.AssignmentTarget OrElse _context = ExprContext.Address OrElse CodeGenerator.FieldLoadMustUseRef(receiver)) Then receiver = VisitExpression(receiver, ExprContext.Address) Else receiver = VisitExpression(receiver, ExprContext.Value) End If End If Else Me._counter += 1 receiver = Nothing End If Return node.Update(receiver, field, node.IsLValue, node.SuppressVirtualCalls, constantsInProgressOpt:=Nothing, node.Type) End Function Public Overrides Function VisitLabelStatement(node As BoundLabelStatement) As BoundNode RecordLabel(node.Label) Return MyBase.VisitLabelStatement(node) End Function Public Overrides Function VisitGotoStatement(node As BoundGotoStatement) As BoundNode Dim result As BoundNode = MyBase.VisitGotoStatement(node) RecordBranch(node.Label) Return result End Function Public Overrides Function VisitConditionalGoto(node As BoundConditionalGoto) As BoundNode Dim result As BoundNode = MyBase.VisitConditionalGoto(node) Me.PopEvalStack() ' condition gets consumed RecordBranch(node.Label) Return result End Function Public Overrides Function VisitBinaryConditionalExpression(node As BoundBinaryConditionalExpression) As BoundNode Dim origStack = Me.StackDepth Dim testExpression As BoundExpression = DirectCast(Me.Visit(node.TestExpression), BoundExpression) Debug.Assert(node.ConvertedTestExpression Is Nothing) ' Me.counter += 1 '' This child is not visited Debug.Assert(node.TestExpressionPlaceholder Is Nothing) ' Me.counter += 1 '' This child is not visited ' implicit branch here Dim cookie As Object = GetStackStateCookie() Me.SetStackDepth(origStack) ' else expression is evaluated with original stack Dim elseExpression As BoundExpression = DirectCast(Me.Visit(node.ElseExpression), BoundExpression) ' implicit label here EnsureStackState(cookie) Return node.Update(testExpression, Nothing, Nothing, elseExpression, node.ConstantValueOpt, node.Type) End Function Public Overrides Function VisitTernaryConditionalExpression(node As BoundTernaryConditionalExpression) As BoundNode Dim origStack As Integer = Me.StackDepth Dim condition = DirectCast(Me.Visit(node.Condition), BoundExpression) Dim cookie As Object = GetStackStateCookie() ' implicit goto here Me.SetStackDepth(origStack) ' consequence is evaluated with original stack Dim whenTrue = DirectCast(Me.Visit(node.WhenTrue), BoundExpression) EnsureStackState(cookie) ' implicit label here Me.SetStackDepth(origStack) ' alternative is evaluated with original stack Dim whenFalse = DirectCast(Me.Visit(node.WhenFalse), BoundExpression) EnsureStackState(cookie) ' implicit label here Return node.Update(condition, whenTrue, whenFalse, node.ConstantValueOpt, node.Type) End Function Public Overrides Function VisitLoweredConditionalAccess(node As BoundLoweredConditionalAccess) As BoundNode If Not node.ReceiverOrCondition.Type.IsBooleanType() Then ' We may need to load a reference to the receiver, or may need to ' reload it after the null check. This won't work well ' with a stack local. EnsureOnlyEvalStack() End If Dim origStack = StackDepth() Dim receiverOrCondition = DirectCast(Me.Visit(node.ReceiverOrCondition), BoundExpression) Dim cookie = GetStackStateCookie() ' implicit branch here ' access Is evaluated with original stack ' (this Is Not entirely true, codegen will keep receiver on the stack, but that Is irrelevant here) Me.SetStackDepth(origStack) Dim whenNotNull = DirectCast(Me.Visit(node.WhenNotNull), BoundExpression) EnsureStackState(cookie) ' implicit label here Dim whenNull As BoundExpression = Nothing If node.WhenNullOpt IsNot Nothing Then Me.SetStackDepth(origStack) whenNull = DirectCast(Me.Visit(node.WhenNullOpt), BoundExpression) EnsureStackState(cookie) ' implicit label here End If Return node.Update(receiverOrCondition, node.CaptureReceiver, node.PlaceholderId, whenNotNull, whenNull, node.Type) End Function Public Overrides Function VisitConditionalAccessReceiverPlaceholder(node As BoundConditionalAccessReceiverPlaceholder) As BoundNode Return MyBase.VisitConditionalAccessReceiverPlaceholder(node) End Function Public Overrides Function VisitComplexConditionalAccessReceiver(node As BoundComplexConditionalAccessReceiver) As BoundNode EnsureOnlyEvalStack() Dim origStack As Integer = Me.StackDepth Me.PushEvalStack(Nothing, ExprContext.None) Dim cookie As Object = GetStackStateCookie() ' implicit goto here Me.SetStackDepth(origStack) ' consequence is evaluated with original stack Dim valueTypeReceiver = DirectCast(Me.Visit(node.ValueTypeReceiver), BoundExpression) EnsureStackState(cookie) ' implicit label here Me.SetStackDepth(origStack) ' alternative is evaluated with original stack Dim referenceTypeReceiver = DirectCast(Me.Visit(node.ReferenceTypeReceiver), BoundExpression) EnsureStackState(cookie) ' implicit label here Return node.Update(valueTypeReceiver, referenceTypeReceiver, node.Type) End Function Public Overrides Function VisitBinaryOperator(node As BoundBinaryOperator) As BoundNode ' Do not blow the stack due to a deep recursion on the left. Dim child As BoundExpression = node.Left If child.Kind <> BoundKind.BinaryOperator OrElse child.ConstantValueOpt IsNot Nothing Then Return VisitBinaryOperatorSimple(node) End If Dim stack = ArrayBuilder(Of BoundBinaryOperator).GetInstance() stack.Push(node) Dim binary As BoundBinaryOperator = DirectCast(child, BoundBinaryOperator) Do stack.Push(binary) child = binary.Left If child.Kind <> BoundKind.BinaryOperator OrElse child.ConstantValueOpt IsNot Nothing Then Exit Do End If binary = DirectCast(child, BoundBinaryOperator) Loop Dim prevStack As Integer = Me.StackDepth() Dim left = DirectCast(Me.Visit(child), BoundExpression) Do binary = stack.Pop() ' Short-circuit operators need to emulate implicit branch/label Dim isLogical As Boolean Dim cookie As Object = Nothing Select Case (binary.OperatorKind And BinaryOperatorKind.OpMask) Case BinaryOperatorKind.AndAlso, BinaryOperatorKind.OrElse isLogical = True ' implicit branch here cookie = GetStackStateCookie() Me.SetStackDepth(prevStack) ' right is evaluated with original stack Case Else isLogical = False End Select Dim right = DirectCast(Me.Visit(binary.Right), BoundExpression) If isLogical Then ' implicit label here EnsureStackState(cookie) End If Dim type As TypeSymbol = Me.VisitType(binary.Type) left = binary.Update(binary.OperatorKind, left, right, binary.Checked, binary.ConstantValueOpt, type) If stack.Count = 0 Then Exit Do End If _counter += 1 SetStackDepth(prevStack) PushEvalStack(node, ExprContext.Value) Loop Debug.Assert(binary Is node) stack.Free() Return left End Function Private Function VisitBinaryOperatorSimple(node As BoundBinaryOperator) As BoundNode Select Case (node.OperatorKind And BinaryOperatorKind.OpMask) Case BinaryOperatorKind.AndAlso, BinaryOperatorKind.OrElse ' Short-circuit operators need to emulate implicit branch/label Dim origStack = Me.StackDepth Dim left As BoundExpression = DirectCast(Me.Visit(node.Left), BoundExpression) ' implicit branch here Dim cookie As Object = GetStackStateCookie() Me.SetStackDepth(origStack) ' right is evaluated with original stack Dim right As BoundExpression = DirectCast(Me.Visit(node.Right), BoundExpression) ' implicit label here EnsureStackState(cookie) Return node.Update(node.OperatorKind, left, right, node.Checked, node.ConstantValueOpt, node.Type) Case Else Return MyBase.VisitBinaryOperator(node) End Select End Function Public Overrides Function VisitUnaryOperator(node As BoundUnaryOperator) As BoundNode ' checked(-x) is emitted as "0 - x" If node.Checked AndAlso (node.OperatorKind And UnaryOperatorKind.OpMask) = UnaryOperatorKind.Minus Then Dim storedStack = Me.StackDepth Me.PushEvalStack(Nothing, ExprContext.None) Dim operand = DirectCast(Me.Visit(node.Operand), BoundExpression) Me.SetStackDepth(storedStack) Return node.Update(node.OperatorKind, operand, node.Checked, node.ConstantValueOpt, node.Type) Else Return MyBase.VisitUnaryOperator(node) End If End Function Public Overrides Function VisitSelectStatement(node As BoundSelectStatement) As BoundNode ' switch requires that key local stays local EnsureOnlyEvalStack() Dim expressionStatement As BoundExpressionStatement = DirectCast(Me.Visit(node.ExpressionStatement), BoundExpressionStatement) If expressionStatement.Expression.Kind = BoundKind.Local Then ' It is required by code gen that if node.ExpressionStatement ' is a local it should not be optimized out Dim local = DirectCast(expressionStatement.Expression, BoundLocal).LocalSymbol ShouldNotSchedule(local) End If Dim origStack = Me.StackDepth EnsureOnlyEvalStack() Dim exprPlaceholderOpt As BoundRValuePlaceholder = DirectCast(Me.Visit(node.ExprPlaceholderOpt), BoundRValuePlaceholder) ' expression value is consumed by the switch Me.SetStackDepth(origStack) EnsureOnlyEvalStack() ' case blocks Dim caseBlocks As ImmutableArray(Of BoundCaseBlock) = Me.VisitList(node.CaseBlocks) ' exit label Dim exitLabel = node.ExitLabel If exitLabel IsNot Nothing Then Me.RecordLabel(exitLabel) End If EnsureOnlyEvalStack() Return node.Update(expressionStatement, exprPlaceholderOpt, caseBlocks, node.RecommendSwitchTable, exitLabel) End Function Public Overrides Function VisitCaseBlock(node As BoundCaseBlock) As BoundNode EnsureOnlyEvalStack() Dim caseStatement As BoundCaseStatement = DirectCast(Me.Visit(node.CaseStatement), BoundCaseStatement) EnsureOnlyEvalStack() Dim body As BoundBlock = DirectCast(Me.Visit(node.Body), BoundBlock) EnsureOnlyEvalStack() Return node.Update(caseStatement, body) End Function Public Overrides Function VisitUnstructuredExceptionOnErrorSwitch(node As BoundUnstructuredExceptionOnErrorSwitch) As BoundNode Dim value = DirectCast(Visit(node.Value), BoundExpression) Me.PopEvalStack() ' value gets consumed Return node.Update(value, Me.VisitList(node.Jumps)) End Function Public Overrides Function VisitUnstructuredExceptionResumeSwitch(node As BoundUnstructuredExceptionResumeSwitch) As BoundNode Dim resumeLabel = DirectCast(Visit(node.ResumeLabel), BoundLabelStatement) Dim resumeNextLabel = DirectCast(Visit(node.ResumeNextLabel), BoundLabelStatement) Dim resumeTargetTemporary = DirectCast(Visit(node.ResumeTargetTemporary), BoundLocal) Me.PopEvalStack() ' value gets consumed Return node.Update(resumeTargetTemporary, resumeLabel, resumeNextLabel, node.Jumps) End Function Public Overrides Function VisitTryStatement(node As BoundTryStatement) As BoundNode EnsureOnlyEvalStack() Dim tryBlock = DirectCast(Me.Visit(node.TryBlock), BoundBlock) EnsureOnlyEvalStack() Dim catchBlocks As ImmutableArray(Of BoundCatchBlock) = Me.VisitList(node.CatchBlocks) EnsureOnlyEvalStack() Dim finallyBlock = DirectCast(Me.Visit(node.FinallyBlockOpt), BoundBlock) EnsureOnlyEvalStack() If node.ExitLabelOpt IsNot Nothing Then RecordLabel(node.ExitLabelOpt) End If EnsureOnlyEvalStack() Return node.Update(tryBlock, catchBlocks, finallyBlock, node.ExitLabelOpt) End Function Public Overrides Function VisitCatchBlock(node As BoundCatchBlock) As BoundNode Dim origStack As Integer = Me.StackDepth DeclareLocal(node.LocalOpt, origStack) EnsureOnlyEvalStack() Dim exceptionVariableOpt As BoundExpression = Me.VisitExpression(node.ExceptionSourceOpt, ExprContext.Value) Me.SetStackDepth(origStack) EnsureOnlyEvalStack() Dim errorLineNumberOpt As BoundExpression = Me.VisitExpression(node.ErrorLineNumberOpt, ExprContext.Value) Me.SetStackDepth(origStack) EnsureOnlyEvalStack() Dim exceptionFilterOpt As BoundExpression = Me.VisitExpression(node.ExceptionFilterOpt, ExprContext.Value) Me.SetStackDepth(origStack) EnsureOnlyEvalStack() Dim body As BoundBlock = DirectCast(Me.Visit(node.Body), BoundBlock) EnsureOnlyEvalStack() Return node.Update(node.LocalOpt, exceptionVariableOpt, errorLineNumberOpt, exceptionFilterOpt, body, node.IsSynthesizedAsyncCatchAll) End Function Public Overrides Function VisitArrayInitialization(node As BoundArrayInitialization) As BoundNode ' nontrivial construct - may use dups, metadata blob helpers etc.. EnsureOnlyEvalStack() Dim initializers As ImmutableArray(Of BoundExpression) = node.Initializers Dim rewrittenInitializers As ArrayBuilder(Of BoundExpression) = Nothing If Not initializers.IsDefault Then For i = 0 To initializers.Length - 1 ' array itself will be pushed on the stack here. EnsureOnlyEvalStack() Dim initializer As BoundExpression = initializers(i) Dim rewrittenInitializer As BoundExpression = Me.VisitExpression(initializer, ExprContext.Value) If rewrittenInitializers Is Nothing AndAlso rewrittenInitializer IsNot initializer Then rewrittenInitializers = ArrayBuilder(Of BoundExpression).GetInstance() rewrittenInitializers.AddRange(initializers, i) End If If rewrittenInitializers IsNot Nothing Then rewrittenInitializers.Add(rewrittenInitializer) End If Next End If Return node.Update(If(rewrittenInitializers IsNot Nothing, rewrittenInitializers.ToImmutableAndFree(), initializers), node.Type) End Function Public Overrides Function VisitReturnStatement(node As BoundReturnStatement) As BoundNode Dim expressionOpt = TryCast(Me.Visit(node.ExpressionOpt), BoundExpression) ' must not have locals on stack when returning EnsureOnlyEvalStack() Return node.Update(expressionOpt, node.FunctionLocalOpt, node.ExitLabelOpt) End Function ''' <summary> ''' Ensures that there are no stack locals. It is done by accessing ''' virtual "empty" local that is at the bottom of all stack locals. ''' </summary> ''' <remarks></remarks> Private Sub EnsureOnlyEvalStack() RecordVarRead(_empty) End Sub Private Function GetStackStateCookie() As Object ' create a dummy and start tracing it Dim dummy As New DummyLocal(Me._container) Me._dummyVariables.Add(dummy, dummy) Me._locals.Add(dummy, New LocalDefUseInfo(Me.StackDepth)) RecordDummyWrite(dummy) Return dummy End Function Private Sub EnsureStackState(cookie As Object) RecordVarRead(Me._dummyVariables(cookie)) End Sub ' called on branches and labels Private Sub RecordBranch(label As LabelSymbol) Dim dummy As DummyLocal = Nothing If Me._dummyVariables.TryGetValue(label, dummy) Then RecordVarRead(dummy) Else ' create a dummy and start tracing it dummy = New DummyLocal(Me._container) Me._dummyVariables.Add(label, dummy) Me._locals.Add(dummy, New LocalDefUseInfo(Me.StackDepth)) RecordDummyWrite(dummy) End If End Sub Private Sub RecordLabel(label As LabelSymbol) Dim dummy As DummyLocal = Nothing If Me._dummyVariables.TryGetValue(label, dummy) Then RecordVarRead(dummy) Else ' this is a backwards jump with nontrivial stack requirements ' just use empty. dummy = _empty Me._dummyVariables.Add(label, dummy) RecordVarRead(dummy) End If End Sub Private Sub RecordVarRef(local As LocalSymbol) Debug.Assert(Not local.IsByRef, "can't tke a ref of a ref") If Not CanScheduleToStack(local) Then Return End If ' if we ever take a reference of a local, it must be a real local. ShouldNotSchedule(local) End Sub Private Sub RecordVarRead(local As LocalSymbol) If Not CanScheduleToStack(local) Then Return End If Dim locInfo As LocalDefUseInfo = _locals(local) If locInfo.CannotSchedule Then Return End If If locInfo.localDefs.Count = 0 Then ' reading before writing. locInfo.ShouldNotSchedule() Return End If ' if accessing real val, check stack If Not TypeOf local Is DummyLocal Then If locInfo.StackAtDeclaration <> StackDepth() AndAlso Not EvalStackHasLocal(local) Then ' reading at different eval stack. locInfo.ShouldNotSchedule() Return End If Else ' dummy must be accessed on same stack. Debug.Assert(local Is _empty OrElse locInfo.StackAtDeclaration = StackDepth()) End If Dim definedAt As LocalDefUseSpan = locInfo.localDefs.Last() definedAt.SetEnd(Me._counter) Dim locDef As New LocalDefUseSpan(_counter) locInfo.localDefs.Add(locDef) End Sub Private Function EvalStackHasLocal(local As LocalSymbol) As Boolean Dim top = _evalStack.Last() Return top.context = If(Not local.IsByRef, ExprContext.Value, ExprContext.Address) AndAlso top.expression.Kind = BoundKind.Local AndAlso DirectCast(top.expression, BoundLocal).LocalSymbol = local End Function Private Sub RecordVarWrite(local As LocalSymbol) Debug.Assert(local.SynthesizedKind <> SynthesizedLocalKind.OptimizerTemp) If Not CanScheduleToStack(local) Then Return End If Dim locInfo = _locals(local) If locInfo.CannotSchedule Then Return End If ' check stack ' -1 because real assignment "consumes" value. Dim evalStack = Me.StackDepth - 1 If locInfo.StackAtDeclaration <> evalStack Then ' writing at different eval stack. locInfo.ShouldNotSchedule() Return End If Dim locDef = New LocalDefUseSpan(Me._counter) locInfo.localDefs.Add(locDef) End Sub Private Sub RecordDummyWrite(local As LocalSymbol) Debug.Assert(local.SynthesizedKind = SynthesizedLocalKind.OptimizerTemp) Dim locInfo = _locals(local) ' dummy must be accessed on same stack. Debug.Assert(local Is _empty OrElse locInfo.StackAtDeclaration = StackDepth()) Dim locDef = New LocalDefUseSpan(Me._counter) locInfo.localDefs.Add(locDef) End Sub Private Sub ShouldNotSchedule(local As LocalSymbol) Dim localDefInfo As LocalDefUseInfo = Nothing If _locals.TryGetValue(local, localDefInfo) Then localDefInfo.ShouldNotSchedule() End If End Sub Private Function CanScheduleToStack(local As LocalSymbol) As Boolean Return local.CanScheduleToStack AndAlso (Not _debugFriendly OrElse Not local.SynthesizedKind.IsLongLived()) End Function Private Sub DeclareLocals(locals As ImmutableArray(Of LocalSymbol), stack As Integer) For Each local In locals DeclareLocal(local, stack) Next End Sub Private Sub DeclareLocal(local As LocalSymbol, stack As Integer) If local IsNot Nothing Then If CanScheduleToStack(local) Then Me._locals.Add(local, New LocalDefUseInfo(stack)) End If End If End Sub End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGen Partial Friend Class StackScheduler ''' <summary> ''' context of expression evaluation. ''' it will affect inference of stack behavior ''' it will also affect when expressions can be dup-reused ''' Example: ''' Goo(x, ref x) x cannot be duped as it is used in different context ''' </summary> Private Enum ExprContext None Sideeffects Value Address AssignmentTarget Box End Enum ''' <summary> ''' Analyzes the tree trying to figure which locals may live on stack. It is ''' a fairly delicate process and must be very familiar with how CodeGen works. ''' It is essentially a part of CodeGen. ''' ''' NOTE: It is always safe to mark a local as not eligible as a stack local ''' so when situation gets complicated we just refuse to schedule and move on. ''' </summary> Private NotInheritable Class Analyzer Inherits BoundTreeRewriter Private ReadOnly _container As Symbol Private _counter As Integer = 0 Private ReadOnly _evalStack As ArrayBuilder(Of (expression As BoundExpression, context As ExprContext)) Private ReadOnly _debugFriendly As Boolean Private _context As ExprContext = ExprContext.None Private _assignmentLocal As BoundLocal = Nothing Private ReadOnly _locals As New Dictionary(Of LocalSymbol, LocalDefUseInfo) ''' <summary> ''' fake local that represents the eval stack. when we need to ensure that eval ''' stack is not blocked by stack Locals, we record an access to empty. ''' </summary> Private ReadOnly _empty As DummyLocal ' we need to guarantee same stack patterns at branches and labels. we do that by placing ' a fake dummy local at one end of a branch and force that it is accessible at another. ' if any stack local tries to intervene and misbalance the stack, it will clash with ' the dummy and will be rejected. Private ReadOnly _dummyVariables As New Dictionary(Of Object, DummyLocal) Private _recursionDepth As Integer Private Sub New(container As Symbol, evalStack As ArrayBuilder(Of ValueTuple(Of BoundExpression, ExprContext)), debugFriendly As Boolean) Me._container = container Me._evalStack = evalStack Me._debugFriendly = debugFriendly Me._empty = New DummyLocal(container) ' this is the top of eval stack DeclareLocal(_empty, 0) RecordDummyWrite(_empty) End Sub Public Shared Function Analyze( container As Symbol, node As BoundNode, debugFriendly As Boolean, <Out> ByRef locals As Dictionary(Of LocalSymbol, LocalDefUseInfo)) As BoundNode Dim evalStack = ArrayBuilder(Of ValueTuple(Of BoundExpression, ExprContext)).GetInstance() Dim analyzer = New Analyzer(container, evalStack, debugFriendly) Dim rewritten As BoundNode = analyzer.Visit(node) evalStack.Free() locals = analyzer._locals Return rewritten End Function Public Overrides Function Visit(node As BoundNode) As BoundNode Dim result As BoundNode Dim expr = TryCast(node, BoundExpression) If expr IsNot Nothing Then Debug.Assert(expr.Kind <> BoundKind.Label) result = VisitExpression(expr, ExprContext.Value) Else result = VisitStatement(node) End If Return result End Function Private Function VisitExpressionCore(node As BoundExpression, context As ExprContext) As BoundExpression If node Is Nothing Then Me._counter += 1 Return node End If Dim prevContext As ExprContext = Me._context Dim prevStack As Integer = Me.StackDepth() Me._context = context ' Don not recurse into constant expressions. Their children do Not push any values. Dim result = If(node.ConstantValueOpt Is Nothing, DirectCast(MyBase.Visit(node), BoundExpression), node) _context = prevContext _counter += 1 Select Case context Case ExprContext.Sideeffects SetStackDepth(prevStack) Case ExprContext.AssignmentTarget Exit Select Case ExprContext.Value, ExprContext.Address, ExprContext.Box SetStackDepth(prevStack) PushEvalStack(node, context) Case Else Throw ExceptionUtilities.UnexpectedValue(context) End Select Return result End Function Private Sub PushEvalStack(result As BoundExpression, context As ExprContext) Debug.Assert(result IsNot Nothing OrElse context = ExprContext.None) _evalStack.Add((result, context)) End Sub Private Function StackDepth() As Integer Return _evalStack.Count End Function Private Function EvalStackIsEmpty() As Boolean Return StackDepth() = 0 End Function Private Sub SetStackDepth(depth As Integer) _evalStack.Clip(depth) End Sub Private Sub PopEvalStack() SetStackDepth(_evalStack.Count - 1) End Sub Private Sub ClearEvalStack() _evalStack.Clear() End Sub Private Function VisitExpression(node As BoundExpression, context As ExprContext) As BoundExpression Dim result As BoundExpression _recursionDepth += 1 If _recursionDepth > 1 Then StackGuard.EnsureSufficientExecutionStack(_recursionDepth) result = VisitExpressionCore(node, context) Else result = VisitExpressionCoreWithStackGuard(node, context) End If _recursionDepth -= 1 Return result End Function Private Function VisitExpressionCoreWithStackGuard(node As BoundExpression, context As ExprContext) As BoundExpression Debug.Assert(_recursionDepth = 1) Try Dim result = VisitExpressionCore(node, context) Debug.Assert(_recursionDepth = 1) Return result Catch ex As InsufficientExecutionStackException Throw New CancelledByStackGuardException(ex, node) End Try End Function Protected Overrides Function VisitExpressionWithoutStackGuard(node As BoundExpression) As BoundExpression Throw ExceptionUtilities.Unreachable End Function Public Overrides Function VisitSpillSequence(node As BoundSpillSequence) As BoundNode Throw ExceptionUtilities.Unreachable End Function Private Function VisitStatement(node As BoundNode) As BoundNode Debug.Assert(node Is Nothing OrElse EvalStackIsEmpty()) Dim origStack = StackDepth() Dim prevContext As ExprContext = Me._context Dim result As BoundNode = MyBase.Visit(node) ' prevent cross-statement local optimizations ' when emitting debug-friendly code. If _debugFriendly Then EnsureOnlyEvalStack() End If Me._context = prevContext SetStackDepth(origStack) _counter += 1 Return result End Function ''' <summary> ''' here we have a case of indirect assignment: *t1 = expr; ''' normally we would need to push t1 and that will cause spilling of t2 ''' ''' TODO: an interesting case arises in unused x[i]++ and ++x[i] : ''' we have trees that look like: ''' ''' t1 = &amp;(x[0]) ''' t2 = *t1 ''' *t1 = t2 + 1 ''' ''' t1 = &amp;(x[0]) ''' t2 = *t1 + 1 ''' *t1 = t2 ''' ''' in these cases, we could keep t2 on stack (dev10 does). ''' we are dealing with exactly 2 locals and access them in strict order ''' t1, t2, t1, t2 and we are not using t2 after that. ''' We may consider detecting exactly these cases and pretend that we do not need ''' to push either t1 or t2 in this case. ''' </summary> Private Function LhsUsesStackWhenAssignedTo(node As BoundNode, context As ExprContext) As Boolean Debug.Assert(context = ExprContext.AssignmentTarget) If node Is Nothing Then Return Nothing End If Select Case node.Kind Case BoundKind.Local, BoundKind.Parameter Return False Case BoundKind.FieldAccess Return Not DirectCast(node, BoundFieldAccess).FieldSymbol.IsShared Case BoundKind.Sequence Return LhsUsesStackWhenAssignedTo(DirectCast(node, BoundSequence).ValueOpt, context) End Select Return True End Function Public Overrides Function VisitBlock(node As BoundBlock) As BoundNode Debug.Assert(EvalStackIsEmpty(), "entering blocks when evaluation stack is not empty?") ' normally we would not allow stack locals ' when evaluation stack is not empty. DeclareLocals(node.Locals, 0) Return MyBase.VisitBlock(node) End Function Public Overrides Function VisitSequence(node As BoundSequence) As BoundNode ' Normally we can only use stack for local scheduling if stack is not used for evaluation. ' In a context of a regular block that simply means that eval stack must be empty. ' Sequences, can be entered on a nonempty evaluation stack ' Ex: ' a.b = Seq{var y, y = 1, y} // a is on the stack for the duration of the sequence. ' ' However evaluation stack at the entry cannot be used inside the sequence, so such stack ' works as effective "empty" for locals declared in sequence. ' Therefore sequence locals can be stack scheduled at same stack as at the entry to the sequence. ' it may seem attractive to relax the stack requirement to be: ' "all uses must agree on stack depth". ' The following example illustrates a case where x is safely used at "declarationStack + 1" ' Ex: ' Seq{var x; y.a = Seq{x = 1; x}; y} // x is used while y is on the eval stack ' ' It is, however not safe assumption in general since eval stack may be accessed between usages. ' Ex: ' Seq{var x; y.a = Seq{x = 1; x}; y.z = x; y} // x blocks access to y ' ' ' --------------------------------------------------- ' NOTE: The following is not implemented in VB ' ' There is one case where we want to tweak the "use at declaration stack" rule - in the case of ' compound assignment that involves ByRef operand captures (like: x[y]++ ) . ' ' Those cases produce specific sequences of the shapes: ' ' prefix: Seq{var temp, ref operand; operand initializers; *operand = Seq{temp = (T)(operand + 1); temp;} result: temp} ' postfix: Seq{var temp, ref operand; operand initializers; *operand = Seq{temp = operand; ; (T)(temp + 1);} result: temp} ' ' 1) temp is used as the result of the sequence (and that is the only reason why it is declared in the outer sequence). ' 2) all side-effects except the last one do not use the temp. ' 3) last side-effect is an indirect assignment of a sequence (and target does not involve the temp). ' ' Note that in a case of side-effects context, the result value will be ignored and therefore ' all usages of the nested temp will be confined to the nested sequence that is executed at +1 stack. ' ' We will detect such case and indicate +1 as the desired stack depth at local accesses. ' --------------------------------------------------- ' Dim declarationStack As Integer = Me.StackDepth() Dim locals = node.Locals If Not locals.IsEmpty Then If Me._context = ExprContext.Sideeffects Then DeclareLocals(locals, declarationStack) ' --------------------------------------------------- ' NOTE: not implemented workaround from above ' foreach (var local in locals) ' { ' if (IsNestedLocalOfCompoundOperator(local, node)) ' { ' // special case ' DeclareLocal(local, declarationStack + 1); ' } ' else ' { ' DeclareLocal(local, declarationStack); ' } ' } ' } ' --------------------------------------------------- Else DeclareLocals(locals, declarationStack) End If End If ' rewrite operands Dim origContext As ExprContext = Me._context Dim sideeffects As ImmutableArray(Of BoundExpression) = node.SideEffects Dim rewrittenSideeffects As ArrayBuilder(Of BoundExpression) = Nothing If Not sideeffects.IsDefault Then For i = 0 To sideeffects.Length - 1 Dim sideeffect As BoundExpression = sideeffects(i) Dim rewrittenSideeffect As BoundExpression = Me.VisitExpression(sideeffect, ExprContext.Sideeffects) If rewrittenSideeffects Is Nothing AndAlso rewrittenSideeffect IsNot sideeffect Then rewrittenSideeffects = ArrayBuilder(Of BoundExpression).GetInstance() rewrittenSideeffects.AddRange(sideeffects, i) End If If rewrittenSideeffects IsNot Nothing Then rewrittenSideeffects.Add(rewrittenSideeffect) End If Next End If Dim value As BoundExpression = Me.VisitExpression(node.ValueOpt, origContext) Return node.Update(node.Locals, If(rewrittenSideeffects IsNot Nothing, rewrittenSideeffects.ToImmutableAndFree(), sideeffects), value, node.Type) End Function #If False Then '// detect a pattern used in compound operators '// where a temp is declared in the outer sequence '// only because it must be returned, otherwise all uses are '// confined to the nested sequence that is indirectly assigned (and therefore has +1 stack) '// in such case the desired stack for this local is +1 'private bool IsNestedLocalOfCompoundOperator(LocalSymbol local, BoundSequence node) '{ ' var value = node.Value; ' // local must be used as the value of the sequence. ' if (value != null && value.Kind == BoundKind.Local && ((BoundLocal)value).LocalSymbol == local) ' { ' var sideeffects = node.SideEffects; ' var lastSideeffect = sideeffects.LastOrDefault(); ' if (lastSideeffect != null) ' { ' // last side-effect must be an indirect assignment of a sequence. ' if (lastSideeffect.Kind == BoundKind.AssignmentOperator) ' { ' var assignment = (BoundAssignmentOperator)lastSideeffect; ' if (IsIndirectAssignment(assignment) && ' assignment.Right.Kind == BoundKind.Sequence) ' { ' // and no other side-effects should use the variable ' var localUsedWalker = new LocalUsedWalker(local); ' for (int i = 0; i < sideeffects.Count - 1; i++) ' { ' if (localUsedWalker.IsLocalUsedIn(sideeffects[i])) ' { ' return false; ' } ' } ' // and local is not used on the left of the assignment ' // (extra check, but better be safe) ' if (localUsedWalker.IsLocalUsedIn(assignment.Left)) ' { ' return false; ' } ' // it should be used somewhere ' Debug.Assert(localUsedWalker.IsLocalUsedIn(assignment.Right), "who assigns the temp?"); ' return true; ' } ' } ' } ' } ' return false; '} 'private class LocalUsedWalker : BoundTreeWalker '{ ' private readonly LocalSymbol local; ' private bool found; ' internal LocalUsedWalker(LocalSymbol local) ' { ' this.local = local; ' } ' public bool IsLocalUsedIn(BoundExpression node) ' { ' this.found = false; ' this.Visit(node); ' return found; ' } ' public override BoundNode Visit(BoundNode node) ' { ' if (!found) ' { ' return base.Visit(node); ' } ' return null; ' } ' public override BoundNode VisitLocal(BoundLocal node) ' { ' if (node.LocalSymbol == local) ' { ' this.found = true; ' } ' return null; ' } '} #End If Public Overrides Function VisitExpressionStatement(node As BoundExpressionStatement) As BoundNode Return node.Update(Me.VisitExpression(node.Expression, ExprContext.Sideeffects)) End Function Public Overrides Function VisitLocal(node As BoundLocal) As BoundNode If node.ConstantValueOpt Is Nothing Then Select Case Me._context Case ExprContext.Address If node.LocalSymbol.IsByRef Then RecordVarRead(node.LocalSymbol) Else RecordVarRef(node.LocalSymbol) End If Case ExprContext.AssignmentTarget Debug.Assert(Me._assignmentLocal Is Nothing) ' actual assignment will happen later, after Right is evaluated ' just remember what we are assigning to. Me._assignmentLocal = node Case ExprContext.Sideeffects ' do nothing Case ExprContext.Value, ExprContext.Box RecordVarRead(node.LocalSymbol) End Select End If Return MyBase.VisitLocal(node) End Function Public Overrides Function VisitReferenceAssignment(node As BoundReferenceAssignment) As BoundNode ' Visit a local in context of regular assignment Dim left = DirectCast(VisitExpression(node.ByRefLocal, ExprContext.AssignmentTarget), BoundLocal) Dim storedAssignmentLocal = Me._assignmentLocal Me._assignmentLocal = Nothing ' Visit a l-value expression in context of 'address' Dim right As BoundExpression = VisitExpression(node.LValue, ExprContext.Address) ' record the Write to the local Debug.Assert(storedAssignmentLocal IsNot Nothing) ' this assert will fire if code relies on implicit CLR coercions ' - i.e assigns int value to a short local. ' in that case we should force lhs to be a real local Debug.Assert(node.ByRefLocal.Type.IsSameTypeIgnoringAll(node.LValue.Type), "cannot use stack when assignment involves implicit coercion of the value") RecordVarWrite(storedAssignmentLocal.LocalSymbol) Return node.Update(left, right, node.IsLValue, node.Type) End Function Public Overrides Function VisitAssignmentOperator(node As BoundAssignmentOperator) As BoundNode Dim isIndirect As Boolean = IsIndirectAssignment(node) Dim left As BoundExpression = VisitExpression(node.Left, If(isIndirect, ExprContext.Address, ExprContext.AssignmentTarget)) ' must delay recording a write until after RHS is evaluated Dim storedAssignmentLocal = Me._assignmentLocal Me._assignmentLocal = Nothing Debug.Assert(Me._context <> ExprContext.AssignmentTarget, "assignment expression cannot be a target of another assignment") ' Left on the right should be Nothing by this time Debug.Assert(node.LeftOnTheRightOpt Is Nothing) ' Do not visit "Left on the right" 'Me.counter += 1 Dim rhsContext As ExprContext If Me._context = ExprContext.Address Then ' we need the address of rhs so we cannot have it on the stack. rhsContext = ExprContext.Address Else Debug.Assert(Me._context = ExprContext.Value OrElse Me._context = ExprContext.Box OrElse Me._context = ExprContext.Sideeffects, "assignment expression cannot be a target of another assignment") ' we only need a value of rhs, so if otherwise possible it can be a stack value. rhsContext = ExprContext.Value End If Dim right As BoundExpression = node.Right ' if right is a struct ctor, it may be optimized into in-place call ' Such call will push the receiver ref before the arguments ' so we need to ensure that arguments cannot use stack temps Dim leftType As TypeSymbol = left.Type Dim mayPushReceiver As Boolean = False If right.Kind = BoundKind.ObjectCreationExpression Then Dim ctor = DirectCast(right, BoundObjectCreationExpression).ConstructorOpt If ctor IsNot Nothing AndAlso ctor.ParameterCount <> 0 Then mayPushReceiver = True End If End If If mayPushReceiver Then 'push unknown value just to prevent access to stack locals. PushEvalStack(Nothing, ExprContext.None) End If right = VisitExpression(node.Right, rhsContext) If mayPushReceiver Then PopEvalStack() End If ' if assigning to a local, now it is the time to record the Write If storedAssignmentLocal IsNot Nothing Then ' this assert will fire if code relies on implicit CLR coercions ' - i.e assigns int value to a short local. ' in that case we should force lhs to be a real local Debug.Assert(node.Left.Type.IsSameTypeIgnoringAll(node.Right.Type), "cannot use stack when assignment involves implicit coercion of the value") Debug.Assert(Not isIndirect, "indirect assignment is a read, not a write") RecordVarWrite(storedAssignmentLocal.LocalSymbol) End If Return node.Update(left, Nothing, right, node.SuppressObjectClone, node.Type) End Function ''' <summary> ''' VB uses a special node to assign references. ''' BoundAssignment is used only to assign values. ''' therefore an indirect assignment may only happen if lhs is a reference ''' </summary> Private Shared Function IsIndirectAssignment(node As BoundAssignmentOperator) As Boolean Return IsByRefVariable(node.Left) End Function Private Shared Function IsByRefVariable(node As BoundExpression) As Boolean Select Case node.Kind Case BoundKind.Parameter Return DirectCast(node, BoundParameter).ParameterSymbol.IsByRef Case BoundKind.Local Return DirectCast(node, BoundLocal).LocalSymbol.IsByRef Case BoundKind.Call Return DirectCast(node, BoundCall).Method.ReturnsByRef Case BoundKind.Sequence Debug.Assert(Not IsByRefVariable(DirectCast(node, BoundSequence).ValueOpt)) Return False Case BoundKind.PseudoVariable Return True Case BoundKind.ReferenceAssignment Return True Case BoundKind.ValueTypeMeReference Return True Case BoundKind.ModuleVersionId, BoundKind.InstrumentationPayloadRoot ' same as static fields Return False Case BoundKind.FieldAccess, BoundKind.ArrayAccess ' fields are never byref Return False Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select End Function Private Shared Function IsVerifierRef(type As TypeSymbol) As Boolean Return Not type.TypeKind = TypeKind.TypeParameter AndAlso type.IsReferenceType End Function Private Shared Function IsVerifierVal(type As TypeSymbol) As Boolean Return Not type.TypeKind = TypeKind.TypeParameter AndAlso type.IsValueType End Function Public Overrides Function VisitCall(node As BoundCall) As BoundNode Dim receiver = node.ReceiverOpt ' matches or a bit stronger than EmitReceiverRef ' if there are any doubts that receiver is a ref type, ' assume we will need an address (that will prevent scheduling of receiver). If Not node.Method.IsShared Then Dim receiverType = receiver.Type Dim context As ExprContext If receiverType.IsReferenceType Then If (receiverType.IsTypeParameter()) Then ' type param receiver that we statically know Is a reference will be boxed context = ExprContext.Box Else ' reference receivers will be used as values context = ExprContext.Value End If Else ' everything else will get an address taken context = ExprContext.Address End If receiver = VisitExpression(receiver, context) Else Me._counter += 1 Debug.Assert(receiver Is Nothing OrElse receiver.Kind = BoundKind.TypeExpression) End If Dim method As MethodSymbol = node.Method Dim rewrittenArguments As ImmutableArray(Of BoundExpression) = VisitArguments(node.Arguments, method.Parameters) Debug.Assert(node.MethodGroupOpt Is Nothing) Return node.Update( method, node.MethodGroupOpt, receiver, rewrittenArguments, node.DefaultArguments, node.ConstantValueOpt, isLValue:=node.IsLValue, suppressObjectClone:=node.SuppressObjectClone, type:=node.Type) End Function Private Function VisitArguments(arguments As ImmutableArray(Of BoundExpression), parameters As ImmutableArray(Of ParameterSymbol)) As ImmutableArray(Of BoundExpression) Debug.Assert(Not arguments.IsDefault) Debug.Assert(Not parameters.IsDefault) ' If this is a varargs method then there will be one additional argument for the __arglist(). Debug.Assert(arguments.Length = parameters.Length OrElse arguments.Length = parameters.Length + 1) Dim rewrittenArguments As ArrayBuilder(Of BoundExpression) = Nothing For i = 0 To arguments.Length - 1 ' Treat the __arglist() as a value parameter. Dim context As ExprContext = If(i = parameters.Length OrElse Not parameters(i).IsByRef, ExprContext.Value, ExprContext.Address) Dim arg As BoundExpression = arguments(i) Dim rewrittenArg As BoundExpression = VisitExpression(arg, context) If rewrittenArguments Is Nothing AndAlso arg IsNot rewrittenArg Then rewrittenArguments = ArrayBuilder(Of BoundExpression).GetInstance() rewrittenArguments.AddRange(arguments, i) End If If rewrittenArguments IsNot Nothing Then rewrittenArguments.Add(rewrittenArg) End If Next Return If(rewrittenArguments IsNot Nothing, rewrittenArguments.ToImmutableAndFree, arguments) End Function Public Overrides Function VisitObjectCreationExpression(node As BoundObjectCreationExpression) As BoundNode Dim constructor As MethodSymbol = node.ConstructorOpt Debug.Assert(constructor IsNot Nothing OrElse node.Arguments.Length = 0) Dim rewrittenArguments As ImmutableArray(Of BoundExpression) = If(constructor Is Nothing, node.Arguments, VisitArguments(node.Arguments, constructor.Parameters)) Debug.Assert(node.InitializerOpt Is Nothing) Me._counter += 1 Return node.Update(constructor, rewrittenArguments, node.DefaultArguments, Nothing, node.Type) End Function Public Overrides Function VisitArrayAccess(node As BoundArrayAccess) As BoundNode ' regardless of purpose, array access visits its children as values ' TODO: do we need to save/restore old context here? Dim oldContext = Me._context Me._context = ExprContext.Value Dim result As BoundNode = MyBase.VisitArrayAccess(node) Me._context = oldContext Return result End Function Public Overrides Function VisitFieldAccess(node As BoundFieldAccess) As BoundNode Dim field As FieldSymbol = node.FieldSymbol Dim receiver As BoundExpression = node.ReceiverOpt ' if there are any doubts that receiver is a ref type, assume we will ' need an address. (that will prevent scheduling of receiver). If Not field.IsShared Then If receiver.Type.IsTypeParameter Then ' type parameters must be boxed to access fields. receiver = VisitExpression(receiver, ExprContext.Box) Else ' need address when assigning to a field and receiver is not a reference ' when accessing a field of a struct unless we only need Value and Value is preferred. If receiver.Type.IsValueType AndAlso (_context = ExprContext.AssignmentTarget OrElse _context = ExprContext.Address OrElse CodeGenerator.FieldLoadMustUseRef(receiver)) Then receiver = VisitExpression(receiver, ExprContext.Address) Else receiver = VisitExpression(receiver, ExprContext.Value) End If End If Else Me._counter += 1 receiver = Nothing End If Return node.Update(receiver, field, node.IsLValue, node.SuppressVirtualCalls, constantsInProgressOpt:=Nothing, node.Type) End Function Public Overrides Function VisitLabelStatement(node As BoundLabelStatement) As BoundNode RecordLabel(node.Label) Return MyBase.VisitLabelStatement(node) End Function Public Overrides Function VisitGotoStatement(node As BoundGotoStatement) As BoundNode Dim result As BoundNode = MyBase.VisitGotoStatement(node) RecordBranch(node.Label) Return result End Function Public Overrides Function VisitConditionalGoto(node As BoundConditionalGoto) As BoundNode Dim result As BoundNode = MyBase.VisitConditionalGoto(node) Me.PopEvalStack() ' condition gets consumed RecordBranch(node.Label) Return result End Function Public Overrides Function VisitBinaryConditionalExpression(node As BoundBinaryConditionalExpression) As BoundNode Dim origStack = Me.StackDepth Dim testExpression As BoundExpression = DirectCast(Me.Visit(node.TestExpression), BoundExpression) Debug.Assert(node.ConvertedTestExpression Is Nothing) ' Me.counter += 1 '' This child is not visited Debug.Assert(node.TestExpressionPlaceholder Is Nothing) ' Me.counter += 1 '' This child is not visited ' implicit branch here Dim cookie As Object = GetStackStateCookie() Me.SetStackDepth(origStack) ' else expression is evaluated with original stack Dim elseExpression As BoundExpression = DirectCast(Me.Visit(node.ElseExpression), BoundExpression) ' implicit label here EnsureStackState(cookie) Return node.Update(testExpression, Nothing, Nothing, elseExpression, node.ConstantValueOpt, node.Type) End Function Public Overrides Function VisitTernaryConditionalExpression(node As BoundTernaryConditionalExpression) As BoundNode Dim origStack As Integer = Me.StackDepth Dim condition = DirectCast(Me.Visit(node.Condition), BoundExpression) Dim cookie As Object = GetStackStateCookie() ' implicit goto here Me.SetStackDepth(origStack) ' consequence is evaluated with original stack Dim whenTrue = DirectCast(Me.Visit(node.WhenTrue), BoundExpression) EnsureStackState(cookie) ' implicit label here Me.SetStackDepth(origStack) ' alternative is evaluated with original stack Dim whenFalse = DirectCast(Me.Visit(node.WhenFalse), BoundExpression) EnsureStackState(cookie) ' implicit label here Return node.Update(condition, whenTrue, whenFalse, node.ConstantValueOpt, node.Type) End Function Public Overrides Function VisitLoweredConditionalAccess(node As BoundLoweredConditionalAccess) As BoundNode If Not node.ReceiverOrCondition.Type.IsBooleanType() Then ' We may need to load a reference to the receiver, or may need to ' reload it after the null check. This won't work well ' with a stack local. EnsureOnlyEvalStack() End If Dim origStack = StackDepth() Dim receiverOrCondition = DirectCast(Me.Visit(node.ReceiverOrCondition), BoundExpression) Dim cookie = GetStackStateCookie() ' implicit branch here ' access Is evaluated with original stack ' (this Is Not entirely true, codegen will keep receiver on the stack, but that Is irrelevant here) Me.SetStackDepth(origStack) Dim whenNotNull = DirectCast(Me.Visit(node.WhenNotNull), BoundExpression) EnsureStackState(cookie) ' implicit label here Dim whenNull As BoundExpression = Nothing If node.WhenNullOpt IsNot Nothing Then Me.SetStackDepth(origStack) whenNull = DirectCast(Me.Visit(node.WhenNullOpt), BoundExpression) EnsureStackState(cookie) ' implicit label here End If Return node.Update(receiverOrCondition, node.CaptureReceiver, node.PlaceholderId, whenNotNull, whenNull, node.Type) End Function Public Overrides Function VisitConditionalAccessReceiverPlaceholder(node As BoundConditionalAccessReceiverPlaceholder) As BoundNode Return MyBase.VisitConditionalAccessReceiverPlaceholder(node) End Function Public Overrides Function VisitComplexConditionalAccessReceiver(node As BoundComplexConditionalAccessReceiver) As BoundNode EnsureOnlyEvalStack() Dim origStack As Integer = Me.StackDepth Me.PushEvalStack(Nothing, ExprContext.None) Dim cookie As Object = GetStackStateCookie() ' implicit goto here Me.SetStackDepth(origStack) ' consequence is evaluated with original stack Dim valueTypeReceiver = DirectCast(Me.Visit(node.ValueTypeReceiver), BoundExpression) EnsureStackState(cookie) ' implicit label here Me.SetStackDepth(origStack) ' alternative is evaluated with original stack Dim referenceTypeReceiver = DirectCast(Me.Visit(node.ReferenceTypeReceiver), BoundExpression) EnsureStackState(cookie) ' implicit label here Return node.Update(valueTypeReceiver, referenceTypeReceiver, node.Type) End Function Public Overrides Function VisitBinaryOperator(node As BoundBinaryOperator) As BoundNode ' Do not blow the stack due to a deep recursion on the left. Dim child As BoundExpression = node.Left If child.Kind <> BoundKind.BinaryOperator OrElse child.ConstantValueOpt IsNot Nothing Then Return VisitBinaryOperatorSimple(node) End If Dim stack = ArrayBuilder(Of BoundBinaryOperator).GetInstance() stack.Push(node) Dim binary As BoundBinaryOperator = DirectCast(child, BoundBinaryOperator) Do stack.Push(binary) child = binary.Left If child.Kind <> BoundKind.BinaryOperator OrElse child.ConstantValueOpt IsNot Nothing Then Exit Do End If binary = DirectCast(child, BoundBinaryOperator) Loop Dim prevStack As Integer = Me.StackDepth() Dim left = DirectCast(Me.Visit(child), BoundExpression) Do binary = stack.Pop() ' Short-circuit operators need to emulate implicit branch/label Dim isLogical As Boolean Dim cookie As Object = Nothing Select Case (binary.OperatorKind And BinaryOperatorKind.OpMask) Case BinaryOperatorKind.AndAlso, BinaryOperatorKind.OrElse isLogical = True ' implicit branch here cookie = GetStackStateCookie() Me.SetStackDepth(prevStack) ' right is evaluated with original stack Case Else isLogical = False End Select Dim right = DirectCast(Me.Visit(binary.Right), BoundExpression) If isLogical Then ' implicit label here EnsureStackState(cookie) End If Dim type As TypeSymbol = Me.VisitType(binary.Type) left = binary.Update(binary.OperatorKind, left, right, binary.Checked, binary.ConstantValueOpt, type) If stack.Count = 0 Then Exit Do End If _counter += 1 SetStackDepth(prevStack) PushEvalStack(node, ExprContext.Value) Loop Debug.Assert(binary Is node) stack.Free() Return left End Function Private Function VisitBinaryOperatorSimple(node As BoundBinaryOperator) As BoundNode Select Case (node.OperatorKind And BinaryOperatorKind.OpMask) Case BinaryOperatorKind.AndAlso, BinaryOperatorKind.OrElse ' Short-circuit operators need to emulate implicit branch/label Dim origStack = Me.StackDepth Dim left As BoundExpression = DirectCast(Me.Visit(node.Left), BoundExpression) ' implicit branch here Dim cookie As Object = GetStackStateCookie() Me.SetStackDepth(origStack) ' right is evaluated with original stack Dim right As BoundExpression = DirectCast(Me.Visit(node.Right), BoundExpression) ' implicit label here EnsureStackState(cookie) Return node.Update(node.OperatorKind, left, right, node.Checked, node.ConstantValueOpt, node.Type) Case Else Return MyBase.VisitBinaryOperator(node) End Select End Function Public Overrides Function VisitUnaryOperator(node As BoundUnaryOperator) As BoundNode ' checked(-x) is emitted as "0 - x" If node.Checked AndAlso (node.OperatorKind And UnaryOperatorKind.OpMask) = UnaryOperatorKind.Minus Then Dim storedStack = Me.StackDepth Me.PushEvalStack(Nothing, ExprContext.None) Dim operand = DirectCast(Me.Visit(node.Operand), BoundExpression) Me.SetStackDepth(storedStack) Return node.Update(node.OperatorKind, operand, node.Checked, node.ConstantValueOpt, node.Type) Else Return MyBase.VisitUnaryOperator(node) End If End Function Public Overrides Function VisitSelectStatement(node As BoundSelectStatement) As BoundNode ' switch requires that key local stays local EnsureOnlyEvalStack() Dim expressionStatement As BoundExpressionStatement = DirectCast(Me.Visit(node.ExpressionStatement), BoundExpressionStatement) If expressionStatement.Expression.Kind = BoundKind.Local Then ' It is required by code gen that if node.ExpressionStatement ' is a local it should not be optimized out Dim local = DirectCast(expressionStatement.Expression, BoundLocal).LocalSymbol ShouldNotSchedule(local) End If Dim origStack = Me.StackDepth EnsureOnlyEvalStack() Dim exprPlaceholderOpt As BoundRValuePlaceholder = DirectCast(Me.Visit(node.ExprPlaceholderOpt), BoundRValuePlaceholder) ' expression value is consumed by the switch Me.SetStackDepth(origStack) EnsureOnlyEvalStack() ' case blocks Dim caseBlocks As ImmutableArray(Of BoundCaseBlock) = Me.VisitList(node.CaseBlocks) ' exit label Dim exitLabel = node.ExitLabel If exitLabel IsNot Nothing Then Me.RecordLabel(exitLabel) End If EnsureOnlyEvalStack() Return node.Update(expressionStatement, exprPlaceholderOpt, caseBlocks, node.RecommendSwitchTable, exitLabel) End Function Public Overrides Function VisitCaseBlock(node As BoundCaseBlock) As BoundNode EnsureOnlyEvalStack() Dim caseStatement As BoundCaseStatement = DirectCast(Me.Visit(node.CaseStatement), BoundCaseStatement) EnsureOnlyEvalStack() Dim body As BoundBlock = DirectCast(Me.Visit(node.Body), BoundBlock) EnsureOnlyEvalStack() Return node.Update(caseStatement, body) End Function Public Overrides Function VisitUnstructuredExceptionOnErrorSwitch(node As BoundUnstructuredExceptionOnErrorSwitch) As BoundNode Dim value = DirectCast(Visit(node.Value), BoundExpression) Me.PopEvalStack() ' value gets consumed Return node.Update(value, Me.VisitList(node.Jumps)) End Function Public Overrides Function VisitUnstructuredExceptionResumeSwitch(node As BoundUnstructuredExceptionResumeSwitch) As BoundNode Dim resumeLabel = DirectCast(Visit(node.ResumeLabel), BoundLabelStatement) Dim resumeNextLabel = DirectCast(Visit(node.ResumeNextLabel), BoundLabelStatement) Dim resumeTargetTemporary = DirectCast(Visit(node.ResumeTargetTemporary), BoundLocal) Me.PopEvalStack() ' value gets consumed Return node.Update(resumeTargetTemporary, resumeLabel, resumeNextLabel, node.Jumps) End Function Public Overrides Function VisitTryStatement(node As BoundTryStatement) As BoundNode EnsureOnlyEvalStack() Dim tryBlock = DirectCast(Me.Visit(node.TryBlock), BoundBlock) EnsureOnlyEvalStack() Dim catchBlocks As ImmutableArray(Of BoundCatchBlock) = Me.VisitList(node.CatchBlocks) EnsureOnlyEvalStack() Dim finallyBlock = DirectCast(Me.Visit(node.FinallyBlockOpt), BoundBlock) EnsureOnlyEvalStack() If node.ExitLabelOpt IsNot Nothing Then RecordLabel(node.ExitLabelOpt) End If EnsureOnlyEvalStack() Return node.Update(tryBlock, catchBlocks, finallyBlock, node.ExitLabelOpt) End Function Public Overrides Function VisitCatchBlock(node As BoundCatchBlock) As BoundNode Dim origStack As Integer = Me.StackDepth DeclareLocal(node.LocalOpt, origStack) EnsureOnlyEvalStack() Dim exceptionVariableOpt As BoundExpression = Me.VisitExpression(node.ExceptionSourceOpt, ExprContext.Value) Me.SetStackDepth(origStack) EnsureOnlyEvalStack() Dim errorLineNumberOpt As BoundExpression = Me.VisitExpression(node.ErrorLineNumberOpt, ExprContext.Value) Me.SetStackDepth(origStack) EnsureOnlyEvalStack() Dim exceptionFilterOpt As BoundExpression = Me.VisitExpression(node.ExceptionFilterOpt, ExprContext.Value) Me.SetStackDepth(origStack) EnsureOnlyEvalStack() Dim body As BoundBlock = DirectCast(Me.Visit(node.Body), BoundBlock) EnsureOnlyEvalStack() Return node.Update(node.LocalOpt, exceptionVariableOpt, errorLineNumberOpt, exceptionFilterOpt, body, node.IsSynthesizedAsyncCatchAll) End Function Public Overrides Function VisitArrayInitialization(node As BoundArrayInitialization) As BoundNode ' nontrivial construct - may use dups, metadata blob helpers etc.. EnsureOnlyEvalStack() Dim initializers As ImmutableArray(Of BoundExpression) = node.Initializers Dim rewrittenInitializers As ArrayBuilder(Of BoundExpression) = Nothing If Not initializers.IsDefault Then For i = 0 To initializers.Length - 1 ' array itself will be pushed on the stack here. EnsureOnlyEvalStack() Dim initializer As BoundExpression = initializers(i) Dim rewrittenInitializer As BoundExpression = Me.VisitExpression(initializer, ExprContext.Value) If rewrittenInitializers Is Nothing AndAlso rewrittenInitializer IsNot initializer Then rewrittenInitializers = ArrayBuilder(Of BoundExpression).GetInstance() rewrittenInitializers.AddRange(initializers, i) End If If rewrittenInitializers IsNot Nothing Then rewrittenInitializers.Add(rewrittenInitializer) End If Next End If Return node.Update(If(rewrittenInitializers IsNot Nothing, rewrittenInitializers.ToImmutableAndFree(), initializers), node.Type) End Function Public Overrides Function VisitReturnStatement(node As BoundReturnStatement) As BoundNode Dim expressionOpt = TryCast(Me.Visit(node.ExpressionOpt), BoundExpression) ' must not have locals on stack when returning EnsureOnlyEvalStack() Return node.Update(expressionOpt, node.FunctionLocalOpt, node.ExitLabelOpt) End Function ''' <summary> ''' Ensures that there are no stack locals. It is done by accessing ''' virtual "empty" local that is at the bottom of all stack locals. ''' </summary> ''' <remarks></remarks> Private Sub EnsureOnlyEvalStack() RecordVarRead(_empty) End Sub Private Function GetStackStateCookie() As Object ' create a dummy and start tracing it Dim dummy As New DummyLocal(Me._container) Me._dummyVariables.Add(dummy, dummy) Me._locals.Add(dummy, New LocalDefUseInfo(Me.StackDepth)) RecordDummyWrite(dummy) Return dummy End Function Private Sub EnsureStackState(cookie As Object) RecordVarRead(Me._dummyVariables(cookie)) End Sub ' called on branches and labels Private Sub RecordBranch(label As LabelSymbol) Dim dummy As DummyLocal = Nothing If Me._dummyVariables.TryGetValue(label, dummy) Then RecordVarRead(dummy) Else ' create a dummy and start tracing it dummy = New DummyLocal(Me._container) Me._dummyVariables.Add(label, dummy) Me._locals.Add(dummy, New LocalDefUseInfo(Me.StackDepth)) RecordDummyWrite(dummy) End If End Sub Private Sub RecordLabel(label As LabelSymbol) Dim dummy As DummyLocal = Nothing If Me._dummyVariables.TryGetValue(label, dummy) Then RecordVarRead(dummy) Else ' this is a backwards jump with nontrivial stack requirements ' just use empty. dummy = _empty Me._dummyVariables.Add(label, dummy) RecordVarRead(dummy) End If End Sub Private Sub RecordVarRef(local As LocalSymbol) Debug.Assert(Not local.IsByRef, "can't tke a ref of a ref") If Not CanScheduleToStack(local) Then Return End If ' if we ever take a reference of a local, it must be a real local. ShouldNotSchedule(local) End Sub Private Sub RecordVarRead(local As LocalSymbol) If Not CanScheduleToStack(local) Then Return End If Dim locInfo As LocalDefUseInfo = _locals(local) If locInfo.CannotSchedule Then Return End If If locInfo.localDefs.Count = 0 Then ' reading before writing. locInfo.ShouldNotSchedule() Return End If ' if accessing real val, check stack If Not TypeOf local Is DummyLocal Then If locInfo.StackAtDeclaration <> StackDepth() AndAlso Not EvalStackHasLocal(local) Then ' reading at different eval stack. locInfo.ShouldNotSchedule() Return End If Else ' dummy must be accessed on same stack. Debug.Assert(local Is _empty OrElse locInfo.StackAtDeclaration = StackDepth()) End If Dim definedAt As LocalDefUseSpan = locInfo.localDefs.Last() definedAt.SetEnd(Me._counter) Dim locDef As New LocalDefUseSpan(_counter) locInfo.localDefs.Add(locDef) End Sub Private Function EvalStackHasLocal(local As LocalSymbol) As Boolean Dim top = _evalStack.Last() Return top.context = If(Not local.IsByRef, ExprContext.Value, ExprContext.Address) AndAlso top.expression.Kind = BoundKind.Local AndAlso DirectCast(top.expression, BoundLocal).LocalSymbol = local End Function Private Sub RecordVarWrite(local As LocalSymbol) Debug.Assert(local.SynthesizedKind <> SynthesizedLocalKind.OptimizerTemp) If Not CanScheduleToStack(local) Then Return End If Dim locInfo = _locals(local) If locInfo.CannotSchedule Then Return End If ' check stack ' -1 because real assignment "consumes" value. Dim evalStack = Me.StackDepth - 1 If locInfo.StackAtDeclaration <> evalStack Then ' writing at different eval stack. locInfo.ShouldNotSchedule() Return End If Dim locDef = New LocalDefUseSpan(Me._counter) locInfo.localDefs.Add(locDef) End Sub Private Sub RecordDummyWrite(local As LocalSymbol) Debug.Assert(local.SynthesizedKind = SynthesizedLocalKind.OptimizerTemp) Dim locInfo = _locals(local) ' dummy must be accessed on same stack. Debug.Assert(local Is _empty OrElse locInfo.StackAtDeclaration = StackDepth()) Dim locDef = New LocalDefUseSpan(Me._counter) locInfo.localDefs.Add(locDef) End Sub Private Sub ShouldNotSchedule(local As LocalSymbol) Dim localDefInfo As LocalDefUseInfo = Nothing If _locals.TryGetValue(local, localDefInfo) Then localDefInfo.ShouldNotSchedule() End If End Sub Private Function CanScheduleToStack(local As LocalSymbol) As Boolean Return local.CanScheduleToStack AndAlso (Not _debugFriendly OrElse Not local.SynthesizedKind.IsLongLived()) End Function Private Sub DeclareLocals(locals As ImmutableArray(Of LocalSymbol), stack As Integer) For Each local In locals DeclareLocal(local, stack) Next End Sub Private Sub DeclareLocal(local As LocalSymbol, stack As Integer) If local IsNot Nothing Then If CanScheduleToStack(local) Then Me._locals.Add(local, New LocalDefUseInfo(stack)) End If End If End Sub End Class End Class End Namespace
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Tools/IdeCoreBenchmarks/ProjectOperationBenchmarks.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using System.Text; using BenchmarkDotNet.Attributes; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace IdeCoreBenchmarks { public class ProjectOperationBenchmarks { private static readonly SourceText s_newText = SourceText.From("text"); [MemoryDiagnoser] public class IterateDocuments { private Workspace _workspace; private Project _emptyProject; private Project _hundredProject; private Project _thousandsProject; public IterateDocuments() { // These fields are initialized in GlobalSetup _workspace = null!; _emptyProject = null!; _hundredProject = null!; _thousandsProject = null!; } [Params(0, 100, 10000)] public int DocumentCount { get; set; } private Project Project { get { return DocumentCount switch { 0 => _emptyProject, 100 => _hundredProject, 10000 => _thousandsProject, _ => throw new NotSupportedException($"'{nameof(DocumentCount)}' is out of range"), }; } } [GlobalSetup] public void GlobalSetup() { _workspace = new AdhocWorkspace(); var solution = _workspace.CurrentSolution; _emptyProject = CreateProject(ref solution, name: "A", documentCount: 0); _hundredProject = CreateProject(ref solution, name: "A", documentCount: 100); _thousandsProject = CreateProject(ref solution, name: "A", documentCount: 10000); static Project CreateProject(ref Solution solution, string name, int documentCount) { var projectId = ProjectId.CreateNewId(name); solution = solution.AddProject(projectId, name, name, LanguageNames.CSharp); var emptySourceText = SourceText.From("", Encoding.UTF8); for (var i = 0; i < documentCount; i++) { var documentName = $"{i}.cs"; var documentId = DocumentId.CreateNewId(projectId, documentName); solution = solution.AddDocument(documentId, documentName, emptySourceText); } return solution.GetRequiredProject(projectId); } } [Benchmark(Description = "Project.DocumentIds")] public int DocumentIds() { var count = 0; foreach (var _ in Project.DocumentIds) { count++; } return count; } [Benchmark(Description = "Project.Documents")] public int Documents() { var count = 0; foreach (var _ in Project.Documents) { count++; } return count; } [Benchmark(Description = "Solution.WithDocumentText")] public void WithDocumentText() { var solution = Project.Solution; var documentId = Project.DocumentIds.FirstOrDefault(); if (documentId != null) { var _ = solution.WithDocumentText(documentId, s_newText); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using System.Text; using BenchmarkDotNet.Attributes; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace IdeCoreBenchmarks { public class ProjectOperationBenchmarks { private static readonly SourceText s_newText = SourceText.From("text"); [MemoryDiagnoser] public class IterateDocuments { private Workspace _workspace; private Project _emptyProject; private Project _hundredProject; private Project _thousandsProject; public IterateDocuments() { // These fields are initialized in GlobalSetup _workspace = null!; _emptyProject = null!; _hundredProject = null!; _thousandsProject = null!; } [Params(0, 100, 10000)] public int DocumentCount { get; set; } private Project Project { get { return DocumentCount switch { 0 => _emptyProject, 100 => _hundredProject, 10000 => _thousandsProject, _ => throw new NotSupportedException($"'{nameof(DocumentCount)}' is out of range"), }; } } [GlobalSetup] public void GlobalSetup() { _workspace = new AdhocWorkspace(); var solution = _workspace.CurrentSolution; _emptyProject = CreateProject(ref solution, name: "A", documentCount: 0); _hundredProject = CreateProject(ref solution, name: "A", documentCount: 100); _thousandsProject = CreateProject(ref solution, name: "A", documentCount: 10000); static Project CreateProject(ref Solution solution, string name, int documentCount) { var projectId = ProjectId.CreateNewId(name); solution = solution.AddProject(projectId, name, name, LanguageNames.CSharp); var emptySourceText = SourceText.From("", Encoding.UTF8); for (var i = 0; i < documentCount; i++) { var documentName = $"{i}.cs"; var documentId = DocumentId.CreateNewId(projectId, documentName); solution = solution.AddDocument(documentId, documentName, emptySourceText); } return solution.GetRequiredProject(projectId); } } [Benchmark(Description = "Project.DocumentIds")] public int DocumentIds() { var count = 0; foreach (var _ in Project.DocumentIds) { count++; } return count; } [Benchmark(Description = "Project.Documents")] public int Documents() { var count = 0; foreach (var _ in Project.Documents) { count++; } return count; } [Benchmark(Description = "Solution.WithDocumentText")] public void WithDocumentText() { var solution = Project.Solution; var documentId = Project.DocumentIds.FirstOrDefault(); if (documentId != null) { var _ = solution.WithDocumentText(documentId, s_newText); } } } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/IFormattingResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Formatting { /// <summary> /// Contains changes that can be either applied to different targets such as a buffer or a tree /// or examined to be used in other places such as quick fix. /// </summary> internal interface IFormattingResult { IList<TextChange> GetTextChanges(CancellationToken cancellationToken); SyntaxNode GetFormattedRoot(CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Formatting { /// <summary> /// Contains changes that can be either applied to different targets such as a buffer or a tree /// or examined to be used in other places such as quick fix. /// </summary> internal interface IFormattingResult { IList<TextChange> GetTextChanges(CancellationToken cancellationToken); SyntaxNode GetFormattedRoot(CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/EditorFeatures/VisualBasicTest/Formatting/CodeCleanUpTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.CodeCleanup Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Diagnostics.VisualBasic Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.MakeFieldReadonly Imports Microsoft.CodeAnalysis.Shared.Utilities Imports Microsoft.CodeAnalysis.SolutionCrawler Imports Microsoft.CodeAnalysis.VisualBasic.Diagnostics.Analyzers Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Formatting <UseExportProvider> Public Class CodeCleanUpTests ' Format Document tests are handled by Format Document Test ' TESTS NEEDED but not found in C# 'Apply object preference initialization preferences 'Apply file header preferences <Fact> <Trait(Traits.Feature, Traits.Features.CodeCleanup)> Public Function VisualBasicRemoveUnusedImports() As Task Dim code = "Imports System.Collections.Generic Imports System Friend Class Program Public Shared Sub Main(args() As String) Console.WriteLine(list.Count) End Sub End Class " Dim expected = "Friend Class Program Public Shared Sub Main(args() As String) Console.WriteLine(list.Count) End Sub End Class " Return AssertCodeCleanupResultAsync(expected, code) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeCleanup)> Public Function VisualBasicSortImports() As Task Dim code = "Imports System.Reflection Imports System.IO Friend Class Program Public Shared Sub Main(args() As String) Dim location As ImmutableArray(Of String) = Assembly.Load(""System.Windows.Forms"").Location Dim SourceText As String Using myFileStream As FileStream = File.OpenRead(location) SourceText = myFileStream.GetFileTextFromStream() End Using End Sub End Class " Dim expected = "Imports System.IO Imports System.Reflection Friend Class Program Public Shared Sub Main(args() As String) Dim location As ImmutableArray(Of String) = Assembly.Load(""System.Windows.Forms"").Location Dim SourceText As String Using myFileStream As FileStream = File.OpenRead(location) SourceText = myFileStream.GetFileTextFromStream() End Using End Sub End Class " Return AssertCodeCleanupResultAsync(expected, code) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeCleanup)> Public Function VisualBasicGroupUsings() As Task 'Apply imports directive placement preference Dim code As String = "Imports M Imports System.IO Friend NotInheritable Class Program Private Shared Sub Main(args As String()) Dim location As ImmutableArray(Of String) = Assembly.Load(""System.Windows.Forms"").Location Dim SourceText As String Using myFileStream As FileStream = File.OpenRead(location) SourceText = myFileStream.GetFileTextFromStream() End Using Dim tempVar As New Goo End Sub End Class Namespace M Public Class Goo End Class End Namespace " Dim expected As String = "Imports M Imports System.IO Friend NotInheritable Class Program Private Shared Sub Main(args As String()) Dim location As ImmutableArray(Of String) = Assembly.Load(""System.Windows.Forms"").Location Dim SourceText As String Using myFileStream As FileStream = File.OpenRead(location) SourceText = myFileStream.GetFileTextFromStream() End Using Dim tempVar As New Goo End Sub End Class Namespace M Public Class Goo End Class End Namespace " Return AssertCodeCleanupResultAsync(expected, code, systemImportsFirst:=False, separateImportsGroups:=True) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeCleanup)> Public Function VisualBasicSortAndGroupUsings() As Task 'Apply imports directive placement preference Dim code As String = "Imports M Imports System.IO Friend NotInheritable Class Program Private Shared Sub Main(args As String()) Dim location As ImmutableArray(Of String) = Assembly.Load(""System.Windows.Forms"").Location Dim SourceText As String Using myFileStream As FileStream = File.OpenRead(location) SourceText = myFileStream.GetFileTextFromStream() End Using Dim tempVar As New Goo End Sub End Class Namespace M Public Class Goo End Class End Namespace " Dim expected As String = "Imports System.IO Imports M Friend NotInheritable Class Program Private Shared Sub Main(args As String()) Dim location As ImmutableArray(Of String) = Assembly.Load(""System.Windows.Forms"").Location Dim SourceText As String Using myFileStream As FileStream = File.OpenRead(location) SourceText = myFileStream.GetFileTextFromStream() End Using Dim tempVar As New Goo End Sub End Class Namespace M Public Class Goo End Class End Namespace " Return AssertCodeCleanupResultAsync(expected, code, systemImportsFirst:=True, separateImportsGroups:=True) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeCleanup)> Public Function VisualBasicRemoveUnusedVariable() As Task 'Remove unused variables Dim code As String = "Public Class Program Public Shared Sub Method() Dim i as integer End Sub End Class " Dim expected As String = "Public Class Program Public Shared Sub Method() End Sub End Class " Return AssertCodeCleanupResultAsync(expected, code) End Function <Fact(Skip:="Not implemented")> <Trait(Traits.Feature, Traits.Features.CodeCleanup)> Public Function VisualBasicRemovePrivateMemberIfUnused() As Task Dim code As String = "Friend Class Program Private Shared Sub Method() End Sub End Class " Dim expected As String = "Friend Class Program End Class " Return AssertCodeCleanupResultAsync(expected, code) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeCleanup)> Public Function VisualBasicAddAccessibilityModifiers() As Task Dim code As String = "Class Program Public Shared Sub Method() Console.WriteLine(""Hello"") End Sub End Class " Dim expected As String = "Friend Class Program Public Shared Sub Method() Console.WriteLine(""Hello"") End Sub End Class " Return AssertCodeCleanupResultAsync(expected, code) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeCleanup)> Public Function VisualBasicRemoveUnnecessaryCast() As Task Dim code As String = "Public Class Program Public Shared Sub Method() Dim s as string = CStr(""Hello"") Console.WriteLine(s) End Sub End Class " Dim expected As String = "Public Class Program Public Shared Sub Method() Dim s as string = ""Hello"" Console.WriteLine(s) End Sub End Class " Return AssertCodeCleanupResultAsync(expected, code) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeCleanup)> Public Shared Function VisualBasicSortAccessibilityModifiers() As Task Dim code As String = "Public Class Program Shared Public Sub Method() Console.WriteLine(""Hello"") End Sub End Class " Dim expected As String = "Public Class Program Public Shared Sub Method() Console.WriteLine(""Hello"") End Sub End Class " Return AssertCodeCleanupResultAsync(expected, code) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeCleanup)> Public Function VisualBasicMakePrivateFieldReadOnly() As Task Dim code = "Friend Class Program Private _a() As String Public Sub New(args() As String) If _a.Length = 0 Then Throw New ArgumentException(NameOf(_a)) _a = args End Sub End Class" Dim expected = "Friend Class Program Private ReadOnly _a() As String Public Sub New(args() As String) If _a.Length = 0 Then Throw New ArgumentException(NameOf(_a)) _a = args End Sub End Class" Return AssertCodeCleanupResultAsync(expected, code) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeCleanup)> Public Shared Function VisualBasicApplyMeQualification() As Task Dim code As String = "Public Class Program Private _value As String Public Sub Method() _value = ""Hello"" Me.PrintHello() PrintHello() End Sub Private Sub PrintHello() Console.WriteLine(_value) End Sub End Class " Dim expected As String = "Public Class Program Private _value As String Public Sub Method() _value = ""Hello"" PrintHello() PrintHello() End Sub Private Sub PrintHello() Console.WriteLine(_value) End Sub End Class " Return AssertCodeCleanupResultAsync(expected, code) End Function ''' <summary> ''' Assert the expected code value equals the actual processed input <paramref name="code"/>. ''' </summary> ''' <param name="expected">The actual processed code to verify against.</param> ''' <param name="code">The input code to be processed and tested.</param> ''' <param name="systemImportsFirst">Indicates whether <c><see cref="System"/>.*</c> '<c>Imports</c>' directives should preceded others. Default is <c>true</c>.</param> ''' <param name="separateImportsGroups">Indicates whether '<c>Imports</c>' directives should be organized into separated groups. Default is <c>true</c>.</param> ''' <returns>The <see cref="Task"/> to test code cleanup.</returns> Private Protected Shared Async Function AssertCodeCleanupResultAsync(expected As String, code As String, Optional systemImportsFirst As Boolean = True, Optional separateImportsGroups As Boolean = False) As Task Using workspace = TestWorkspace.CreateVisualBasic(code, composition:=EditorTestCompositions.EditorFeaturesWpf) Dim solution = workspace.CurrentSolution _ .WithOptions(workspace.Options _ .WithChangedOption(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.VisualBasic, systemImportsFirst) _ .WithChangedOption(GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.VisualBasic, separateImportsGroups)) _ .WithAnalyzerReferences({ New AnalyzerFileReference(GetType(VisualBasicCompilerDiagnosticAnalyzer).Assembly.Location, TestAnalyzerAssemblyLoader.LoadFromFile), New AnalyzerFileReference(GetType(MakeFieldReadonlyDiagnosticAnalyzer).Assembly.Location, TestAnalyzerAssemblyLoader.LoadFromFile), New AnalyzerFileReference(GetType(VisualBasicPreferFrameworkTypeDiagnosticAnalyzer).Assembly.Location, TestAnalyzerAssemblyLoader.LoadFromFile) }) workspace.TryApplyChanges(solution) ' register this workspace to solution crawler so that analyzer service associate itself with given workspace Dim incrementalAnalyzerProvider = TryCast(workspace.ExportProvider.GetExportedValue(Of IDiagnosticAnalyzerService)(), IIncrementalAnalyzerProvider) incrementalAnalyzerProvider.CreateIncrementalAnalyzer(workspace) Dim hostdoc = workspace.Documents.[Single]() Dim document = workspace.CurrentSolution.GetDocument(hostdoc.Id) Dim codeCleanupService = document.GetLanguageService(Of ICodeCleanupService)() Dim enabledDiagnostics = codeCleanupService.GetAllDiagnostics() Dim newDoc = Await codeCleanupService.CleanupAsync(document, enabledDiagnostics, New ProgressTracker, CancellationToken.None) Dim actual = Await newDoc.GetTextAsync() AssertEx.EqualOrDiff(expected, actual.ToString()) End Using End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.CodeCleanup Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Diagnostics.VisualBasic Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.MakeFieldReadonly Imports Microsoft.CodeAnalysis.Shared.Utilities Imports Microsoft.CodeAnalysis.SolutionCrawler Imports Microsoft.CodeAnalysis.VisualBasic.Diagnostics.Analyzers Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Formatting <UseExportProvider> Public Class CodeCleanUpTests ' Format Document tests are handled by Format Document Test ' TESTS NEEDED but not found in C# 'Apply object preference initialization preferences 'Apply file header preferences <Fact> <Trait(Traits.Feature, Traits.Features.CodeCleanup)> Public Function VisualBasicRemoveUnusedImports() As Task Dim code = "Imports System.Collections.Generic Imports System Friend Class Program Public Shared Sub Main(args() As String) Console.WriteLine(list.Count) End Sub End Class " Dim expected = "Friend Class Program Public Shared Sub Main(args() As String) Console.WriteLine(list.Count) End Sub End Class " Return AssertCodeCleanupResultAsync(expected, code) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeCleanup)> Public Function VisualBasicSortImports() As Task Dim code = "Imports System.Reflection Imports System.IO Friend Class Program Public Shared Sub Main(args() As String) Dim location As ImmutableArray(Of String) = Assembly.Load(""System.Windows.Forms"").Location Dim SourceText As String Using myFileStream As FileStream = File.OpenRead(location) SourceText = myFileStream.GetFileTextFromStream() End Using End Sub End Class " Dim expected = "Imports System.IO Imports System.Reflection Friend Class Program Public Shared Sub Main(args() As String) Dim location As ImmutableArray(Of String) = Assembly.Load(""System.Windows.Forms"").Location Dim SourceText As String Using myFileStream As FileStream = File.OpenRead(location) SourceText = myFileStream.GetFileTextFromStream() End Using End Sub End Class " Return AssertCodeCleanupResultAsync(expected, code) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeCleanup)> Public Function VisualBasicGroupUsings() As Task 'Apply imports directive placement preference Dim code As String = "Imports M Imports System.IO Friend NotInheritable Class Program Private Shared Sub Main(args As String()) Dim location As ImmutableArray(Of String) = Assembly.Load(""System.Windows.Forms"").Location Dim SourceText As String Using myFileStream As FileStream = File.OpenRead(location) SourceText = myFileStream.GetFileTextFromStream() End Using Dim tempVar As New Goo End Sub End Class Namespace M Public Class Goo End Class End Namespace " Dim expected As String = "Imports M Imports System.IO Friend NotInheritable Class Program Private Shared Sub Main(args As String()) Dim location As ImmutableArray(Of String) = Assembly.Load(""System.Windows.Forms"").Location Dim SourceText As String Using myFileStream As FileStream = File.OpenRead(location) SourceText = myFileStream.GetFileTextFromStream() End Using Dim tempVar As New Goo End Sub End Class Namespace M Public Class Goo End Class End Namespace " Return AssertCodeCleanupResultAsync(expected, code, systemImportsFirst:=False, separateImportsGroups:=True) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeCleanup)> Public Function VisualBasicSortAndGroupUsings() As Task 'Apply imports directive placement preference Dim code As String = "Imports M Imports System.IO Friend NotInheritable Class Program Private Shared Sub Main(args As String()) Dim location As ImmutableArray(Of String) = Assembly.Load(""System.Windows.Forms"").Location Dim SourceText As String Using myFileStream As FileStream = File.OpenRead(location) SourceText = myFileStream.GetFileTextFromStream() End Using Dim tempVar As New Goo End Sub End Class Namespace M Public Class Goo End Class End Namespace " Dim expected As String = "Imports System.IO Imports M Friend NotInheritable Class Program Private Shared Sub Main(args As String()) Dim location As ImmutableArray(Of String) = Assembly.Load(""System.Windows.Forms"").Location Dim SourceText As String Using myFileStream As FileStream = File.OpenRead(location) SourceText = myFileStream.GetFileTextFromStream() End Using Dim tempVar As New Goo End Sub End Class Namespace M Public Class Goo End Class End Namespace " Return AssertCodeCleanupResultAsync(expected, code, systemImportsFirst:=True, separateImportsGroups:=True) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeCleanup)> Public Function VisualBasicRemoveUnusedVariable() As Task 'Remove unused variables Dim code As String = "Public Class Program Public Shared Sub Method() Dim i as integer End Sub End Class " Dim expected As String = "Public Class Program Public Shared Sub Method() End Sub End Class " Return AssertCodeCleanupResultAsync(expected, code) End Function <Fact(Skip:="Not implemented")> <Trait(Traits.Feature, Traits.Features.CodeCleanup)> Public Function VisualBasicRemovePrivateMemberIfUnused() As Task Dim code As String = "Friend Class Program Private Shared Sub Method() End Sub End Class " Dim expected As String = "Friend Class Program End Class " Return AssertCodeCleanupResultAsync(expected, code) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeCleanup)> Public Function VisualBasicAddAccessibilityModifiers() As Task Dim code As String = "Class Program Public Shared Sub Method() Console.WriteLine(""Hello"") End Sub End Class " Dim expected As String = "Friend Class Program Public Shared Sub Method() Console.WriteLine(""Hello"") End Sub End Class " Return AssertCodeCleanupResultAsync(expected, code) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeCleanup)> Public Function VisualBasicRemoveUnnecessaryCast() As Task Dim code As String = "Public Class Program Public Shared Sub Method() Dim s as string = CStr(""Hello"") Console.WriteLine(s) End Sub End Class " Dim expected As String = "Public Class Program Public Shared Sub Method() Dim s as string = ""Hello"" Console.WriteLine(s) End Sub End Class " Return AssertCodeCleanupResultAsync(expected, code) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeCleanup)> Public Shared Function VisualBasicSortAccessibilityModifiers() As Task Dim code As String = "Public Class Program Shared Public Sub Method() Console.WriteLine(""Hello"") End Sub End Class " Dim expected As String = "Public Class Program Public Shared Sub Method() Console.WriteLine(""Hello"") End Sub End Class " Return AssertCodeCleanupResultAsync(expected, code) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeCleanup)> Public Function VisualBasicMakePrivateFieldReadOnly() As Task Dim code = "Friend Class Program Private _a() As String Public Sub New(args() As String) If _a.Length = 0 Then Throw New ArgumentException(NameOf(_a)) _a = args End Sub End Class" Dim expected = "Friend Class Program Private ReadOnly _a() As String Public Sub New(args() As String) If _a.Length = 0 Then Throw New ArgumentException(NameOf(_a)) _a = args End Sub End Class" Return AssertCodeCleanupResultAsync(expected, code) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeCleanup)> Public Shared Function VisualBasicApplyMeQualification() As Task Dim code As String = "Public Class Program Private _value As String Public Sub Method() _value = ""Hello"" Me.PrintHello() PrintHello() End Sub Private Sub PrintHello() Console.WriteLine(_value) End Sub End Class " Dim expected As String = "Public Class Program Private _value As String Public Sub Method() _value = ""Hello"" PrintHello() PrintHello() End Sub Private Sub PrintHello() Console.WriteLine(_value) End Sub End Class " Return AssertCodeCleanupResultAsync(expected, code) End Function ''' <summary> ''' Assert the expected code value equals the actual processed input <paramref name="code"/>. ''' </summary> ''' <param name="expected">The actual processed code to verify against.</param> ''' <param name="code">The input code to be processed and tested.</param> ''' <param name="systemImportsFirst">Indicates whether <c><see cref="System"/>.*</c> '<c>Imports</c>' directives should preceded others. Default is <c>true</c>.</param> ''' <param name="separateImportsGroups">Indicates whether '<c>Imports</c>' directives should be organized into separated groups. Default is <c>true</c>.</param> ''' <returns>The <see cref="Task"/> to test code cleanup.</returns> Private Protected Shared Async Function AssertCodeCleanupResultAsync(expected As String, code As String, Optional systemImportsFirst As Boolean = True, Optional separateImportsGroups As Boolean = False) As Task Using workspace = TestWorkspace.CreateVisualBasic(code, composition:=EditorTestCompositions.EditorFeaturesWpf) Dim solution = workspace.CurrentSolution _ .WithOptions(workspace.Options _ .WithChangedOption(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.VisualBasic, systemImportsFirst) _ .WithChangedOption(GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.VisualBasic, separateImportsGroups)) _ .WithAnalyzerReferences({ New AnalyzerFileReference(GetType(VisualBasicCompilerDiagnosticAnalyzer).Assembly.Location, TestAnalyzerAssemblyLoader.LoadFromFile), New AnalyzerFileReference(GetType(MakeFieldReadonlyDiagnosticAnalyzer).Assembly.Location, TestAnalyzerAssemblyLoader.LoadFromFile), New AnalyzerFileReference(GetType(VisualBasicPreferFrameworkTypeDiagnosticAnalyzer).Assembly.Location, TestAnalyzerAssemblyLoader.LoadFromFile) }) workspace.TryApplyChanges(solution) ' register this workspace to solution crawler so that analyzer service associate itself with given workspace Dim incrementalAnalyzerProvider = TryCast(workspace.ExportProvider.GetExportedValue(Of IDiagnosticAnalyzerService)(), IIncrementalAnalyzerProvider) incrementalAnalyzerProvider.CreateIncrementalAnalyzer(workspace) Dim hostdoc = workspace.Documents.[Single]() Dim document = workspace.CurrentSolution.GetDocument(hostdoc.Id) Dim codeCleanupService = document.GetLanguageService(Of ICodeCleanupService)() Dim enabledDiagnostics = codeCleanupService.GetAllDiagnostics() Dim newDoc = Await codeCleanupService.CleanupAsync(document, enabledDiagnostics, New ProgressTracker, CancellationToken.None) Dim actual = Await newDoc.GetTextAsync() AssertEx.EqualOrDiff(expected, actual.ToString()) End Using End Function End Class End Namespace
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Compilers/Core/Portable/Symbols/VarianceKind.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis { /// <summary> /// An enumeration declaring the kinds of variance supported for generic type parameters. /// </summary> public enum VarianceKind : short { /// <summary> /// Invariant. /// </summary> None = 0, /// <summary> /// Covariant (<c>out</c>). /// </summary> Out = 1, /// <summary> /// Contravariant (<c>in</c>). /// </summary> In = 2, } }
// Licensed to the .NET Foundation under one or more 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 { /// <summary> /// An enumeration declaring the kinds of variance supported for generic type parameters. /// </summary> public enum VarianceKind : short { /// <summary> /// Invariant. /// </summary> None = 0, /// <summary> /// Covariant (<c>out</c>). /// </summary> Out = 1, /// <summary> /// Contravariant (<c>in</c>). /// </summary> In = 2, } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Compilers/CSharp/Portable/BoundTree/BoundBinaryOperator.UncommonData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal partial class BoundBinaryOperator { internal class UncommonData { public static UncommonData UnconvertedInterpolatedStringAddition(ConstantValue? constantValue) => new UncommonData( constantValue, method: null, constrainedToType: null, originalUserDefinedOperatorsOpt: default, isUnconvertedInterpolatedStringAddition: true, interpolatedStringHandlerData: null); public static UncommonData InterpolatedStringHandlerAddition(InterpolatedStringHandlerData data) => new UncommonData( constantValue: null, method: null, constrainedToType: null, originalUserDefinedOperatorsOpt: default, isUnconvertedInterpolatedStringAddition: false, data); public static UncommonData? CreateIfNeeded(ConstantValue? constantValue, MethodSymbol? method, TypeSymbol? constrainedToType, ImmutableArray<MethodSymbol> originalUserDefinedOperatorsOpt) { if (constantValue != null || method is not null || constrainedToType is not null || !originalUserDefinedOperatorsOpt.IsDefault) { return new UncommonData(constantValue, method, constrainedToType, originalUserDefinedOperatorsOpt, isUnconvertedInterpolatedStringAddition: false, interpolatedStringHandlerData: null); } return null; } public readonly ConstantValue? ConstantValue; public readonly MethodSymbol? Method; public readonly TypeSymbol? ConstrainedToType; public readonly bool IsUnconvertedInterpolatedStringAddition; public readonly InterpolatedStringHandlerData? InterpolatedStringHandlerData; // The set of method symbols from which this operator's method was chosen. // Only kept in the tree if the operator was an error and overload resolution // was unable to choose a best method. public readonly ImmutableArray<MethodSymbol> OriginalUserDefinedOperatorsOpt; private UncommonData(ConstantValue? constantValue, MethodSymbol? method, TypeSymbol? constrainedToType, ImmutableArray<MethodSymbol> originalUserDefinedOperatorsOpt, bool isUnconvertedInterpolatedStringAddition, InterpolatedStringHandlerData? interpolatedStringHandlerData) { Debug.Assert(interpolatedStringHandlerData is null || !isUnconvertedInterpolatedStringAddition); ConstantValue = constantValue; Method = method; ConstrainedToType = constrainedToType; OriginalUserDefinedOperatorsOpt = originalUserDefinedOperatorsOpt; IsUnconvertedInterpolatedStringAddition = isUnconvertedInterpolatedStringAddition; InterpolatedStringHandlerData = interpolatedStringHandlerData; } public UncommonData WithUpdatedMethod(MethodSymbol? method) { if ((object?)method == Method) { return this; } return new UncommonData(ConstantValue, method, ConstrainedToType, OriginalUserDefinedOperatorsOpt, IsUnconvertedInterpolatedStringAddition, InterpolatedStringHandlerData); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal partial class BoundBinaryOperator { internal class UncommonData { public static UncommonData UnconvertedInterpolatedStringAddition(ConstantValue? constantValue) => new UncommonData( constantValue, method: null, constrainedToType: null, originalUserDefinedOperatorsOpt: default, isUnconvertedInterpolatedStringAddition: true, interpolatedStringHandlerData: null); public static UncommonData InterpolatedStringHandlerAddition(InterpolatedStringHandlerData data) => new UncommonData( constantValue: null, method: null, constrainedToType: null, originalUserDefinedOperatorsOpt: default, isUnconvertedInterpolatedStringAddition: false, data); public static UncommonData? CreateIfNeeded(ConstantValue? constantValue, MethodSymbol? method, TypeSymbol? constrainedToType, ImmutableArray<MethodSymbol> originalUserDefinedOperatorsOpt) { if (constantValue != null || method is not null || constrainedToType is not null || !originalUserDefinedOperatorsOpt.IsDefault) { return new UncommonData(constantValue, method, constrainedToType, originalUserDefinedOperatorsOpt, isUnconvertedInterpolatedStringAddition: false, interpolatedStringHandlerData: null); } return null; } public readonly ConstantValue? ConstantValue; public readonly MethodSymbol? Method; public readonly TypeSymbol? ConstrainedToType; public readonly bool IsUnconvertedInterpolatedStringAddition; public readonly InterpolatedStringHandlerData? InterpolatedStringHandlerData; // The set of method symbols from which this operator's method was chosen. // Only kept in the tree if the operator was an error and overload resolution // was unable to choose a best method. public readonly ImmutableArray<MethodSymbol> OriginalUserDefinedOperatorsOpt; private UncommonData(ConstantValue? constantValue, MethodSymbol? method, TypeSymbol? constrainedToType, ImmutableArray<MethodSymbol> originalUserDefinedOperatorsOpt, bool isUnconvertedInterpolatedStringAddition, InterpolatedStringHandlerData? interpolatedStringHandlerData) { Debug.Assert(interpolatedStringHandlerData is null || !isUnconvertedInterpolatedStringAddition); ConstantValue = constantValue; Method = method; ConstrainedToType = constrainedToType; OriginalUserDefinedOperatorsOpt = originalUserDefinedOperatorsOpt; IsUnconvertedInterpolatedStringAddition = isUnconvertedInterpolatedStringAddition; InterpolatedStringHandlerData = interpolatedStringHandlerData; } public UncommonData WithUpdatedMethod(MethodSymbol? method) { if ((object?)method == Method) { return this; } return new UncommonData(ConstantValue, method, ConstrainedToType, OriginalUserDefinedOperatorsOpt, IsUnconvertedInterpolatedStringAddition, InterpolatedStringHandlerData); } } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Features/CSharp/Portable/Completion/CompletionProviders/CSharpSuggestionModeCompletionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(CSharpSuggestionModeCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(ObjectAndWithInitializerCompletionProvider))] [Shared] internal class CSharpSuggestionModeCompletionProvider : AbstractSuggestionModeCompletionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpSuggestionModeCompletionProvider() { } protected override async Task<CompletionItem?> GetSuggestionModeItemAsync( Document document, int position, TextSpan itemSpan, CompletionTrigger trigger, CancellationToken cancellationToken = default) { if (trigger.Kind != CompletionTriggerKind.Snippets) { var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = tree .FindTokenOnLeftOfPosition(position, cancellationToken) .GetPreviousTokenIfTouchingWord(position); if (token.Kind() == SyntaxKind.None) return null; var semanticModel = await document.ReuseExistingSpeculativeModelAsync(token.Parent, cancellationToken).ConfigureAwait(false); var typeInferrer = document.GetRequiredLanguageService<ITypeInferenceService>(); if (IsLambdaExpression(semanticModel, tree, position, token, typeInferrer, cancellationToken)) { return CreateSuggestionModeItem(CSharpFeaturesResources.lambda_expression, CSharpFeaturesResources.Autoselect_disabled_due_to_potential_lambda_declaration); } else if (IsAnonymousObjectCreation(token)) { return CreateSuggestionModeItem(CSharpFeaturesResources.member_name, CSharpFeaturesResources.Autoselect_disabled_due_to_possible_explicitly_named_anonymous_type_member_creation); } else if (IsPotentialPatternVariableDeclaration(tree.FindTokenOnLeftOfPosition(position, cancellationToken))) { return CreateSuggestionModeItem(CSharpFeaturesResources.pattern_variable, CSharpFeaturesResources.Autoselect_disabled_due_to_potential_pattern_variable_declaration); } else if (token.IsPreProcessorExpressionContext()) { return CreateEmptySuggestionModeItem(); } else if (token.IsKindOrHasMatchingText(SyntaxKind.FromKeyword) || token.IsKindOrHasMatchingText(SyntaxKind.JoinKeyword)) { return CreateSuggestionModeItem(CSharpFeaturesResources.range_variable, CSharpFeaturesResources.Autoselect_disabled_due_to_potential_range_variable_declaration); } else if (tree.IsNamespaceDeclarationNameContext(position, cancellationToken)) { return CreateSuggestionModeItem(CSharpFeaturesResources.namespace_name, CSharpFeaturesResources.Autoselect_disabled_due_to_namespace_declaration); } else if (tree.IsPartialTypeDeclarationNameContext(position, cancellationToken, out var typeDeclaration)) { switch (typeDeclaration.Keyword.Kind()) { case SyntaxKind.ClassKeyword: return CreateSuggestionModeItem(CSharpFeaturesResources.class_name, CSharpFeaturesResources.Autoselect_disabled_due_to_type_declaration); case SyntaxKind.StructKeyword: return CreateSuggestionModeItem(CSharpFeaturesResources.struct_name, CSharpFeaturesResources.Autoselect_disabled_due_to_type_declaration); case SyntaxKind.InterfaceKeyword: return CreateSuggestionModeItem(CSharpFeaturesResources.interface_name, CSharpFeaturesResources.Autoselect_disabled_due_to_type_declaration); } } else if (tree.IsPossibleDeconstructionDesignation(position, cancellationToken)) { return CreateSuggestionModeItem(CSharpFeaturesResources.designation_name, CSharpFeaturesResources.Autoselect_disabled_due_to_possible_deconstruction_declaration); } } return null; } private static bool IsAnonymousObjectCreation(SyntaxToken token) { if (token.Parent is AnonymousObjectCreationExpressionSyntax) { // We'll show the builder after an open brace or comma, because that's where the // user can start declaring new named parts. return token.Kind() == SyntaxKind.OpenBraceToken || token.Kind() == SyntaxKind.CommaToken; } return false; } private static bool IsLambdaExpression(SemanticModel semanticModel, SyntaxTree tree, int position, SyntaxToken token, ITypeInferenceService typeInferrer, CancellationToken cancellationToken) { // Not after `new` if (token.IsKind(SyntaxKind.NewKeyword) && token.Parent.IsKind(SyntaxKind.ObjectCreationExpression)) { return false; } // Typing a generic type parameter, the tree might look like a binary expression around the < token. // If we infer a delegate type here (because that's what on the other side of the binop), // ignore it. if (token.Kind() == SyntaxKind.LessThanToken && token.Parent is BinaryExpressionSyntax) { return false; } // We might be in the arguments to a parenthesized lambda if (token.Kind() == SyntaxKind.OpenParenToken || token.Kind() == SyntaxKind.CommaToken) { if (token.Parent != null && token.Parent is ParameterListSyntax) { return token.Parent.Parent != null && token.Parent.Parent is ParenthesizedLambdaExpressionSyntax; } } // A lambda that is being typed may be parsed as a tuple without names // For example, "(a, b" could be the start of either a tuple or lambda // But "(a: b, c" cannot be a lambda if (tree.IsPossibleTupleContext(token, position) && token.Parent.IsKind(SyntaxKind.TupleExpression, out TupleExpressionSyntax? tupleExpression) && !tupleExpression.HasNames()) { position = token.Parent.SpanStart; } // Walk up a single level to allow for typing the beginning of a lambda: // new AssemblyLoadEventHandler(($$ if (token.Kind() == SyntaxKind.OpenParenToken && token.GetRequiredParent().Kind() == SyntaxKind.ParenthesizedExpression) { position = token.GetRequiredParent().SpanStart; } // WorkItem 834609: Automatic brace completion inserts the closing paren, making it // like a cast. if (token.Kind() == SyntaxKind.OpenParenToken && token.GetRequiredParent().Kind() == SyntaxKind.CastExpression) { position = token.GetRequiredParent().SpanStart; } // In the following situation, the type inferrer will infer Task to support target type preselection // Action a = Task.$$ // We need to explicitly exclude invocation/member access from suggestion mode var previousToken = token.GetPreviousTokenIfTouchingWord(position); if (previousToken.IsKind(SyntaxKind.DotToken) && previousToken.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { return false; } // async lambda: // Goo(async($$ // Goo(async(p1, $$ if (token.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken) && token.Parent.IsKind(SyntaxKind.ArgumentList) && token.Parent.Parent is InvocationExpressionSyntax invocation && invocation.Expression is IdentifierNameSyntax identifier) { if (identifier.Identifier.IsKindOrHasMatchingText(SyntaxKind.AsyncKeyword)) { return true; } } // If we're an argument to a function with multiple overloads, // open the builder if any overload takes a delegate at our argument position var inferredTypeInfo = typeInferrer.GetTypeInferenceInfo(semanticModel, position, cancellationToken: cancellationToken); return inferredTypeInfo.Any(type => GetDelegateType(type, semanticModel.Compilation).IsDelegateType()); } private static ITypeSymbol? GetDelegateType(TypeInferenceInfo typeInferenceInfo, Compilation compilation) { var typeSymbol = typeInferenceInfo.InferredType; if (typeInferenceInfo.IsParams && typeInferenceInfo.InferredType.IsArrayType()) { typeSymbol = ((IArrayTypeSymbol)typeInferenceInfo.InferredType).ElementType; } return typeSymbol.GetDelegateType(compilation); } private static bool IsPotentialPatternVariableDeclaration(SyntaxToken token) { var patternSyntax = token.GetAncestor<PatternSyntax>(); if (patternSyntax == null) { return false; } for (var current = patternSyntax; current != null; current = current.Parent as PatternSyntax) { // Patterns containing 'or' cannot contain valid variable declarations, e.g. 'e is 1 or int $$' if (current.IsKind(SyntaxKind.OrPattern)) { return false; } // Patterns containing 'not' cannot be valid variable declarations, e.g. 'e is not int $$' and 'e is not (1 and int $$)' if (current.IsKind(SyntaxKind.NotPattern)) { return false; } } // e is int o$$ // e is { P: 1 } o$$ var lastTokenInPattern = patternSyntax.GetLastToken(); if (lastTokenInPattern.Parent is SingleVariableDesignationSyntax variableDesignationSyntax && token.Parent == variableDesignationSyntax) { return patternSyntax is DeclarationPatternSyntax || patternSyntax is RecursivePatternSyntax; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(CSharpSuggestionModeCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(ObjectAndWithInitializerCompletionProvider))] [Shared] internal class CSharpSuggestionModeCompletionProvider : AbstractSuggestionModeCompletionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpSuggestionModeCompletionProvider() { } protected override async Task<CompletionItem?> GetSuggestionModeItemAsync( Document document, int position, TextSpan itemSpan, CompletionTrigger trigger, CancellationToken cancellationToken = default) { if (trigger.Kind != CompletionTriggerKind.Snippets) { var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = tree .FindTokenOnLeftOfPosition(position, cancellationToken) .GetPreviousTokenIfTouchingWord(position); if (token.Kind() == SyntaxKind.None) return null; var semanticModel = await document.ReuseExistingSpeculativeModelAsync(token.Parent, cancellationToken).ConfigureAwait(false); var typeInferrer = document.GetRequiredLanguageService<ITypeInferenceService>(); if (IsLambdaExpression(semanticModel, tree, position, token, typeInferrer, cancellationToken)) { return CreateSuggestionModeItem(CSharpFeaturesResources.lambda_expression, CSharpFeaturesResources.Autoselect_disabled_due_to_potential_lambda_declaration); } else if (IsAnonymousObjectCreation(token)) { return CreateSuggestionModeItem(CSharpFeaturesResources.member_name, CSharpFeaturesResources.Autoselect_disabled_due_to_possible_explicitly_named_anonymous_type_member_creation); } else if (IsPotentialPatternVariableDeclaration(tree.FindTokenOnLeftOfPosition(position, cancellationToken))) { return CreateSuggestionModeItem(CSharpFeaturesResources.pattern_variable, CSharpFeaturesResources.Autoselect_disabled_due_to_potential_pattern_variable_declaration); } else if (token.IsPreProcessorExpressionContext()) { return CreateEmptySuggestionModeItem(); } else if (token.IsKindOrHasMatchingText(SyntaxKind.FromKeyword) || token.IsKindOrHasMatchingText(SyntaxKind.JoinKeyword)) { return CreateSuggestionModeItem(CSharpFeaturesResources.range_variable, CSharpFeaturesResources.Autoselect_disabled_due_to_potential_range_variable_declaration); } else if (tree.IsNamespaceDeclarationNameContext(position, cancellationToken)) { return CreateSuggestionModeItem(CSharpFeaturesResources.namespace_name, CSharpFeaturesResources.Autoselect_disabled_due_to_namespace_declaration); } else if (tree.IsPartialTypeDeclarationNameContext(position, cancellationToken, out var typeDeclaration)) { switch (typeDeclaration.Keyword.Kind()) { case SyntaxKind.ClassKeyword: return CreateSuggestionModeItem(CSharpFeaturesResources.class_name, CSharpFeaturesResources.Autoselect_disabled_due_to_type_declaration); case SyntaxKind.StructKeyword: return CreateSuggestionModeItem(CSharpFeaturesResources.struct_name, CSharpFeaturesResources.Autoselect_disabled_due_to_type_declaration); case SyntaxKind.InterfaceKeyword: return CreateSuggestionModeItem(CSharpFeaturesResources.interface_name, CSharpFeaturesResources.Autoselect_disabled_due_to_type_declaration); } } else if (tree.IsPossibleDeconstructionDesignation(position, cancellationToken)) { return CreateSuggestionModeItem(CSharpFeaturesResources.designation_name, CSharpFeaturesResources.Autoselect_disabled_due_to_possible_deconstruction_declaration); } } return null; } private static bool IsAnonymousObjectCreation(SyntaxToken token) { if (token.Parent is AnonymousObjectCreationExpressionSyntax) { // We'll show the builder after an open brace or comma, because that's where the // user can start declaring new named parts. return token.Kind() == SyntaxKind.OpenBraceToken || token.Kind() == SyntaxKind.CommaToken; } return false; } private static bool IsLambdaExpression(SemanticModel semanticModel, SyntaxTree tree, int position, SyntaxToken token, ITypeInferenceService typeInferrer, CancellationToken cancellationToken) { // Not after `new` if (token.IsKind(SyntaxKind.NewKeyword) && token.Parent.IsKind(SyntaxKind.ObjectCreationExpression)) { return false; } // Typing a generic type parameter, the tree might look like a binary expression around the < token. // If we infer a delegate type here (because that's what on the other side of the binop), // ignore it. if (token.Kind() == SyntaxKind.LessThanToken && token.Parent is BinaryExpressionSyntax) { return false; } // We might be in the arguments to a parenthesized lambda if (token.Kind() == SyntaxKind.OpenParenToken || token.Kind() == SyntaxKind.CommaToken) { if (token.Parent != null && token.Parent is ParameterListSyntax) { return token.Parent.Parent != null && token.Parent.Parent is ParenthesizedLambdaExpressionSyntax; } } // A lambda that is being typed may be parsed as a tuple without names // For example, "(a, b" could be the start of either a tuple or lambda // But "(a: b, c" cannot be a lambda if (tree.IsPossibleTupleContext(token, position) && token.Parent.IsKind(SyntaxKind.TupleExpression, out TupleExpressionSyntax? tupleExpression) && !tupleExpression.HasNames()) { position = token.Parent.SpanStart; } // Walk up a single level to allow for typing the beginning of a lambda: // new AssemblyLoadEventHandler(($$ if (token.Kind() == SyntaxKind.OpenParenToken && token.GetRequiredParent().Kind() == SyntaxKind.ParenthesizedExpression) { position = token.GetRequiredParent().SpanStart; } // WorkItem 834609: Automatic brace completion inserts the closing paren, making it // like a cast. if (token.Kind() == SyntaxKind.OpenParenToken && token.GetRequiredParent().Kind() == SyntaxKind.CastExpression) { position = token.GetRequiredParent().SpanStart; } // In the following situation, the type inferrer will infer Task to support target type preselection // Action a = Task.$$ // We need to explicitly exclude invocation/member access from suggestion mode var previousToken = token.GetPreviousTokenIfTouchingWord(position); if (previousToken.IsKind(SyntaxKind.DotToken) && previousToken.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { return false; } // async lambda: // Goo(async($$ // Goo(async(p1, $$ if (token.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken) && token.Parent.IsKind(SyntaxKind.ArgumentList) && token.Parent.Parent is InvocationExpressionSyntax invocation && invocation.Expression is IdentifierNameSyntax identifier) { if (identifier.Identifier.IsKindOrHasMatchingText(SyntaxKind.AsyncKeyword)) { return true; } } // If we're an argument to a function with multiple overloads, // open the builder if any overload takes a delegate at our argument position var inferredTypeInfo = typeInferrer.GetTypeInferenceInfo(semanticModel, position, cancellationToken: cancellationToken); return inferredTypeInfo.Any(type => GetDelegateType(type, semanticModel.Compilation).IsDelegateType()); } private static ITypeSymbol? GetDelegateType(TypeInferenceInfo typeInferenceInfo, Compilation compilation) { var typeSymbol = typeInferenceInfo.InferredType; if (typeInferenceInfo.IsParams && typeInferenceInfo.InferredType.IsArrayType()) { typeSymbol = ((IArrayTypeSymbol)typeInferenceInfo.InferredType).ElementType; } return typeSymbol.GetDelegateType(compilation); } private static bool IsPotentialPatternVariableDeclaration(SyntaxToken token) { var patternSyntax = token.GetAncestor<PatternSyntax>(); if (patternSyntax == null) { return false; } for (var current = patternSyntax; current != null; current = current.Parent as PatternSyntax) { // Patterns containing 'or' cannot contain valid variable declarations, e.g. 'e is 1 or int $$' if (current.IsKind(SyntaxKind.OrPattern)) { return false; } // Patterns containing 'not' cannot be valid variable declarations, e.g. 'e is not int $$' and 'e is not (1 and int $$)' if (current.IsKind(SyntaxKind.NotPattern)) { return false; } } // e is int o$$ // e is { P: 1 } o$$ var lastTokenInPattern = patternSyntax.GetLastToken(); if (lastTokenInPattern.Parent is SingleVariableDesignationSyntax variableDesignationSyntax && token.Parent == variableDesignationSyntax) { return patternSyntax is DeclarationPatternSyntax || patternSyntax is RecursivePatternSyntax; } return false; } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Compilers/VisualBasic/Portable/Syntax/VisualBasicSyntaxTree.ConditionalSymbolsMap.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports InternalSyntax = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Imports PreprocessorState = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax.Scanner.PreprocessorState Imports Scanner = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax.Scanner Namespace Microsoft.CodeAnalysis.VisualBasic Partial Public Class VisualBasicSyntaxTree ''' <summary> ''' Map containing information about all conditional symbol definitions in the source file corresponding to a parsed syntax tree. ''' </summary> Private Class ConditionalSymbolsMap ''' <summary> ''' Conditional symbols map, where each key-value pair indicates: ''' Key: Conditional symbol name. ''' Value: Stack of all active conditional symbol definitions, i.e. #Const directives, in the source file corresponding to a parsed syntax tree. ''' All the defining #Const directives for a conditional symbol are pushed onto this stack in source code order. ''' Each stack entry is a tuple {InternalSyntax.CConst, Integer} where: ''' InternalSyntax.CConst: Constant value of the symbol. ''' Integer: Source position of the defining #Const directive. ''' </summary> Private ReadOnly _conditionalsMap As ImmutableDictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer))) Friend Shared ReadOnly Uninitialized As ConditionalSymbolsMap = New ConditionalSymbolsMap() ' Only used by Uninitialized instance Private Sub New() End Sub Private Sub New(conditionalsMap As ImmutableDictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer)))) Debug.Assert(conditionalsMap IsNot Nothing) Debug.Assert(conditionalsMap.Any()) #If DEBUG Then For Each kvPair In conditionalsMap Dim conditionalStack As Stack(Of Tuple(Of InternalSyntax.CConst, Integer)) = kvPair.Value Debug.Assert(conditionalStack.Any()) ' Ensure that all the defining #Const directives for this conditional symbol are pushed onto the stack in source code order. Dim prevPosition As Integer = Int32.MaxValue For i = 0 To conditionalStack.Count - 1 Dim position As Integer = conditionalStack(i).Item2 Debug.Assert(prevPosition >= position) prevPosition = position Next Next #End If Me._conditionalsMap = conditionalsMap End Sub #Region "Build conditional symbols map" Friend Shared Function Create(syntaxRoot As VisualBasicSyntaxNode, options As VisualBasicParseOptions) As ConditionalSymbolsMap Dim symbolsMapBuilder = New ConditionalSymbolsMapBuilder() Dim conditionalSymbolsMap As ImmutableDictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer))) = symbolsMapBuilder.Build(syntaxRoot, options) Debug.Assert(conditionalSymbolsMap Is Nothing OrElse conditionalSymbolsMap.Count > 0) Return If(conditionalSymbolsMap IsNot Nothing, New ConditionalSymbolsMap(conditionalSymbolsMap), Nothing) End Function Private Class ConditionalSymbolsMapBuilder Private _conditionalsMap As Dictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer))) Private _preprocessorState As PreprocessorState Friend Function Build(root As SyntaxNodeOrToken, options As VisualBasicParseOptions) As ImmutableDictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer))) Me._conditionalsMap = New Dictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer)))(IdentifierComparison.Comparer) ' Process command line preprocessor symbol definitions. Dim preprocessorSymbolsMap As ImmutableDictionary(Of String, InternalSyntax.CConst) = Scanner.GetPreprocessorConstants(options) Me.ProcessCommandLinePreprocessorSymbols(preprocessorSymbolsMap) Me._preprocessorState = New PreprocessorState(preprocessorSymbolsMap) ' Get and process source directives. Dim directives As IEnumerable(Of DirectiveTriviaSyntax) = root.GetDirectives(Of DirectiveTriviaSyntax)() Debug.Assert(directives IsNot Nothing) ProcessSourceDirectives(directives) Return If(Me._conditionalsMap.Any(), ImmutableDictionary.CreateRange(IdentifierComparison.Comparer, Me._conditionalsMap), Nothing) End Function Private Sub ProcessCommandLinePreprocessorSymbols(preprocessorSymbolsMap As ImmutableDictionary(Of String, InternalSyntax.CConst)) For Each kvPair In preprocessorSymbolsMap Me.ProcessConditionalSymbolDefinition(kvPair.Key, kvPair.Value, 0) Next End Sub Private Sub ProcessConditionalSymbolDefinition(name As String, value As InternalSyntax.CConst, position As Integer) Dim values As Stack(Of Tuple(Of InternalSyntax.CConst, Integer)) = Nothing If Not _conditionalsMap.TryGetValue(name, values) Then ' First definition for this conditional symbol in this source file, create a new key-value pair. values = New Stack(Of Tuple(Of InternalSyntax.CConst, Integer)) _conditionalsMap.Add(name, values) End If values.Push(Tuple.Create(value, position)) End Sub Private Sub ProcessSourceDirectives(directives As IEnumerable(Of DirectiveTriviaSyntax)) For Each directive In directives ProcessDirective(directive) Next End Sub ' Process all active conditional directives under trivia, in source code order. Private Sub ProcessDirective(directive As DirectiveTriviaSyntax) Debug.Assert(_conditionalsMap IsNot Nothing) Debug.Assert(directive IsNot Nothing) Select Case directive.Kind Case SyntaxKind.ConstDirectiveTrivia Dim prevPreprocessorSymbols = _preprocessorState.SymbolsMap _preprocessorState = Scanner.ApplyDirective(_preprocessorState, DirectCast(directive.Green(), InternalSyntax.DirectiveTriviaSyntax)) Dim newPreprocessorSymbols = _preprocessorState.SymbolsMap If Not prevPreprocessorSymbols Is newPreprocessorSymbols Then Dim name As String = DirectCast(directive, ConstDirectiveTriviaSyntax).Name.ValueText #If DEBUG Then Dim values As Stack(Of Tuple(Of InternalSyntax.CConst, Integer)) = Nothing If Not _conditionalsMap.TryGetValue(name, values) Then ' First definition for this conditional symbol in this source file, create a new key-value pair. Debug.Assert(Not prevPreprocessorSymbols.ContainsKey(name)) Else ' Not the first definition for this conditional symbol in this source file. ' We must have an existing entry for this conditional symbol in prevPreprocessorSymbols map. Debug.Assert(values IsNot Nothing) Debug.Assert(prevPreprocessorSymbols.ContainsKey(name)) Debug.Assert(Object.Equals(prevPreprocessorSymbols(name).ValueAsObject, values.Peek().Item1.ValueAsObject)) End If #End If ProcessConditionalSymbolDefinition(name, newPreprocessorSymbols(name), directive.SpanStart) End If Case Else _preprocessorState = Scanner.ApplyDirective(_preprocessorState, DirectCast(directive.Green(), InternalSyntax.DirectiveTriviaSyntax)) End Select End Sub End Class #End Region Friend Function GetPreprocessingSymbolInfo(conditionalSymbolName As String, node As IdentifierNameSyntax) As VisualBasicPreprocessingSymbolInfo Dim constValue As InternalSyntax.CConst = GetPreprocessorSymbolValue(conditionalSymbolName, node) If constValue Is Nothing Then Return VisualBasicPreprocessingSymbolInfo.None End If ' Get symbol name at preprocessor definition, i.e. #Const directive. ' NOTE: symbolName and conditionalSymbolName might have different case, we want the definition name. Dim symbolName = _conditionalsMap.Keys.First(Function(key) IdentifierComparison.Equals(key, conditionalSymbolName)) Return New VisualBasicPreprocessingSymbolInfo(New PreprocessingSymbol(name:=symbolName), constantValueOpt:=constValue.ValueAsObject, isDefined:=True) End Function Private Function GetPreprocessorSymbolValue(conditionalSymbolName As String, node As SyntaxNodeOrToken) As InternalSyntax.CConst Dim values As Stack(Of Tuple(Of InternalSyntax.CConst, Integer)) = Nothing If _conditionalsMap.TryGetValue(conditionalSymbolName, values) Then ' All the defining #Const directives for a conditional symbol are pushed onto the stack in source code order. ' Get the first entry from the top end of the stack with source position less then the source position of 'node'. ' If there is none, then the given conditional symbol is undefined at 'node' Dim position As Integer = node.SpanStart For Each valueTuple In values If valueTuple.Item2 < position Then Return valueTuple.Item1 End If Next End If Return Nothing End Function ' Returns a flag indicating whether the given conditional symbol is defined prior to the given node in source code order in this parsed syntax tree and ' it has a non-zero integral value or non-null string value. ' NOTE: These criteria are used by the native VB compiler. Friend Function IsConditionalSymbolDefined(conditionalSymbolName As String, node As SyntaxNodeOrToken) As Boolean If conditionalSymbolName IsNot Nothing Then Dim constValue As InternalSyntax.CConst = GetPreprocessorSymbolValue(conditionalSymbolName, node) If constValue IsNot Nothing AndAlso Not constValue.IsBad Then Select Case constValue.SpecialType Case SpecialType.System_Boolean Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Boolean)) Return value.Value Case SpecialType.System_Byte Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Byte)) Return value.Value <> 0 Case SpecialType.System_Int16 Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Int16)) Return value.Value <> 0 Case SpecialType.System_Int32 Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Int32)) Return value.Value <> 0 Case SpecialType.System_Int64 Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Int64)) Return value.Value <> 0 Case SpecialType.System_SByte Dim value = DirectCast(constValue, InternalSyntax.CConst(Of SByte)) Return value.Value <> 0 Case SpecialType.System_UInt16 Dim value = DirectCast(constValue, InternalSyntax.CConst(Of UInt16)) Return value.Value <> 0 Case SpecialType.System_UInt32 Dim value = DirectCast(constValue, InternalSyntax.CConst(Of UInt32)) Return value.Value <> 0 Case SpecialType.System_UInt64 Dim value = DirectCast(constValue, InternalSyntax.CConst(Of UInt64)) Return value.Value <> 0 Case SpecialType.System_String Debug.Assert(DirectCast(constValue, InternalSyntax.CConst(Of String)).Value IsNot Nothing) Return True End Select End If End If Return False End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports InternalSyntax = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Imports PreprocessorState = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax.Scanner.PreprocessorState Imports Scanner = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax.Scanner Namespace Microsoft.CodeAnalysis.VisualBasic Partial Public Class VisualBasicSyntaxTree ''' <summary> ''' Map containing information about all conditional symbol definitions in the source file corresponding to a parsed syntax tree. ''' </summary> Private Class ConditionalSymbolsMap ''' <summary> ''' Conditional symbols map, where each key-value pair indicates: ''' Key: Conditional symbol name. ''' Value: Stack of all active conditional symbol definitions, i.e. #Const directives, in the source file corresponding to a parsed syntax tree. ''' All the defining #Const directives for a conditional symbol are pushed onto this stack in source code order. ''' Each stack entry is a tuple {InternalSyntax.CConst, Integer} where: ''' InternalSyntax.CConst: Constant value of the symbol. ''' Integer: Source position of the defining #Const directive. ''' </summary> Private ReadOnly _conditionalsMap As ImmutableDictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer))) Friend Shared ReadOnly Uninitialized As ConditionalSymbolsMap = New ConditionalSymbolsMap() ' Only used by Uninitialized instance Private Sub New() End Sub Private Sub New(conditionalsMap As ImmutableDictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer)))) Debug.Assert(conditionalsMap IsNot Nothing) Debug.Assert(conditionalsMap.Any()) #If DEBUG Then For Each kvPair In conditionalsMap Dim conditionalStack As Stack(Of Tuple(Of InternalSyntax.CConst, Integer)) = kvPair.Value Debug.Assert(conditionalStack.Any()) ' Ensure that all the defining #Const directives for this conditional symbol are pushed onto the stack in source code order. Dim prevPosition As Integer = Int32.MaxValue For i = 0 To conditionalStack.Count - 1 Dim position As Integer = conditionalStack(i).Item2 Debug.Assert(prevPosition >= position) prevPosition = position Next Next #End If Me._conditionalsMap = conditionalsMap End Sub #Region "Build conditional symbols map" Friend Shared Function Create(syntaxRoot As VisualBasicSyntaxNode, options As VisualBasicParseOptions) As ConditionalSymbolsMap Dim symbolsMapBuilder = New ConditionalSymbolsMapBuilder() Dim conditionalSymbolsMap As ImmutableDictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer))) = symbolsMapBuilder.Build(syntaxRoot, options) Debug.Assert(conditionalSymbolsMap Is Nothing OrElse conditionalSymbolsMap.Count > 0) Return If(conditionalSymbolsMap IsNot Nothing, New ConditionalSymbolsMap(conditionalSymbolsMap), Nothing) End Function Private Class ConditionalSymbolsMapBuilder Private _conditionalsMap As Dictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer))) Private _preprocessorState As PreprocessorState Friend Function Build(root As SyntaxNodeOrToken, options As VisualBasicParseOptions) As ImmutableDictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer))) Me._conditionalsMap = New Dictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer)))(IdentifierComparison.Comparer) ' Process command line preprocessor symbol definitions. Dim preprocessorSymbolsMap As ImmutableDictionary(Of String, InternalSyntax.CConst) = Scanner.GetPreprocessorConstants(options) Me.ProcessCommandLinePreprocessorSymbols(preprocessorSymbolsMap) Me._preprocessorState = New PreprocessorState(preprocessorSymbolsMap) ' Get and process source directives. Dim directives As IEnumerable(Of DirectiveTriviaSyntax) = root.GetDirectives(Of DirectiveTriviaSyntax)() Debug.Assert(directives IsNot Nothing) ProcessSourceDirectives(directives) Return If(Me._conditionalsMap.Any(), ImmutableDictionary.CreateRange(IdentifierComparison.Comparer, Me._conditionalsMap), Nothing) End Function Private Sub ProcessCommandLinePreprocessorSymbols(preprocessorSymbolsMap As ImmutableDictionary(Of String, InternalSyntax.CConst)) For Each kvPair In preprocessorSymbolsMap Me.ProcessConditionalSymbolDefinition(kvPair.Key, kvPair.Value, 0) Next End Sub Private Sub ProcessConditionalSymbolDefinition(name As String, value As InternalSyntax.CConst, position As Integer) Dim values As Stack(Of Tuple(Of InternalSyntax.CConst, Integer)) = Nothing If Not _conditionalsMap.TryGetValue(name, values) Then ' First definition for this conditional symbol in this source file, create a new key-value pair. values = New Stack(Of Tuple(Of InternalSyntax.CConst, Integer)) _conditionalsMap.Add(name, values) End If values.Push(Tuple.Create(value, position)) End Sub Private Sub ProcessSourceDirectives(directives As IEnumerable(Of DirectiveTriviaSyntax)) For Each directive In directives ProcessDirective(directive) Next End Sub ' Process all active conditional directives under trivia, in source code order. Private Sub ProcessDirective(directive As DirectiveTriviaSyntax) Debug.Assert(_conditionalsMap IsNot Nothing) Debug.Assert(directive IsNot Nothing) Select Case directive.Kind Case SyntaxKind.ConstDirectiveTrivia Dim prevPreprocessorSymbols = _preprocessorState.SymbolsMap _preprocessorState = Scanner.ApplyDirective(_preprocessorState, DirectCast(directive.Green(), InternalSyntax.DirectiveTriviaSyntax)) Dim newPreprocessorSymbols = _preprocessorState.SymbolsMap If Not prevPreprocessorSymbols Is newPreprocessorSymbols Then Dim name As String = DirectCast(directive, ConstDirectiveTriviaSyntax).Name.ValueText #If DEBUG Then Dim values As Stack(Of Tuple(Of InternalSyntax.CConst, Integer)) = Nothing If Not _conditionalsMap.TryGetValue(name, values) Then ' First definition for this conditional symbol in this source file, create a new key-value pair. Debug.Assert(Not prevPreprocessorSymbols.ContainsKey(name)) Else ' Not the first definition for this conditional symbol in this source file. ' We must have an existing entry for this conditional symbol in prevPreprocessorSymbols map. Debug.Assert(values IsNot Nothing) Debug.Assert(prevPreprocessorSymbols.ContainsKey(name)) Debug.Assert(Object.Equals(prevPreprocessorSymbols(name).ValueAsObject, values.Peek().Item1.ValueAsObject)) End If #End If ProcessConditionalSymbolDefinition(name, newPreprocessorSymbols(name), directive.SpanStart) End If Case Else _preprocessorState = Scanner.ApplyDirective(_preprocessorState, DirectCast(directive.Green(), InternalSyntax.DirectiveTriviaSyntax)) End Select End Sub End Class #End Region Friend Function GetPreprocessingSymbolInfo(conditionalSymbolName As String, node As IdentifierNameSyntax) As VisualBasicPreprocessingSymbolInfo Dim constValue As InternalSyntax.CConst = GetPreprocessorSymbolValue(conditionalSymbolName, node) If constValue Is Nothing Then Return VisualBasicPreprocessingSymbolInfo.None End If ' Get symbol name at preprocessor definition, i.e. #Const directive. ' NOTE: symbolName and conditionalSymbolName might have different case, we want the definition name. Dim symbolName = _conditionalsMap.Keys.First(Function(key) IdentifierComparison.Equals(key, conditionalSymbolName)) Return New VisualBasicPreprocessingSymbolInfo(New PreprocessingSymbol(name:=symbolName), constantValueOpt:=constValue.ValueAsObject, isDefined:=True) End Function Private Function GetPreprocessorSymbolValue(conditionalSymbolName As String, node As SyntaxNodeOrToken) As InternalSyntax.CConst Dim values As Stack(Of Tuple(Of InternalSyntax.CConst, Integer)) = Nothing If _conditionalsMap.TryGetValue(conditionalSymbolName, values) Then ' All the defining #Const directives for a conditional symbol are pushed onto the stack in source code order. ' Get the first entry from the top end of the stack with source position less then the source position of 'node'. ' If there is none, then the given conditional symbol is undefined at 'node' Dim position As Integer = node.SpanStart For Each valueTuple In values If valueTuple.Item2 < position Then Return valueTuple.Item1 End If Next End If Return Nothing End Function ' Returns a flag indicating whether the given conditional symbol is defined prior to the given node in source code order in this parsed syntax tree and ' it has a non-zero integral value or non-null string value. ' NOTE: These criteria are used by the native VB compiler. Friend Function IsConditionalSymbolDefined(conditionalSymbolName As String, node As SyntaxNodeOrToken) As Boolean If conditionalSymbolName IsNot Nothing Then Dim constValue As InternalSyntax.CConst = GetPreprocessorSymbolValue(conditionalSymbolName, node) If constValue IsNot Nothing AndAlso Not constValue.IsBad Then Select Case constValue.SpecialType Case SpecialType.System_Boolean Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Boolean)) Return value.Value Case SpecialType.System_Byte Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Byte)) Return value.Value <> 0 Case SpecialType.System_Int16 Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Int16)) Return value.Value <> 0 Case SpecialType.System_Int32 Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Int32)) Return value.Value <> 0 Case SpecialType.System_Int64 Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Int64)) Return value.Value <> 0 Case SpecialType.System_SByte Dim value = DirectCast(constValue, InternalSyntax.CConst(Of SByte)) Return value.Value <> 0 Case SpecialType.System_UInt16 Dim value = DirectCast(constValue, InternalSyntax.CConst(Of UInt16)) Return value.Value <> 0 Case SpecialType.System_UInt32 Dim value = DirectCast(constValue, InternalSyntax.CConst(Of UInt32)) Return value.Value <> 0 Case SpecialType.System_UInt64 Dim value = DirectCast(constValue, InternalSyntax.CConst(Of UInt64)) Return value.Value <> 0 Case SpecialType.System_String Debug.Assert(DirectCast(constValue, InternalSyntax.CConst(Of String)).Value IsNot Nothing) Return True End Select End If End If Return False End Function End Class End Class End Namespace
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Test/Perf/Utilities/ITraceManager.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Roslyn.Test.Performance.Utilities { public interface ITraceManager { bool HasWarmUpIteration { get; } void Cleanup(); void EndEvent(); void EndScenario(); void EndScenarios(); void ResetScenarioGenerator(); void Setup(); void Start(); void StartEvent(); void StartScenario(string scenarioName, string processName); void StartScenarios(); void Stop(); void WriteScenarios(string[] scenarios); void WriteScenariosFileToDisk(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Roslyn.Test.Performance.Utilities { public interface ITraceManager { bool HasWarmUpIteration { get; } void Cleanup(); void EndEvent(); void EndScenario(); void EndScenarios(); void ResetScenarioGenerator(); void Setup(); void Start(); void StartEvent(); void StartScenario(string scenarioName, string processName); void StartScenarios(); void Stop(); void WriteScenarios(string[] scenarios); void WriteScenariosFileToDisk(); } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Compilers/Core/Portable/Emit/DebugInformationFormat.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Emit { public enum DebugInformationFormat { Pdb = 1, PortablePdb = 2, Embedded = 3, } internal static partial class DebugInformationFormatExtensions { internal static bool IsValid(this DebugInformationFormat value) { return value >= DebugInformationFormat.Pdb && value <= DebugInformationFormat.Embedded; } internal static bool IsPortable(this DebugInformationFormat value) { return value == DebugInformationFormat.PortablePdb || value == DebugInformationFormat.Embedded; } } }
// Licensed to the .NET Foundation under one or more 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.Emit { public enum DebugInformationFormat { Pdb = 1, PortablePdb = 2, Embedded = 3, } internal static partial class DebugInformationFormatExtensions { internal static bool IsValid(this DebugInformationFormat value) { return value >= DebugInformationFormat.Pdb && value <= DebugInformationFormat.Embedded; } internal static bool IsPortable(this DebugInformationFormat value) { return value == DebugInformationFormat.PortablePdb || value == DebugInformationFormat.Embedded; } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/VisualStudio/Xaml/Impl/Features/AutoInsert/IXamlAutoInsertService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.AutoInsert { internal interface IXamlAutoInsertService : ILanguageService { public Task<XamlAutoInsertResult> GetAutoInsertAsync(TextDocument document, char typedChar, int position, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.AutoInsert { internal interface IXamlAutoInsertService : ILanguageService { public Task<XamlAutoInsertResult> GetAutoInsertAsync(TextDocument document, char typedChar, int position, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioDocumentNavigationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; using TextSpan = Microsoft.CodeAnalysis.Text.TextSpan; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation { using Workspace = Microsoft.CodeAnalysis.Workspace; [ExportWorkspaceService(typeof(IDocumentNavigationService), ServiceLayer.Host), Shared] [Export(typeof(VisualStudioDocumentNavigationService))] internal sealed class VisualStudioDocumentNavigationService : ForegroundThreadAffinitizedObject, IDocumentNavigationService { private readonly IServiceProvider _serviceProvider; private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; private readonly IVsRunningDocumentTable4 _runningDocumentTable; private readonly IThreadingContext _threadingContext; private readonly Lazy<SourceGeneratedFileManager> _sourceGeneratedFileManager; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioDocumentNavigationService( IThreadingContext threadingContext, SVsServiceProvider serviceProvider, IVsEditorAdaptersFactoryService editorAdaptersFactoryService, Lazy<SourceGeneratedFileManager> sourceGeneratedFileManager /* lazy to avoid circularities */) : base(threadingContext) { _serviceProvider = serviceProvider; _editorAdaptersFactoryService = editorAdaptersFactoryService; _runningDocumentTable = (IVsRunningDocumentTable4)serviceProvider.GetService(typeof(SVsRunningDocumentTable)); _threadingContext = threadingContext; _sourceGeneratedFileManager = sourceGeneratedFileManager; } public async Task<bool> CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); return CanNavigateToSpan(workspace, documentId, textSpan, cancellationToken); } public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsSecondaryBuffer(workspace, documentId)) { return true; } var document = workspace.CurrentSolution.GetRequiredDocument(documentId); var text = document.GetTextSynchronously(cancellationToken); var boundedTextSpan = GetSpanWithinDocumentBounds(textSpan, text.Length); if (boundedTextSpan != textSpan) { try { throw new ArgumentOutOfRangeException(); } catch (ArgumentOutOfRangeException e) when (FatalError.ReportAndCatch(e)) { } return false; } var vsTextSpan = text.GetVsTextSpanForSpan(textSpan); return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan); } public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsSecondaryBuffer(workspace, documentId)) { return true; } var document = workspace.CurrentSolution.GetRequiredDocument(documentId); var text = document.GetTextSynchronously(cancellationToken); var vsTextSpan = text.GetVsTextSpanForLineOffset(lineNumber, offset); return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan); } public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsSecondaryBuffer(workspace, documentId)) { return true; } var document = workspace.CurrentSolution.GetRequiredDocument(documentId); var text = document.GetTextSynchronously(cancellationToken); var boundedPosition = GetPositionWithinDocumentBounds(position, text.Length); if (boundedPosition != position) { try { throw new ArgumentOutOfRangeException(); } catch (ArgumentOutOfRangeException e) when (FatalError.ReportAndCatch(e)) { } return false; } var vsTextSpan = text.GetVsTextSpanForPosition(position, virtualSpace); return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan); } public async Task<bool> TryNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet? options, bool allowInvalidSpan, CancellationToken cancellationToken) { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); return TryNavigateToSpan(workspace, documentId, textSpan, options, allowInvalidSpan, cancellationToken); } public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet? options, bool allowInvalidSpan, CancellationToken cancellationToken) { return TryNavigateToLocation(workspace, documentId, _ => textSpan, text => GetVsTextSpan(text, textSpan, allowInvalidSpan), options, cancellationToken); static VsTextSpan GetVsTextSpan(SourceText text, TextSpan textSpan, bool allowInvalidSpan) { var boundedTextSpan = GetSpanWithinDocumentBounds(textSpan, text.Length); if (boundedTextSpan != textSpan && !allowInvalidSpan) { try { throw new ArgumentOutOfRangeException(); } catch (ArgumentOutOfRangeException e) when (FatalError.ReportAndCatch(e)) { } } return text.GetVsTextSpanForSpan(boundedTextSpan); } } public bool TryNavigateToLineAndOffset( Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet? options, CancellationToken cancellationToken) { return TryNavigateToLocation(workspace, documentId, document => GetTextSpanFromLineAndOffset(document, lineNumber, offset, cancellationToken), text => GetVsTextSpan(text, lineNumber, offset), options, cancellationToken); static TextSpan GetTextSpanFromLineAndOffset(Document document, int lineNumber, int offset, CancellationToken cancellationToken) { var text = document.GetTextSynchronously(cancellationToken); var linePosition = new LinePosition(lineNumber, offset); return text.Lines.GetTextSpan(new LinePositionSpan(linePosition, linePosition)); } static VsTextSpan GetVsTextSpan(SourceText text, int lineNumber, int offset) { return text.GetVsTextSpanForLineOffset(lineNumber, offset); } } public bool TryNavigateToPosition( Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet? options, CancellationToken cancellationToken) { return TryNavigateToLocation(workspace, documentId, document => GetTextSpanFromPosition(document, position, virtualSpace, cancellationToken), text => GetVsTextSpan(text, position, virtualSpace), options, cancellationToken); static TextSpan GetTextSpanFromPosition(Document document, int position, int virtualSpace, CancellationToken cancellationToken) { var text = document.GetTextSynchronously(cancellationToken); text.GetLineAndOffset(position, out var lineNumber, out var offset); offset += virtualSpace; var linePosition = new LinePosition(lineNumber, offset); return text.Lines.GetTextSpan(new LinePositionSpan(linePosition, linePosition)); } static VsTextSpan GetVsTextSpan(SourceText text, int position, int virtualSpace) { var boundedPosition = GetPositionWithinDocumentBounds(position, text.Length); if (boundedPosition != position) { try { throw new ArgumentOutOfRangeException(); } catch (ArgumentOutOfRangeException e) when (FatalError.ReportAndCatch(e)) { } } return text.GetVsTextSpanForPosition(boundedPosition, virtualSpace); } } private bool TryNavigateToLocation( Workspace workspace, DocumentId documentId, Func<Document, TextSpan> getTextSpanForMapping, Func<SourceText, VsTextSpan> getVsTextSpan, OptionSet? options, CancellationToken cancellationToken) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsForeground()) { throw new InvalidOperationException(ServicesVSResources.Navigation_must_be_performed_on_the_foreground_thread); } var solution = workspace.CurrentSolution; using (OpenNewDocumentStateScope(options ?? solution.Options)) { var document = solution.GetDocument(documentId); if (document == null) { var project = solution.GetProject(documentId.ProjectId); if (project is null) { // This is a source generated document shown in Solution Explorer, but is no longer valid since // the configuration and/or platform changed since the last generation completed. return false; } var generatedDocument = project.GetSourceGeneratedDocumentAsync(documentId, cancellationToken).AsTask().GetAwaiter().GetResult(); if (generatedDocument != null) { _sourceGeneratedFileManager.Value.NavigateToSourceGeneratedFile(generatedDocument, getTextSpanForMapping(generatedDocument), cancellationToken); return true; } return false; } // Before attempting to open the document, check if the location maps to a different file that should be opened instead. var spanMappingService = document.Services.GetService<ISpanMappingService>(); if (spanMappingService != null) { var mappedSpan = GetMappedSpan(spanMappingService, document, getTextSpanForMapping(document), cancellationToken); if (mappedSpan.HasValue) { // Check if the mapped file matches one already in the workspace. // If so use the workspace APIs to navigate to it. Otherwise use VS APIs to navigate to the file path. var documentIdsForFilePath = solution.GetDocumentIdsWithFilePath(mappedSpan.Value.FilePath); if (!documentIdsForFilePath.IsEmpty) { // If the mapped file maps to the same document that was passed in, then re-use the documentId to preserve context. // Otherwise, just pick one of the ids to use for navigation. var documentIdToNavigate = documentIdsForFilePath.Contains(documentId) ? documentId : documentIdsForFilePath.First(); return NavigateToFileInWorkspace(documentIdToNavigate, workspace, getVsTextSpan, cancellationToken); } return TryNavigateToMappedFile(workspace, document, mappedSpan.Value, cancellationToken); } } return NavigateToFileInWorkspace(documentId, workspace, getVsTextSpan, cancellationToken); } } private bool NavigateToFileInWorkspace( DocumentId documentId, Workspace workspace, Func<SourceText, VsTextSpan> getVsTextSpan, CancellationToken cancellationToken) { var document = OpenDocument(workspace, documentId); if (document == null) { return false; } var text = document.GetTextSynchronously(cancellationToken); var textBuffer = text.Container.GetTextBuffer(); var vsTextSpan = getVsTextSpan(text); if (IsSecondaryBuffer(workspace, documentId) && !vsTextSpan.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out vsTextSpan)) { return false; } return NavigateTo(textBuffer, vsTextSpan, cancellationToken); } private bool TryNavigateToMappedFile(Workspace workspace, Document generatedDocument, MappedSpanResult mappedSpanResult, CancellationToken cancellationToken) { var vsWorkspace = (VisualStudioWorkspaceImpl)workspace; // TODO - Move to IOpenDocumentService - https://github.com/dotnet/roslyn/issues/45954 // Pass the original result's project context so that if the mapped file has the same context available, we navigate // to the mapped file with a consistent project context. vsWorkspace.OpenDocumentFromPath(mappedSpanResult.FilePath, generatedDocument.Project.Id); if (_runningDocumentTable.TryGetBufferFromMoniker(_editorAdaptersFactoryService, mappedSpanResult.FilePath, out var textBuffer)) { var vsTextSpan = new VsTextSpan { iStartIndex = mappedSpanResult.LinePositionSpan.Start.Character, iStartLine = mappedSpanResult.LinePositionSpan.Start.Line, iEndIndex = mappedSpanResult.LinePositionSpan.End.Character, iEndLine = mappedSpanResult.LinePositionSpan.End.Line }; return NavigateTo(textBuffer, vsTextSpan, cancellationToken); } return false; } private MappedSpanResult? GetMappedSpan(ISpanMappingService spanMappingService, Document generatedDocument, TextSpan textSpan, CancellationToken cancellationToken) { // Mappings for opened razor files are retrieved via the LSP client making a request to the razor server. // If we wait for the result on the UI thread, we will hit a bug in the LSP client that brings us to a code path // using ConfigureAwait(true). This deadlocks as it then attempts to return to the UI thread which is already blocked by us. // Instead, we invoke this in JTF run which will mitigate deadlocks when the ConfigureAwait(true) // tries to switch back to the main thread in the LSP client. // Link to LSP client bug for ConfigureAwait(true) - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1216657 var results = _threadingContext.JoinableTaskFactory.Run(() => spanMappingService.MapSpansAsync(generatedDocument, SpecializedCollections.SingletonEnumerable(textSpan), cancellationToken)); if (!results.IsDefaultOrEmpty) { return results.First(); } return null; } /// <summary> /// It is unclear why, but we are sometimes asked to navigate to a position that is not /// inside the bounds of the associated <see cref="Document"/>. This method returns a /// position that is guaranteed to be inside the <see cref="Document"/> bounds. If the /// returned position is different from the given position, then the worst observable /// behavior is either no navigation or navigation to the end of the document. See the /// following bugs for more details: /// https://devdiv.visualstudio.com/DevDiv/_workitems?id=112211 /// https://devdiv.visualstudio.com/DevDiv/_workitems?id=136895 /// https://devdiv.visualstudio.com/DevDiv/_workitems?id=224318 /// https://devdiv.visualstudio.com/DevDiv/_workitems?id=235409 /// </summary> private static int GetPositionWithinDocumentBounds(int position, int documentLength) => Math.Min(documentLength, Math.Max(position, 0)); /// <summary> /// It is unclear why, but we are sometimes asked to navigate to a <see cref="TextSpan"/> /// that is not inside the bounds of the associated <see cref="Document"/>. This method /// returns a span that is guaranteed to be inside the <see cref="Document"/> bounds. If /// the returned span is different from the given span, then the worst observable behavior /// is either no navigation or navigation to the end of the document. /// See https://github.com/dotnet/roslyn/issues/7660 for more details. /// </summary> private static TextSpan GetSpanWithinDocumentBounds(TextSpan span, int documentLength) => TextSpan.FromBounds(GetPositionWithinDocumentBounds(span.Start, documentLength), GetPositionWithinDocumentBounds(span.End, documentLength)); private static Document? OpenDocument(Workspace workspace, DocumentId documentId) { // Always open the document again, even if the document is already open in the // workspace. If a document is already open in a preview tab and it is opened again // in a permanent tab, this allows the document to transition to the new state. if (workspace.CanOpenDocuments) { workspace.OpenDocument(documentId); } if (!workspace.IsDocumentOpen(documentId)) { return null; } return workspace.CurrentSolution.GetDocument(documentId); } public bool NavigateTo(ITextBuffer textBuffer, VsTextSpan vsTextSpan, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.NavigationService_VSDocumentNavigationService_NavigateTo, cancellationToken)) { var vsTextBuffer = _editorAdaptersFactoryService.GetBufferAdapter(textBuffer); if (vsTextBuffer == null) { Debug.Fail("Could not get IVsTextBuffer for document!"); return false; } var textManager = (IVsTextManager2)_serviceProvider.GetService(typeof(SVsTextManager)); if (textManager == null) { Debug.Fail("Could not get IVsTextManager service!"); return false; } return ErrorHandler.Succeeded( textManager.NavigateToLineAndColumn2( vsTextBuffer, VSConstants.LOGVIEWID.TextView_guid, vsTextSpan.iStartLine, vsTextSpan.iStartIndex, vsTextSpan.iEndLine, vsTextSpan.iEndIndex, (uint)_VIEWFRAMETYPE.vftCodeWindow)); } } private static bool IsSecondaryBuffer(Workspace workspace, DocumentId documentId) { if (workspace is not VisualStudioWorkspaceImpl visualStudioWorkspace) { return false; } var containedDocument = visualStudioWorkspace.TryGetContainedDocument(documentId); if (containedDocument == null) { return false; } return true; } private static bool CanMapFromSecondaryBufferToPrimaryBuffer(Workspace workspace, DocumentId documentId, VsTextSpan spanInSecondaryBuffer) => spanInSecondaryBuffer.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out _); private static IDisposable OpenNewDocumentStateScope(OptionSet options) { var state = options.GetOption(NavigationOptions.PreferProvisionalTab) ? __VSNEWDOCUMENTSTATE.NDS_Provisional : __VSNEWDOCUMENTSTATE.NDS_Permanent; if (!options.GetOption(NavigationOptions.ActivateTab)) { state |= __VSNEWDOCUMENTSTATE.NDS_NoActivate; } return new NewDocumentStateScope(state, VSConstants.NewDocumentStateReason.Navigation); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; using TextSpan = Microsoft.CodeAnalysis.Text.TextSpan; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation { using Workspace = Microsoft.CodeAnalysis.Workspace; [ExportWorkspaceService(typeof(IDocumentNavigationService), ServiceLayer.Host), Shared] [Export(typeof(VisualStudioDocumentNavigationService))] internal sealed class VisualStudioDocumentNavigationService : ForegroundThreadAffinitizedObject, IDocumentNavigationService { private readonly IServiceProvider _serviceProvider; private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; private readonly IVsRunningDocumentTable4 _runningDocumentTable; private readonly IThreadingContext _threadingContext; private readonly Lazy<SourceGeneratedFileManager> _sourceGeneratedFileManager; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioDocumentNavigationService( IThreadingContext threadingContext, SVsServiceProvider serviceProvider, IVsEditorAdaptersFactoryService editorAdaptersFactoryService, Lazy<SourceGeneratedFileManager> sourceGeneratedFileManager /* lazy to avoid circularities */) : base(threadingContext) { _serviceProvider = serviceProvider; _editorAdaptersFactoryService = editorAdaptersFactoryService; _runningDocumentTable = (IVsRunningDocumentTable4)serviceProvider.GetService(typeof(SVsRunningDocumentTable)); _threadingContext = threadingContext; _sourceGeneratedFileManager = sourceGeneratedFileManager; } public async Task<bool> CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); return CanNavigateToSpan(workspace, documentId, textSpan, cancellationToken); } public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsSecondaryBuffer(workspace, documentId)) { return true; } var document = workspace.CurrentSolution.GetRequiredDocument(documentId); var text = document.GetTextSynchronously(cancellationToken); var boundedTextSpan = GetSpanWithinDocumentBounds(textSpan, text.Length); if (boundedTextSpan != textSpan) { try { throw new ArgumentOutOfRangeException(); } catch (ArgumentOutOfRangeException e) when (FatalError.ReportAndCatch(e)) { } return false; } var vsTextSpan = text.GetVsTextSpanForSpan(textSpan); return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan); } public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsSecondaryBuffer(workspace, documentId)) { return true; } var document = workspace.CurrentSolution.GetRequiredDocument(documentId); var text = document.GetTextSynchronously(cancellationToken); var vsTextSpan = text.GetVsTextSpanForLineOffset(lineNumber, offset); return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan); } public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsSecondaryBuffer(workspace, documentId)) { return true; } var document = workspace.CurrentSolution.GetRequiredDocument(documentId); var text = document.GetTextSynchronously(cancellationToken); var boundedPosition = GetPositionWithinDocumentBounds(position, text.Length); if (boundedPosition != position) { try { throw new ArgumentOutOfRangeException(); } catch (ArgumentOutOfRangeException e) when (FatalError.ReportAndCatch(e)) { } return false; } var vsTextSpan = text.GetVsTextSpanForPosition(position, virtualSpace); return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan); } public async Task<bool> TryNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet? options, bool allowInvalidSpan, CancellationToken cancellationToken) { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); return TryNavigateToSpan(workspace, documentId, textSpan, options, allowInvalidSpan, cancellationToken); } public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet? options, bool allowInvalidSpan, CancellationToken cancellationToken) { return TryNavigateToLocation(workspace, documentId, _ => textSpan, text => GetVsTextSpan(text, textSpan, allowInvalidSpan), options, cancellationToken); static VsTextSpan GetVsTextSpan(SourceText text, TextSpan textSpan, bool allowInvalidSpan) { var boundedTextSpan = GetSpanWithinDocumentBounds(textSpan, text.Length); if (boundedTextSpan != textSpan && !allowInvalidSpan) { try { throw new ArgumentOutOfRangeException(); } catch (ArgumentOutOfRangeException e) when (FatalError.ReportAndCatch(e)) { } } return text.GetVsTextSpanForSpan(boundedTextSpan); } } public bool TryNavigateToLineAndOffset( Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet? options, CancellationToken cancellationToken) { return TryNavigateToLocation(workspace, documentId, document => GetTextSpanFromLineAndOffset(document, lineNumber, offset, cancellationToken), text => GetVsTextSpan(text, lineNumber, offset), options, cancellationToken); static TextSpan GetTextSpanFromLineAndOffset(Document document, int lineNumber, int offset, CancellationToken cancellationToken) { var text = document.GetTextSynchronously(cancellationToken); var linePosition = new LinePosition(lineNumber, offset); return text.Lines.GetTextSpan(new LinePositionSpan(linePosition, linePosition)); } static VsTextSpan GetVsTextSpan(SourceText text, int lineNumber, int offset) { return text.GetVsTextSpanForLineOffset(lineNumber, offset); } } public bool TryNavigateToPosition( Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet? options, CancellationToken cancellationToken) { return TryNavigateToLocation(workspace, documentId, document => GetTextSpanFromPosition(document, position, virtualSpace, cancellationToken), text => GetVsTextSpan(text, position, virtualSpace), options, cancellationToken); static TextSpan GetTextSpanFromPosition(Document document, int position, int virtualSpace, CancellationToken cancellationToken) { var text = document.GetTextSynchronously(cancellationToken); text.GetLineAndOffset(position, out var lineNumber, out var offset); offset += virtualSpace; var linePosition = new LinePosition(lineNumber, offset); return text.Lines.GetTextSpan(new LinePositionSpan(linePosition, linePosition)); } static VsTextSpan GetVsTextSpan(SourceText text, int position, int virtualSpace) { var boundedPosition = GetPositionWithinDocumentBounds(position, text.Length); if (boundedPosition != position) { try { throw new ArgumentOutOfRangeException(); } catch (ArgumentOutOfRangeException e) when (FatalError.ReportAndCatch(e)) { } } return text.GetVsTextSpanForPosition(boundedPosition, virtualSpace); } } private bool TryNavigateToLocation( Workspace workspace, DocumentId documentId, Func<Document, TextSpan> getTextSpanForMapping, Func<SourceText, VsTextSpan> getVsTextSpan, OptionSet? options, CancellationToken cancellationToken) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsForeground()) { throw new InvalidOperationException(ServicesVSResources.Navigation_must_be_performed_on_the_foreground_thread); } var solution = workspace.CurrentSolution; using (OpenNewDocumentStateScope(options ?? solution.Options)) { var document = solution.GetDocument(documentId); if (document == null) { var project = solution.GetProject(documentId.ProjectId); if (project is null) { // This is a source generated document shown in Solution Explorer, but is no longer valid since // the configuration and/or platform changed since the last generation completed. return false; } var generatedDocument = project.GetSourceGeneratedDocumentAsync(documentId, cancellationToken).AsTask().GetAwaiter().GetResult(); if (generatedDocument != null) { _sourceGeneratedFileManager.Value.NavigateToSourceGeneratedFile(generatedDocument, getTextSpanForMapping(generatedDocument), cancellationToken); return true; } return false; } // Before attempting to open the document, check if the location maps to a different file that should be opened instead. var spanMappingService = document.Services.GetService<ISpanMappingService>(); if (spanMappingService != null) { var mappedSpan = GetMappedSpan(spanMappingService, document, getTextSpanForMapping(document), cancellationToken); if (mappedSpan.HasValue) { // Check if the mapped file matches one already in the workspace. // If so use the workspace APIs to navigate to it. Otherwise use VS APIs to navigate to the file path. var documentIdsForFilePath = solution.GetDocumentIdsWithFilePath(mappedSpan.Value.FilePath); if (!documentIdsForFilePath.IsEmpty) { // If the mapped file maps to the same document that was passed in, then re-use the documentId to preserve context. // Otherwise, just pick one of the ids to use for navigation. var documentIdToNavigate = documentIdsForFilePath.Contains(documentId) ? documentId : documentIdsForFilePath.First(); return NavigateToFileInWorkspace(documentIdToNavigate, workspace, getVsTextSpan, cancellationToken); } return TryNavigateToMappedFile(workspace, document, mappedSpan.Value, cancellationToken); } } return NavigateToFileInWorkspace(documentId, workspace, getVsTextSpan, cancellationToken); } } private bool NavigateToFileInWorkspace( DocumentId documentId, Workspace workspace, Func<SourceText, VsTextSpan> getVsTextSpan, CancellationToken cancellationToken) { var document = OpenDocument(workspace, documentId); if (document == null) { return false; } var text = document.GetTextSynchronously(cancellationToken); var textBuffer = text.Container.GetTextBuffer(); var vsTextSpan = getVsTextSpan(text); if (IsSecondaryBuffer(workspace, documentId) && !vsTextSpan.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out vsTextSpan)) { return false; } return NavigateTo(textBuffer, vsTextSpan, cancellationToken); } private bool TryNavigateToMappedFile(Workspace workspace, Document generatedDocument, MappedSpanResult mappedSpanResult, CancellationToken cancellationToken) { var vsWorkspace = (VisualStudioWorkspaceImpl)workspace; // TODO - Move to IOpenDocumentService - https://github.com/dotnet/roslyn/issues/45954 // Pass the original result's project context so that if the mapped file has the same context available, we navigate // to the mapped file with a consistent project context. vsWorkspace.OpenDocumentFromPath(mappedSpanResult.FilePath, generatedDocument.Project.Id); if (_runningDocumentTable.TryGetBufferFromMoniker(_editorAdaptersFactoryService, mappedSpanResult.FilePath, out var textBuffer)) { var vsTextSpan = new VsTextSpan { iStartIndex = mappedSpanResult.LinePositionSpan.Start.Character, iStartLine = mappedSpanResult.LinePositionSpan.Start.Line, iEndIndex = mappedSpanResult.LinePositionSpan.End.Character, iEndLine = mappedSpanResult.LinePositionSpan.End.Line }; return NavigateTo(textBuffer, vsTextSpan, cancellationToken); } return false; } private MappedSpanResult? GetMappedSpan(ISpanMappingService spanMappingService, Document generatedDocument, TextSpan textSpan, CancellationToken cancellationToken) { // Mappings for opened razor files are retrieved via the LSP client making a request to the razor server. // If we wait for the result on the UI thread, we will hit a bug in the LSP client that brings us to a code path // using ConfigureAwait(true). This deadlocks as it then attempts to return to the UI thread which is already blocked by us. // Instead, we invoke this in JTF run which will mitigate deadlocks when the ConfigureAwait(true) // tries to switch back to the main thread in the LSP client. // Link to LSP client bug for ConfigureAwait(true) - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1216657 var results = _threadingContext.JoinableTaskFactory.Run(() => spanMappingService.MapSpansAsync(generatedDocument, SpecializedCollections.SingletonEnumerable(textSpan), cancellationToken)); if (!results.IsDefaultOrEmpty) { return results.First(); } return null; } /// <summary> /// It is unclear why, but we are sometimes asked to navigate to a position that is not /// inside the bounds of the associated <see cref="Document"/>. This method returns a /// position that is guaranteed to be inside the <see cref="Document"/> bounds. If the /// returned position is different from the given position, then the worst observable /// behavior is either no navigation or navigation to the end of the document. See the /// following bugs for more details: /// https://devdiv.visualstudio.com/DevDiv/_workitems?id=112211 /// https://devdiv.visualstudio.com/DevDiv/_workitems?id=136895 /// https://devdiv.visualstudio.com/DevDiv/_workitems?id=224318 /// https://devdiv.visualstudio.com/DevDiv/_workitems?id=235409 /// </summary> private static int GetPositionWithinDocumentBounds(int position, int documentLength) => Math.Min(documentLength, Math.Max(position, 0)); /// <summary> /// It is unclear why, but we are sometimes asked to navigate to a <see cref="TextSpan"/> /// that is not inside the bounds of the associated <see cref="Document"/>. This method /// returns a span that is guaranteed to be inside the <see cref="Document"/> bounds. If /// the returned span is different from the given span, then the worst observable behavior /// is either no navigation or navigation to the end of the document. /// See https://github.com/dotnet/roslyn/issues/7660 for more details. /// </summary> private static TextSpan GetSpanWithinDocumentBounds(TextSpan span, int documentLength) => TextSpan.FromBounds(GetPositionWithinDocumentBounds(span.Start, documentLength), GetPositionWithinDocumentBounds(span.End, documentLength)); private static Document? OpenDocument(Workspace workspace, DocumentId documentId) { // Always open the document again, even if the document is already open in the // workspace. If a document is already open in a preview tab and it is opened again // in a permanent tab, this allows the document to transition to the new state. if (workspace.CanOpenDocuments) { workspace.OpenDocument(documentId); } if (!workspace.IsDocumentOpen(documentId)) { return null; } return workspace.CurrentSolution.GetDocument(documentId); } public bool NavigateTo(ITextBuffer textBuffer, VsTextSpan vsTextSpan, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.NavigationService_VSDocumentNavigationService_NavigateTo, cancellationToken)) { var vsTextBuffer = _editorAdaptersFactoryService.GetBufferAdapter(textBuffer); if (vsTextBuffer == null) { Debug.Fail("Could not get IVsTextBuffer for document!"); return false; } var textManager = (IVsTextManager2)_serviceProvider.GetService(typeof(SVsTextManager)); if (textManager == null) { Debug.Fail("Could not get IVsTextManager service!"); return false; } return ErrorHandler.Succeeded( textManager.NavigateToLineAndColumn2( vsTextBuffer, VSConstants.LOGVIEWID.TextView_guid, vsTextSpan.iStartLine, vsTextSpan.iStartIndex, vsTextSpan.iEndLine, vsTextSpan.iEndIndex, (uint)_VIEWFRAMETYPE.vftCodeWindow)); } } private static bool IsSecondaryBuffer(Workspace workspace, DocumentId documentId) { if (workspace is not VisualStudioWorkspaceImpl visualStudioWorkspace) { return false; } var containedDocument = visualStudioWorkspace.TryGetContainedDocument(documentId); if (containedDocument == null) { return false; } return true; } private static bool CanMapFromSecondaryBufferToPrimaryBuffer(Workspace workspace, DocumentId documentId, VsTextSpan spanInSecondaryBuffer) => spanInSecondaryBuffer.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out _); private static IDisposable OpenNewDocumentStateScope(OptionSet options) { var state = options.GetOption(NavigationOptions.PreferProvisionalTab) ? __VSNEWDOCUMENTSTATE.NDS_Provisional : __VSNEWDOCUMENTSTATE.NDS_Permanent; if (!options.GetOption(NavigationOptions.ActivateTab)) { state |= __VSNEWDOCUMENTSTATE.NDS_NoActivate; } return new NewDocumentStateScope(state, VSConstants.NewDocumentStateReason.Navigation); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Features/Core/Portable/MetadataAsSource/MetadataAsSourceFileService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Composition; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.DecompiledSource; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolMapping; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.MetadataAsSource { [Export(typeof(IMetadataAsSourceFileService)), Shared] internal class MetadataAsSourceFileService : IMetadataAsSourceFileService { /// <summary> /// A lock to guard parallel accesses to this type. In practice, we presume that it's not /// an important scenario that we can be generating multiple documents in parallel, and so /// we simply take this lock around all public entrypoints to enforce sequential access. /// </summary> private readonly SemaphoreSlim _gate = new(initialCount: 1); /// <summary> /// For a description of the key, see GetKeyAsync. /// </summary> private readonly Dictionary<UniqueDocumentKey, MetadataAsSourceGeneratedFileInfo> _keyToInformation = new(); private readonly Dictionary<string, MetadataAsSourceGeneratedFileInfo> _generatedFilenameToInformation = new(StringComparer.OrdinalIgnoreCase); private IBidirectionalMap<MetadataAsSourceGeneratedFileInfo, DocumentId> _openedDocumentIds = BidirectionalMap<MetadataAsSourceGeneratedFileInfo, DocumentId>.Empty; private MetadataAsSourceWorkspace? _workspace; /// <summary> /// We create a mutex so other processes can see if our directory is still alive. We destroy the mutex when /// we purge our generated files. /// </summary> private Mutex? _mutex; private string? _rootTemporaryPathWithGuid; private readonly string _rootTemporaryPath; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MetadataAsSourceFileService() => _rootTemporaryPath = Path.Combine(Path.GetTempPath(), "MetadataAsSource"); private static string CreateMutexName(string directoryName) => "MetadataAsSource-" + directoryName; private string GetRootPathWithGuid_NoLock() { if (_rootTemporaryPathWithGuid == null) { var guidString = Guid.NewGuid().ToString("N"); _rootTemporaryPathWithGuid = Path.Combine(_rootTemporaryPath, guidString); _mutex = new Mutex(initiallyOwned: true, name: CreateMutexName(guidString)); } return _rootTemporaryPathWithGuid; } public async Task<MetadataAsSourceFile> GetGeneratedFileAsync(Project project, ISymbol symbol, bool allowDecompilation, CancellationToken cancellationToken = default) { if (project == null) { throw new ArgumentNullException(nameof(project)); } if (symbol == null) { throw new ArgumentNullException(nameof(symbol)); } if (symbol.Kind == SymbolKind.Namespace) { throw new ArgumentException(FeaturesResources.symbol_cannot_be_a_namespace, nameof(symbol)); } symbol = symbol.GetOriginalUnreducedDefinition(); MetadataAsSourceGeneratedFileInfo fileInfo; Location? navigateLocation = null; var topLevelNamedType = MetadataAsSourceHelpers.GetTopLevelContainingNamedType(symbol); var symbolId = SymbolKey.Create(symbol, cancellationToken); var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { InitializeWorkspace(project); Contract.ThrowIfNull(_workspace); var infoKey = await GetUniqueDocumentKeyAsync(project, topLevelNamedType, allowDecompilation, cancellationToken).ConfigureAwait(false); fileInfo = _keyToInformation.GetOrAdd(infoKey, _ => new MetadataAsSourceGeneratedFileInfo(GetRootPathWithGuid_NoLock(), project, topLevelNamedType, allowDecompilation)); _generatedFilenameToInformation[fileInfo.TemporaryFilePath] = fileInfo; if (!File.Exists(fileInfo.TemporaryFilePath)) { // We need to generate this. First, we'll need a temporary project to do the generation into. We // avoid loading the actual file from disk since it doesn't exist yet. var temporaryProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: false); var temporaryDocument = _workspace.CurrentSolution.AddProject(temporaryProjectInfoAndDocumentId.Item1) .GetDocument(temporaryProjectInfoAndDocumentId.Item2); Contract.ThrowIfNull(temporaryDocument, "The temporary ProjectInfo didn't contain the document it said it would."); var useDecompiler = allowDecompilation; if (useDecompiler) { useDecompiler = !symbol.ContainingAssembly.GetAttributes().Any(attribute => attribute.AttributeClass?.Name == nameof(SuppressIldasmAttribute) && attribute.AttributeClass.ToNameDisplayString() == typeof(SuppressIldasmAttribute).FullName); } if (useDecompiler) { try { var decompiledSourceService = temporaryDocument.GetLanguageService<IDecompiledSourceService>(); if (decompiledSourceService != null) { temporaryDocument = await decompiledSourceService.AddSourceToAsync(temporaryDocument, compilation, symbol, cancellationToken).ConfigureAwait(false); } else { useDecompiler = false; } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { useDecompiler = false; } } if (!useDecompiler) { var sourceFromMetadataService = temporaryDocument.Project.LanguageServices.GetRequiredService<IMetadataAsSourceService>(); temporaryDocument = await sourceFromMetadataService.AddSourceToAsync(temporaryDocument, compilation, symbol, cancellationToken).ConfigureAwait(false); } // We have the content, so write it out to disk var text = await temporaryDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); // Create the directory. It's possible a parallel deletion is happening in another process, so we may have // to retry this a few times. var directoryToCreate = Path.GetDirectoryName(fileInfo.TemporaryFilePath)!; while (!Directory.Exists(directoryToCreate)) { try { Directory.CreateDirectory(directoryToCreate); } catch (DirectoryNotFoundException) { } catch (UnauthorizedAccessException) { } } using (var textWriter = new StreamWriter(fileInfo.TemporaryFilePath, append: false, encoding: MetadataAsSourceGeneratedFileInfo.Encoding)) { text.Write(textWriter, cancellationToken); } // Mark read-only new FileInfo(fileInfo.TemporaryFilePath).IsReadOnly = true; // Locate the target in the thing we just created navigateLocation = await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, temporaryDocument, cancellationToken).ConfigureAwait(false); } // If we don't have a location yet, then that means we're re-using an existing file. In this case, we'll want to relocate the symbol. if (navigateLocation == null) { navigateLocation = await RelocateSymbol_NoLockAsync(fileInfo, symbolId, cancellationToken).ConfigureAwait(false); } } var documentName = string.Format( "{0} [{1}]", topLevelNamedType.Name, FeaturesResources.from_metadata); var documentTooltip = topLevelNamedType.ToDisplayString(new SymbolDisplayFormat(typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces)); return new MetadataAsSourceFile(fileInfo.TemporaryFilePath, navigateLocation, documentName, documentTooltip); } private async Task<Location> RelocateSymbol_NoLockAsync(MetadataAsSourceGeneratedFileInfo fileInfo, SymbolKey symbolId, CancellationToken cancellationToken) { Contract.ThrowIfNull(_workspace); // We need to relocate the symbol in the already existing file. If the file is open, we can just // reuse that workspace. Otherwise, we have to go spin up a temporary project to do the binding. if (_openedDocumentIds.TryGetValue(fileInfo, out var openDocumentId)) { // Awesome, it's already open. Let's try to grab a document for it var document = _workspace.CurrentSolution.GetDocument(openDocumentId); return await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, document, cancellationToken).ConfigureAwait(false); } // Annoying case: the file is still on disk. Only real option here is to spin up a fake project to go and bind in. var temporaryProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: true); var temporaryDocument = _workspace.CurrentSolution.AddProject(temporaryProjectInfoAndDocumentId.Item1) .GetDocument(temporaryProjectInfoAndDocumentId.Item2); return await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, temporaryDocument, cancellationToken).ConfigureAwait(false); } public bool TryAddDocumentToWorkspace(string filePath, SourceTextContainer sourceTextContainer) { using (_gate.DisposableWait()) { if (_generatedFilenameToInformation.TryGetValue(filePath, out var fileInfo)) { Contract.ThrowIfNull(_workspace); Contract.ThrowIfTrue(_openedDocumentIds.ContainsKey(fileInfo)); // We do own the file, so let's open it up in our workspace var newProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: true); _workspace.OnProjectAdded(newProjectInfoAndDocumentId.Item1); _workspace.OnDocumentOpened(newProjectInfoAndDocumentId.Item2, sourceTextContainer); _openedDocumentIds = _openedDocumentIds.Add(fileInfo, newProjectInfoAndDocumentId.Item2); return true; } } return false; } public bool TryRemoveDocumentFromWorkspace(string filePath) { using (_gate.DisposableWait()) { if (_generatedFilenameToInformation.TryGetValue(filePath, out var fileInfo)) { if (_openedDocumentIds.ContainsKey(fileInfo)) { RemoveDocumentFromWorkspace_NoLock(fileInfo); return true; } } } return false; } private void RemoveDocumentFromWorkspace_NoLock(MetadataAsSourceGeneratedFileInfo fileInfo) { var documentId = _openedDocumentIds.GetValueOrDefault(fileInfo); Contract.ThrowIfNull(documentId); Contract.ThrowIfNull(_workspace); _workspace.OnDocumentClosed(documentId, new FileTextLoader(fileInfo.TemporaryFilePath, MetadataAsSourceGeneratedFileInfo.Encoding)); _workspace.OnProjectRemoved(documentId.ProjectId); _openedDocumentIds = _openedDocumentIds.RemoveKey(fileInfo); } private static async Task<UniqueDocumentKey> GetUniqueDocumentKeyAsync(Project project, INamedTypeSymbol topLevelNamedType, bool allowDecompilation, CancellationToken cancellationToken) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(compilation, "We are trying to produce a key for a language that doesn't support compilations."); var peMetadataReference = compilation.GetMetadataReference(topLevelNamedType.ContainingAssembly) as PortableExecutableReference; if (peMetadataReference?.FilePath != null) { return new UniqueDocumentKey(peMetadataReference.FilePath, peMetadataReference.GetMetadataId(), project.Language, SymbolKey.Create(topLevelNamedType, cancellationToken), allowDecompilation); } else { var containingAssembly = topLevelNamedType.ContainingAssembly; return new UniqueDocumentKey(containingAssembly.Identity, containingAssembly.GetMetadata()?.Id, project.Language, SymbolKey.Create(topLevelNamedType, cancellationToken), allowDecompilation); } } private void InitializeWorkspace(Project project) { if (_workspace == null) { _workspace = new MetadataAsSourceWorkspace(this, project.Solution.Workspace.Services.HostServices); } } private async Task<Project?> MapDocumentAsync(Document document, CancellationToken cancellationToken) { MetadataAsSourceGeneratedFileInfo? fileInfo; using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { if (!_openedDocumentIds.TryGetKey(document.Id, out fileInfo)) { return null; } } // WARNING: do not touch any state fields outside the lock. var solution = fileInfo.Workspace.CurrentSolution; var project = solution.GetProject(fileInfo.SourceProjectId); return project; } internal async Task<SymbolMappingResult?> MapSymbolAsync(Document document, SymbolKey symbolId, CancellationToken cancellationToken) { var project = await MapDocumentAsync(document, cancellationToken).ConfigureAwait(false); if (project == null) return null; var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var resolutionResult = symbolId.Resolve(compilation, ignoreAssemblyKey: true, cancellationToken: cancellationToken); if (resolutionResult.Symbol == null) return null; return new SymbolMappingResult(project, resolutionResult.Symbol); } public void CleanupGeneratedFiles() { using (_gate.DisposableWait()) { // Release our mutex to indicate we're no longer using our directory and reset state if (_mutex != null) { _mutex.Dispose(); _mutex = null; _rootTemporaryPathWithGuid = null; } // Clone the list so we don't break our own enumeration var generatedFileInfoList = _generatedFilenameToInformation.Values.ToList(); foreach (var generatedFileInfo in generatedFileInfoList) { if (_openedDocumentIds.ContainsKey(generatedFileInfo)) { RemoveDocumentFromWorkspace_NoLock(generatedFileInfo); } } _generatedFilenameToInformation.Clear(); _keyToInformation.Clear(); Contract.ThrowIfFalse(_openedDocumentIds.IsEmpty); try { if (Directory.Exists(_rootTemporaryPath)) { var deletedEverything = true; // Let's look through directories to delete. foreach (var directoryInfo in new DirectoryInfo(_rootTemporaryPath).EnumerateDirectories()) { // Is there a mutex for this one? if (Mutex.TryOpenExisting(CreateMutexName(directoryInfo.Name), out var acquiredMutex)) { acquiredMutex.Dispose(); deletedEverything = false; continue; } TryDeleteFolderWhichContainsReadOnlyFiles(directoryInfo.FullName); } if (deletedEverything) { Directory.Delete(_rootTemporaryPath); } } } catch (Exception) { } } } private static void TryDeleteFolderWhichContainsReadOnlyFiles(string directoryPath) { try { foreach (var fileInfo in new DirectoryInfo(directoryPath).EnumerateFiles("*", SearchOption.AllDirectories)) { fileInfo.IsReadOnly = false; } Directory.Delete(directoryPath, recursive: true); } catch (Exception) { } } public bool IsNavigableMetadataSymbol(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Event: case SymbolKind.Field: case SymbolKind.Method: case SymbolKind.NamedType: case SymbolKind.Property: case SymbolKind.Parameter: return true; } return false; } public Workspace? TryGetWorkspace() => _workspace; private class UniqueDocumentKey : IEquatable<UniqueDocumentKey> { private static readonly IEqualityComparer<SymbolKey> s_symbolIdComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true); /// <summary> /// The path to the assembly. Null in the case of in-memory assemblies, where we then use assembly identity. /// </summary> private readonly string? _filePath; /// <summary> /// Assembly identity. Only non-null if <see cref="_filePath"/> is null, where it's an in-memory assembly. /// </summary> private readonly AssemblyIdentity? _assemblyIdentity; private readonly MetadataId? _metadataId; private readonly string _language; private readonly SymbolKey _symbolId; private readonly bool _allowDecompilation; public UniqueDocumentKey(string filePath, MetadataId? metadataId, string language, SymbolKey symbolId, bool allowDecompilation) { Contract.ThrowIfNull(filePath); _filePath = filePath; _metadataId = metadataId; _language = language; _symbolId = symbolId; _allowDecompilation = allowDecompilation; } public UniqueDocumentKey(AssemblyIdentity assemblyIdentity, MetadataId? metadataId, string language, SymbolKey symbolId, bool allowDecompilation) { Contract.ThrowIfNull(assemblyIdentity); _assemblyIdentity = assemblyIdentity; _metadataId = metadataId; _language = language; _symbolId = symbolId; _allowDecompilation = allowDecompilation; } public bool Equals(UniqueDocumentKey? other) { if (other == null) { return false; } return StringComparer.OrdinalIgnoreCase.Equals(_filePath, other._filePath) && object.Equals(_assemblyIdentity, other._assemblyIdentity) && object.Equals(_metadataId, other._metadataId) && _language == other._language && s_symbolIdComparer.Equals(_symbolId, other._symbolId) && _allowDecompilation == other._allowDecompilation; } public override bool Equals(object? obj) => Equals(obj as UniqueDocumentKey); public override int GetHashCode() { return Hash.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(_filePath ?? string.Empty), Hash.Combine(_assemblyIdentity?.GetHashCode() ?? 0, Hash.Combine(_metadataId?.GetHashCode() ?? 0, Hash.Combine(_language.GetHashCode(), Hash.Combine(s_symbolIdComparer.GetHashCode(_symbolId), _allowDecompilation.GetHashCode()))))); } } } }
// Licensed to the .NET Foundation under one or more 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.Composition; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.DecompiledSource; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolMapping; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.MetadataAsSource { [Export(typeof(IMetadataAsSourceFileService)), Shared] internal class MetadataAsSourceFileService : IMetadataAsSourceFileService { /// <summary> /// A lock to guard parallel accesses to this type. In practice, we presume that it's not /// an important scenario that we can be generating multiple documents in parallel, and so /// we simply take this lock around all public entrypoints to enforce sequential access. /// </summary> private readonly SemaphoreSlim _gate = new(initialCount: 1); /// <summary> /// For a description of the key, see GetKeyAsync. /// </summary> private readonly Dictionary<UniqueDocumentKey, MetadataAsSourceGeneratedFileInfo> _keyToInformation = new(); private readonly Dictionary<string, MetadataAsSourceGeneratedFileInfo> _generatedFilenameToInformation = new(StringComparer.OrdinalIgnoreCase); private IBidirectionalMap<MetadataAsSourceGeneratedFileInfo, DocumentId> _openedDocumentIds = BidirectionalMap<MetadataAsSourceGeneratedFileInfo, DocumentId>.Empty; private MetadataAsSourceWorkspace? _workspace; /// <summary> /// We create a mutex so other processes can see if our directory is still alive. We destroy the mutex when /// we purge our generated files. /// </summary> private Mutex? _mutex; private string? _rootTemporaryPathWithGuid; private readonly string _rootTemporaryPath; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MetadataAsSourceFileService() => _rootTemporaryPath = Path.Combine(Path.GetTempPath(), "MetadataAsSource"); private static string CreateMutexName(string directoryName) => "MetadataAsSource-" + directoryName; private string GetRootPathWithGuid_NoLock() { if (_rootTemporaryPathWithGuid == null) { var guidString = Guid.NewGuid().ToString("N"); _rootTemporaryPathWithGuid = Path.Combine(_rootTemporaryPath, guidString); _mutex = new Mutex(initiallyOwned: true, name: CreateMutexName(guidString)); } return _rootTemporaryPathWithGuid; } public async Task<MetadataAsSourceFile> GetGeneratedFileAsync(Project project, ISymbol symbol, bool allowDecompilation, CancellationToken cancellationToken = default) { if (project == null) { throw new ArgumentNullException(nameof(project)); } if (symbol == null) { throw new ArgumentNullException(nameof(symbol)); } if (symbol.Kind == SymbolKind.Namespace) { throw new ArgumentException(FeaturesResources.symbol_cannot_be_a_namespace, nameof(symbol)); } symbol = symbol.GetOriginalUnreducedDefinition(); MetadataAsSourceGeneratedFileInfo fileInfo; Location? navigateLocation = null; var topLevelNamedType = MetadataAsSourceHelpers.GetTopLevelContainingNamedType(symbol); var symbolId = SymbolKey.Create(symbol, cancellationToken); var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { InitializeWorkspace(project); Contract.ThrowIfNull(_workspace); var infoKey = await GetUniqueDocumentKeyAsync(project, topLevelNamedType, allowDecompilation, cancellationToken).ConfigureAwait(false); fileInfo = _keyToInformation.GetOrAdd(infoKey, _ => new MetadataAsSourceGeneratedFileInfo(GetRootPathWithGuid_NoLock(), project, topLevelNamedType, allowDecompilation)); _generatedFilenameToInformation[fileInfo.TemporaryFilePath] = fileInfo; if (!File.Exists(fileInfo.TemporaryFilePath)) { // We need to generate this. First, we'll need a temporary project to do the generation into. We // avoid loading the actual file from disk since it doesn't exist yet. var temporaryProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: false); var temporaryDocument = _workspace.CurrentSolution.AddProject(temporaryProjectInfoAndDocumentId.Item1) .GetDocument(temporaryProjectInfoAndDocumentId.Item2); Contract.ThrowIfNull(temporaryDocument, "The temporary ProjectInfo didn't contain the document it said it would."); var useDecompiler = allowDecompilation; if (useDecompiler) { useDecompiler = !symbol.ContainingAssembly.GetAttributes().Any(attribute => attribute.AttributeClass?.Name == nameof(SuppressIldasmAttribute) && attribute.AttributeClass.ToNameDisplayString() == typeof(SuppressIldasmAttribute).FullName); } if (useDecompiler) { try { var decompiledSourceService = temporaryDocument.GetLanguageService<IDecompiledSourceService>(); if (decompiledSourceService != null) { temporaryDocument = await decompiledSourceService.AddSourceToAsync(temporaryDocument, compilation, symbol, cancellationToken).ConfigureAwait(false); } else { useDecompiler = false; } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { useDecompiler = false; } } if (!useDecompiler) { var sourceFromMetadataService = temporaryDocument.Project.LanguageServices.GetRequiredService<IMetadataAsSourceService>(); temporaryDocument = await sourceFromMetadataService.AddSourceToAsync(temporaryDocument, compilation, symbol, cancellationToken).ConfigureAwait(false); } // We have the content, so write it out to disk var text = await temporaryDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); // Create the directory. It's possible a parallel deletion is happening in another process, so we may have // to retry this a few times. var directoryToCreate = Path.GetDirectoryName(fileInfo.TemporaryFilePath)!; while (!Directory.Exists(directoryToCreate)) { try { Directory.CreateDirectory(directoryToCreate); } catch (DirectoryNotFoundException) { } catch (UnauthorizedAccessException) { } } using (var textWriter = new StreamWriter(fileInfo.TemporaryFilePath, append: false, encoding: MetadataAsSourceGeneratedFileInfo.Encoding)) { text.Write(textWriter, cancellationToken); } // Mark read-only new FileInfo(fileInfo.TemporaryFilePath).IsReadOnly = true; // Locate the target in the thing we just created navigateLocation = await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, temporaryDocument, cancellationToken).ConfigureAwait(false); } // If we don't have a location yet, then that means we're re-using an existing file. In this case, we'll want to relocate the symbol. if (navigateLocation == null) { navigateLocation = await RelocateSymbol_NoLockAsync(fileInfo, symbolId, cancellationToken).ConfigureAwait(false); } } var documentName = string.Format( "{0} [{1}]", topLevelNamedType.Name, FeaturesResources.from_metadata); var documentTooltip = topLevelNamedType.ToDisplayString(new SymbolDisplayFormat(typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces)); return new MetadataAsSourceFile(fileInfo.TemporaryFilePath, navigateLocation, documentName, documentTooltip); } private async Task<Location> RelocateSymbol_NoLockAsync(MetadataAsSourceGeneratedFileInfo fileInfo, SymbolKey symbolId, CancellationToken cancellationToken) { Contract.ThrowIfNull(_workspace); // We need to relocate the symbol in the already existing file. If the file is open, we can just // reuse that workspace. Otherwise, we have to go spin up a temporary project to do the binding. if (_openedDocumentIds.TryGetValue(fileInfo, out var openDocumentId)) { // Awesome, it's already open. Let's try to grab a document for it var document = _workspace.CurrentSolution.GetDocument(openDocumentId); return await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, document, cancellationToken).ConfigureAwait(false); } // Annoying case: the file is still on disk. Only real option here is to spin up a fake project to go and bind in. var temporaryProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: true); var temporaryDocument = _workspace.CurrentSolution.AddProject(temporaryProjectInfoAndDocumentId.Item1) .GetDocument(temporaryProjectInfoAndDocumentId.Item2); return await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, temporaryDocument, cancellationToken).ConfigureAwait(false); } public bool TryAddDocumentToWorkspace(string filePath, SourceTextContainer sourceTextContainer) { using (_gate.DisposableWait()) { if (_generatedFilenameToInformation.TryGetValue(filePath, out var fileInfo)) { Contract.ThrowIfNull(_workspace); Contract.ThrowIfTrue(_openedDocumentIds.ContainsKey(fileInfo)); // We do own the file, so let's open it up in our workspace var newProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: true); _workspace.OnProjectAdded(newProjectInfoAndDocumentId.Item1); _workspace.OnDocumentOpened(newProjectInfoAndDocumentId.Item2, sourceTextContainer); _openedDocumentIds = _openedDocumentIds.Add(fileInfo, newProjectInfoAndDocumentId.Item2); return true; } } return false; } public bool TryRemoveDocumentFromWorkspace(string filePath) { using (_gate.DisposableWait()) { if (_generatedFilenameToInformation.TryGetValue(filePath, out var fileInfo)) { if (_openedDocumentIds.ContainsKey(fileInfo)) { RemoveDocumentFromWorkspace_NoLock(fileInfo); return true; } } } return false; } private void RemoveDocumentFromWorkspace_NoLock(MetadataAsSourceGeneratedFileInfo fileInfo) { var documentId = _openedDocumentIds.GetValueOrDefault(fileInfo); Contract.ThrowIfNull(documentId); Contract.ThrowIfNull(_workspace); _workspace.OnDocumentClosed(documentId, new FileTextLoader(fileInfo.TemporaryFilePath, MetadataAsSourceGeneratedFileInfo.Encoding)); _workspace.OnProjectRemoved(documentId.ProjectId); _openedDocumentIds = _openedDocumentIds.RemoveKey(fileInfo); } private static async Task<UniqueDocumentKey> GetUniqueDocumentKeyAsync(Project project, INamedTypeSymbol topLevelNamedType, bool allowDecompilation, CancellationToken cancellationToken) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(compilation, "We are trying to produce a key for a language that doesn't support compilations."); var peMetadataReference = compilation.GetMetadataReference(topLevelNamedType.ContainingAssembly) as PortableExecutableReference; if (peMetadataReference?.FilePath != null) { return new UniqueDocumentKey(peMetadataReference.FilePath, peMetadataReference.GetMetadataId(), project.Language, SymbolKey.Create(topLevelNamedType, cancellationToken), allowDecompilation); } else { var containingAssembly = topLevelNamedType.ContainingAssembly; return new UniqueDocumentKey(containingAssembly.Identity, containingAssembly.GetMetadata()?.Id, project.Language, SymbolKey.Create(topLevelNamedType, cancellationToken), allowDecompilation); } } private void InitializeWorkspace(Project project) { if (_workspace == null) { _workspace = new MetadataAsSourceWorkspace(this, project.Solution.Workspace.Services.HostServices); } } private async Task<Project?> MapDocumentAsync(Document document, CancellationToken cancellationToken) { MetadataAsSourceGeneratedFileInfo? fileInfo; using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { if (!_openedDocumentIds.TryGetKey(document.Id, out fileInfo)) { return null; } } // WARNING: do not touch any state fields outside the lock. var solution = fileInfo.Workspace.CurrentSolution; var project = solution.GetProject(fileInfo.SourceProjectId); return project; } internal async Task<SymbolMappingResult?> MapSymbolAsync(Document document, SymbolKey symbolId, CancellationToken cancellationToken) { var project = await MapDocumentAsync(document, cancellationToken).ConfigureAwait(false); if (project == null) return null; var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var resolutionResult = symbolId.Resolve(compilation, ignoreAssemblyKey: true, cancellationToken: cancellationToken); if (resolutionResult.Symbol == null) return null; return new SymbolMappingResult(project, resolutionResult.Symbol); } public void CleanupGeneratedFiles() { using (_gate.DisposableWait()) { // Release our mutex to indicate we're no longer using our directory and reset state if (_mutex != null) { _mutex.Dispose(); _mutex = null; _rootTemporaryPathWithGuid = null; } // Clone the list so we don't break our own enumeration var generatedFileInfoList = _generatedFilenameToInformation.Values.ToList(); foreach (var generatedFileInfo in generatedFileInfoList) { if (_openedDocumentIds.ContainsKey(generatedFileInfo)) { RemoveDocumentFromWorkspace_NoLock(generatedFileInfo); } } _generatedFilenameToInformation.Clear(); _keyToInformation.Clear(); Contract.ThrowIfFalse(_openedDocumentIds.IsEmpty); try { if (Directory.Exists(_rootTemporaryPath)) { var deletedEverything = true; // Let's look through directories to delete. foreach (var directoryInfo in new DirectoryInfo(_rootTemporaryPath).EnumerateDirectories()) { // Is there a mutex for this one? if (Mutex.TryOpenExisting(CreateMutexName(directoryInfo.Name), out var acquiredMutex)) { acquiredMutex.Dispose(); deletedEverything = false; continue; } TryDeleteFolderWhichContainsReadOnlyFiles(directoryInfo.FullName); } if (deletedEverything) { Directory.Delete(_rootTemporaryPath); } } } catch (Exception) { } } } private static void TryDeleteFolderWhichContainsReadOnlyFiles(string directoryPath) { try { foreach (var fileInfo in new DirectoryInfo(directoryPath).EnumerateFiles("*", SearchOption.AllDirectories)) { fileInfo.IsReadOnly = false; } Directory.Delete(directoryPath, recursive: true); } catch (Exception) { } } public bool IsNavigableMetadataSymbol(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Event: case SymbolKind.Field: case SymbolKind.Method: case SymbolKind.NamedType: case SymbolKind.Property: case SymbolKind.Parameter: return true; } return false; } public Workspace? TryGetWorkspace() => _workspace; private class UniqueDocumentKey : IEquatable<UniqueDocumentKey> { private static readonly IEqualityComparer<SymbolKey> s_symbolIdComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true); /// <summary> /// The path to the assembly. Null in the case of in-memory assemblies, where we then use assembly identity. /// </summary> private readonly string? _filePath; /// <summary> /// Assembly identity. Only non-null if <see cref="_filePath"/> is null, where it's an in-memory assembly. /// </summary> private readonly AssemblyIdentity? _assemblyIdentity; private readonly MetadataId? _metadataId; private readonly string _language; private readonly SymbolKey _symbolId; private readonly bool _allowDecompilation; public UniqueDocumentKey(string filePath, MetadataId? metadataId, string language, SymbolKey symbolId, bool allowDecompilation) { Contract.ThrowIfNull(filePath); _filePath = filePath; _metadataId = metadataId; _language = language; _symbolId = symbolId; _allowDecompilation = allowDecompilation; } public UniqueDocumentKey(AssemblyIdentity assemblyIdentity, MetadataId? metadataId, string language, SymbolKey symbolId, bool allowDecompilation) { Contract.ThrowIfNull(assemblyIdentity); _assemblyIdentity = assemblyIdentity; _metadataId = metadataId; _language = language; _symbolId = symbolId; _allowDecompilation = allowDecompilation; } public bool Equals(UniqueDocumentKey? other) { if (other == null) { return false; } return StringComparer.OrdinalIgnoreCase.Equals(_filePath, other._filePath) && object.Equals(_assemblyIdentity, other._assemblyIdentity) && object.Equals(_metadataId, other._metadataId) && _language == other._language && s_symbolIdComparer.Equals(_symbolId, other._symbolId) && _allowDecompilation == other._allowDecompilation; } public override bool Equals(object? obj) => Equals(obj as UniqueDocumentKey); public override int GetHashCode() { return Hash.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(_filePath ?? string.Empty), Hash.Combine(_assemblyIdentity?.GetHashCode() ?? 0, Hash.Combine(_metadataId?.GetHashCode() ?? 0, Hash.Combine(_language.GetHashCode(), Hash.Combine(s_symbolIdComparer.GetHashCode(_symbolId), _allowDecompilation.GetHashCode()))))); } } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/Results/CheckedAndOrXor.txt
-=-=-=-=-=-=-=-=- SByte And SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.SByte ) body { ConvertChecked( And( ConvertChecked( Parameter( x type: System.SByte ) type: System.Int32 ) ConvertChecked( Parameter( y type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) } return type: System.SByte type: System.Func`3[System.SByte,System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- SByte And SByte => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.SByte ) body { ConvertChecked( ConvertChecked( And( ConvertChecked( Parameter( x type: System.SByte ) type: System.Int32 ) ConvertChecked( Parameter( y type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.SByte,System.SByte,System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- SByte? And SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) Parameter( y type: System.SByte ) body { ConvertChecked( ConvertChecked( And( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( ConvertChecked( Parameter( y type: System.SByte ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted type: System.SByte ) } return type: System.SByte type: System.Func`3[System.Nullable`1[System.SByte],System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- SByte And SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.Nullable`1[System.SByte] ) body { ConvertChecked( And( ConvertChecked( ConvertChecked( Parameter( x type: System.SByte ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.SByte,System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- SByte? And SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) Parameter( y type: System.Nullable`1[System.SByte] ) body { ConvertChecked( And( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.Nullable`1[System.SByte],System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- E_SByte And E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: E_SByte ) body { Convert( ConvertChecked( And( ConvertChecked( Convert( Parameter( x type: E_SByte ) type: System.SByte ) type: System.Int32 ) ConvertChecked( Convert( Parameter( y type: E_SByte ) type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) type: E_SByte ) } return type: E_SByte type: System.Func`3[E_SByte,E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- E_SByte And E_SByte => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: E_SByte ) body { ConvertChecked( Convert( ConvertChecked( And( ConvertChecked( Convert( Parameter( x type: E_SByte ) type: System.SByte ) type: System.Int32 ) ConvertChecked( Convert( Parameter( y type: E_SByte ) type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) type: E_SByte ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[E_SByte,E_SByte,System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- E_SByte? And E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: E_SByte ) body { ConvertChecked( Convert( ConvertChecked( And( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( ConvertChecked( Parameter( y type: E_SByte ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) Lifted type: E_SByte ) } return type: E_SByte type: System.Func`3[System.Nullable`1[E_SByte],E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- E_SByte And E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( And( ConvertChecked( Convert( ConvertChecked( Parameter( x type: E_SByte ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( Parameter( y type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[E_SByte,System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- E_SByte? And E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( And( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( Parameter( y type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[System.Nullable`1[E_SByte],System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- Byte And Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Byte ) body { ConvertChecked( And( ConvertChecked( Parameter( x type: System.Byte ) type: System.Int32 ) ConvertChecked( Parameter( y type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) } return type: System.Byte type: System.Func`3[System.Byte,System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- Byte And Byte => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Byte ) body { ConvertChecked( ConvertChecked( And( ConvertChecked( Parameter( x type: System.Byte ) type: System.Int32 ) ConvertChecked( Parameter( y type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Byte,System.Byte,System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Byte? And Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) Parameter( y type: System.Byte ) body { ConvertChecked( ConvertChecked( And( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( ConvertChecked( Parameter( y type: System.Byte ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted type: System.Byte ) } return type: System.Byte type: System.Func`3[System.Nullable`1[System.Byte],System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- Byte And Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Nullable`1[System.Byte] ) body { ConvertChecked( And( ConvertChecked( ConvertChecked( Parameter( x type: System.Byte ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Byte,System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Byte? And Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) Parameter( y type: System.Nullable`1[System.Byte] ) body { ConvertChecked( And( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Nullable`1[System.Byte],System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- E_Byte And E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: E_Byte ) body { Convert( ConvertChecked( And( ConvertChecked( Convert( Parameter( x type: E_Byte ) type: System.Byte ) type: System.Int32 ) ConvertChecked( Convert( Parameter( y type: E_Byte ) type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) type: E_Byte ) } return type: E_Byte type: System.Func`3[E_Byte,E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- E_Byte And E_Byte => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: E_Byte ) body { ConvertChecked( Convert( ConvertChecked( And( ConvertChecked( Convert( Parameter( x type: E_Byte ) type: System.Byte ) type: System.Int32 ) ConvertChecked( Convert( Parameter( y type: E_Byte ) type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) type: E_Byte ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[E_Byte,E_Byte,System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- E_Byte? And E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) Parameter( y type: E_Byte ) body { ConvertChecked( Convert( ConvertChecked( And( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( ConvertChecked( Parameter( y type: E_Byte ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) Lifted type: E_Byte ) } return type: E_Byte type: System.Func`3[System.Nullable`1[E_Byte],E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- E_Byte And E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( And( ConvertChecked( Convert( ConvertChecked( Parameter( x type: E_Byte ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( Parameter( y type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[E_Byte,System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- E_Byte? And E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) Parameter( y type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( And( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( Parameter( y type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[System.Nullable`1[E_Byte],System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- Short And Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) body { And( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`3[System.Int16,System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- Short And Short => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) body { ConvertChecked( And( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Int16,System.Int16,System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Short? And Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Int16 ) body { ConvertChecked( And( Parameter( x type: System.Nullable`1[System.Int16] ) ConvertChecked( Parameter( y type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted type: System.Int16 ) } return type: System.Int16 type: System.Func`3[System.Nullable`1[System.Int16],System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- Short And Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Nullable`1[System.Int16] ) body { And( ConvertChecked( Parameter( x type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Int16,System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Short? And Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Nullable`1[System.Int16] ) body { And( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Nullable`1[System.Int16],System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- E_Short And E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: E_Short ) body { Convert( And( Convert( Parameter( x type: E_Short ) type: System.Int16 ) Convert( Parameter( y type: E_Short ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) } return type: E_Short type: System.Func`3[E_Short,E_Short,E_Short] ) -=-=-=-=-=-=-=-=- E_Short And E_Short => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: E_Short ) body { ConvertChecked( Convert( And( Convert( Parameter( x type: E_Short ) type: System.Int16 ) Convert( Parameter( y type: E_Short ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[E_Short,E_Short,System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- E_Short? And E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) Parameter( y type: E_Short ) body { ConvertChecked( Convert( And( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Convert( ConvertChecked( Parameter( y type: E_Short ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) Lifted type: E_Short ) } return type: E_Short type: System.Func`3[System.Nullable`1[E_Short],E_Short,E_Short] ) -=-=-=-=-=-=-=-=- E_Short And E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: System.Nullable`1[E_Short] ) body { Convert( And( Convert( ConvertChecked( Parameter( x type: E_Short ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Convert( Parameter( y type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[E_Short,System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- E_Short? And E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) Parameter( y type: System.Nullable`1[E_Short] ) body { Convert( And( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Convert( Parameter( y type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[System.Nullable`1[E_Short],System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- UShort And UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) body { And( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) type: System.UInt16 ) } return type: System.UInt16 type: System.Func`3[System.UInt16,System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- UShort And UShort => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) body { ConvertChecked( And( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) type: System.UInt16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.UInt16,System.UInt16,System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- UShort? And UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.UInt16 ) body { ConvertChecked( And( Parameter( x type: System.Nullable`1[System.UInt16] ) ConvertChecked( Parameter( y type: System.UInt16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted type: System.UInt16 ) } return type: System.UInt16 type: System.Func`3[System.Nullable`1[System.UInt16],System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- UShort And UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.Nullable`1[System.UInt16] ) body { And( ConvertChecked( Parameter( x type: System.UInt16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.UInt16,System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- UShort? And UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.Nullable`1[System.UInt16] ) body { And( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- E_UShort And E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: E_UShort ) body { Convert( And( Convert( Parameter( x type: E_UShort ) type: System.UInt16 ) Convert( Parameter( y type: E_UShort ) type: System.UInt16 ) type: System.UInt16 ) type: E_UShort ) } return type: E_UShort type: System.Func`3[E_UShort,E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- E_UShort And E_UShort => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: E_UShort ) body { ConvertChecked( Convert( And( Convert( Parameter( x type: E_UShort ) type: System.UInt16 ) Convert( Parameter( y type: E_UShort ) type: System.UInt16 ) type: System.UInt16 ) type: E_UShort ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[E_UShort,E_UShort,System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- E_UShort? And E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) Parameter( y type: E_UShort ) body { ConvertChecked( Convert( And( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Convert( ConvertChecked( Parameter( y type: E_UShort ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) Lifted type: E_UShort ) } return type: E_UShort type: System.Func`3[System.Nullable`1[E_UShort],E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- E_UShort And E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: System.Nullable`1[E_UShort] ) body { Convert( And( Convert( ConvertChecked( Parameter( x type: E_UShort ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Convert( Parameter( y type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[E_UShort,System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- E_UShort? And E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) Parameter( y type: System.Nullable`1[E_UShort] ) body { Convert( And( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Convert( Parameter( y type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[System.Nullable`1[E_UShort],System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- Integer And Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) body { And( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`3[System.Int32,System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- Integer And Integer => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) body { ConvertChecked( And( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Int32,System.Int32,System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Integer? And Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Int32 ) body { ConvertChecked( And( Parameter( x type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted type: System.Int32 ) } return type: System.Int32 type: System.Func`3[System.Nullable`1[System.Int32],System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- Integer And Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Nullable`1[System.Int32] ) body { And( ConvertChecked( Parameter( x type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Int32,System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Integer? And Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Nullable`1[System.Int32] ) body { And( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Nullable`1[System.Int32],System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- E_Integer And E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: E_Integer ) body { Convert( And( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) Convert( Parameter( y type: E_Integer ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) } return type: E_Integer type: System.Func`3[E_Integer,E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- E_Integer And E_Integer => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: E_Integer ) body { ConvertChecked( Convert( And( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) Convert( Parameter( y type: E_Integer ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[E_Integer,E_Integer,System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- E_Integer? And E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) Parameter( y type: E_Integer ) body { ConvertChecked( Convert( And( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Convert( ConvertChecked( Parameter( y type: E_Integer ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) Lifted type: E_Integer ) } return type: E_Integer type: System.Func`3[System.Nullable`1[E_Integer],E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- E_Integer And E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: System.Nullable`1[E_Integer] ) body { Convert( And( Convert( ConvertChecked( Parameter( x type: E_Integer ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Convert( Parameter( y type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[E_Integer,System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- E_Integer? And E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) Parameter( y type: System.Nullable`1[E_Integer] ) body { Convert( And( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Convert( Parameter( y type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[System.Nullable`1[E_Integer],System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- UInteger And UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) body { And( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) type: System.UInt32 ) } return type: System.UInt32 type: System.Func`3[System.UInt32,System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- UInteger And UInteger => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) body { ConvertChecked( And( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) type: System.UInt32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.UInt32,System.UInt32,System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- UInteger? And UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.UInt32 ) body { ConvertChecked( And( Parameter( x type: System.Nullable`1[System.UInt32] ) ConvertChecked( Parameter( y type: System.UInt32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted type: System.UInt32 ) } return type: System.UInt32 type: System.Func`3[System.Nullable`1[System.UInt32],System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- UInteger And UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.Nullable`1[System.UInt32] ) body { And( ConvertChecked( Parameter( x type: System.UInt32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.UInt32,System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- UInteger? And UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.Nullable`1[System.UInt32] ) body { And( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- E_UInteger And E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: E_UInteger ) body { Convert( And( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) Convert( Parameter( y type: E_UInteger ) type: System.UInt32 ) type: System.UInt32 ) type: E_UInteger ) } return type: E_UInteger type: System.Func`3[E_UInteger,E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- E_UInteger And E_UInteger => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: E_UInteger ) body { ConvertChecked( Convert( And( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) Convert( Parameter( y type: E_UInteger ) type: System.UInt32 ) type: System.UInt32 ) type: E_UInteger ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[E_UInteger,E_UInteger,System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- E_UInteger? And E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) Parameter( y type: E_UInteger ) body { ConvertChecked( Convert( And( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Convert( ConvertChecked( Parameter( y type: E_UInteger ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) Lifted type: E_UInteger ) } return type: E_UInteger type: System.Func`3[System.Nullable`1[E_UInteger],E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- E_UInteger And E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: System.Nullable`1[E_UInteger] ) body { Convert( And( Convert( ConvertChecked( Parameter( x type: E_UInteger ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Convert( Parameter( y type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[E_UInteger,System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- E_UInteger? And E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) Parameter( y type: System.Nullable`1[E_UInteger] ) body { Convert( And( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Convert( Parameter( y type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- Long And Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) body { And( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`3[System.Int64,System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- Long And Long => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) body { ConvertChecked( And( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Int64,System.Int64,System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Long? And Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Int64 ) body { ConvertChecked( And( Parameter( x type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted type: System.Int64 ) } return type: System.Int64 type: System.Func`3[System.Nullable`1[System.Int64],System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- Long And Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Nullable`1[System.Int64] ) body { And( ConvertChecked( Parameter( x type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Int64,System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Long? And Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Nullable`1[System.Int64] ) body { And( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Nullable`1[System.Int64],System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- E_Long And E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: E_Long ) body { Convert( And( Convert( Parameter( x type: E_Long ) type: System.Int64 ) Convert( Parameter( y type: E_Long ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) } return type: E_Long type: System.Func`3[E_Long,E_Long,E_Long] ) -=-=-=-=-=-=-=-=- E_Long And E_Long => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: E_Long ) body { ConvertChecked( Convert( And( Convert( Parameter( x type: E_Long ) type: System.Int64 ) Convert( Parameter( y type: E_Long ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[E_Long,E_Long,System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- E_Long? And E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) Parameter( y type: E_Long ) body { ConvertChecked( Convert( And( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Convert( ConvertChecked( Parameter( y type: E_Long ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) Lifted type: E_Long ) } return type: E_Long type: System.Func`3[System.Nullable`1[E_Long],E_Long,E_Long] ) -=-=-=-=-=-=-=-=- E_Long And E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: System.Nullable`1[E_Long] ) body { Convert( And( Convert( ConvertChecked( Parameter( x type: E_Long ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Convert( Parameter( y type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[E_Long,System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- E_Long? And E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) Parameter( y type: System.Nullable`1[E_Long] ) body { Convert( And( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Convert( Parameter( y type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[System.Nullable`1[E_Long],System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- ULong And ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) body { And( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) type: System.UInt64 ) } return type: System.UInt64 type: System.Func`3[System.UInt64,System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- ULong And ULong => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) body { ConvertChecked( And( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) type: System.UInt64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.UInt64,System.UInt64,System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- ULong? And ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.UInt64 ) body { ConvertChecked( And( Parameter( x type: System.Nullable`1[System.UInt64] ) ConvertChecked( Parameter( y type: System.UInt64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted type: System.UInt64 ) } return type: System.UInt64 type: System.Func`3[System.Nullable`1[System.UInt64],System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- ULong And ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.Nullable`1[System.UInt64] ) body { And( ConvertChecked( Parameter( x type: System.UInt64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.UInt64,System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- ULong? And ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.Nullable`1[System.UInt64] ) body { And( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- E_ULong And E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: E_ULong ) body { Convert( And( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) Convert( Parameter( y type: E_ULong ) type: System.UInt64 ) type: System.UInt64 ) type: E_ULong ) } return type: E_ULong type: System.Func`3[E_ULong,E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- E_ULong And E_ULong => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: E_ULong ) body { ConvertChecked( Convert( And( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) Convert( Parameter( y type: E_ULong ) type: System.UInt64 ) type: System.UInt64 ) type: E_ULong ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[E_ULong,E_ULong,System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- E_ULong? And E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) Parameter( y type: E_ULong ) body { ConvertChecked( Convert( And( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Convert( ConvertChecked( Parameter( y type: E_ULong ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) Lifted type: E_ULong ) } return type: E_ULong type: System.Func`3[System.Nullable`1[E_ULong],E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- E_ULong And E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: System.Nullable`1[E_ULong] ) body { Convert( And( Convert( ConvertChecked( Parameter( x type: E_ULong ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Convert( Parameter( y type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[E_ULong,System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- E_ULong? And E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) Parameter( y type: System.Nullable`1[E_ULong] ) body { Convert( And( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Convert( Parameter( y type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[System.Nullable`1[E_ULong],System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- Boolean And Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) body { And( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) type: System.Boolean ) } return type: System.Boolean type: System.Func`3[System.Boolean,System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- Boolean And Boolean => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) body { Convert( And( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Boolean,System.Boolean,System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Boolean? And Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Boolean ) body { Convert( And( Parameter( x type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Boolean ) } return type: System.Boolean type: System.Func`3[System.Nullable`1[System.Boolean],System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- Boolean And Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Nullable`1[System.Boolean] ) body { And( Convert( Parameter( x type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Boolean,System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Boolean? And Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) body { And( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Single And Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Single ) body { Convert( And( ConvertChecked( Parameter( x type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) ConvertChecked( Parameter( y type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Single ) } return type: System.Single type: System.Func`3[System.Single,System.Single,System.Single] ) -=-=-=-=-=-=-=-=- Single And Single => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Single ) body { Convert( Convert( And( ConvertChecked( Parameter( x type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) ConvertChecked( Parameter( y type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Single ) method: System.Nullable`1[System.Single] op_Implicit(Single) in System.Nullable`1[System.Single] type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Single,System.Single,System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Single? And Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) Parameter( y type: System.Single ) body { Convert( ConvertChecked( And( ConvertChecked( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) ConvertChecked( ConvertChecked( Parameter( y type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) type: System.Single ) } return type: System.Single type: System.Func`3[System.Nullable`1[System.Single],System.Single,System.Single] ) -=-=-=-=-=-=-=-=- Single And Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Nullable`1[System.Single] ) body { Convert( And( ConvertChecked( ConvertChecked( Parameter( x type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Single,System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Single? And Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) Parameter( y type: System.Nullable`1[System.Single] ) body { Convert( And( ConvertChecked( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Nullable`1[System.Single],System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Double And Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Double ) body { Convert( And( ConvertChecked( Parameter( x type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) ConvertChecked( Parameter( y type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Double ) } return type: System.Double type: System.Func`3[System.Double,System.Double,System.Double] ) -=-=-=-=-=-=-=-=- Double And Double => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Double ) body { Convert( Convert( And( ConvertChecked( Parameter( x type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) ConvertChecked( Parameter( y type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Double,System.Double,System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Double? And Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) Parameter( y type: System.Double ) body { Convert( ConvertChecked( And( ConvertChecked( Parameter( x type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) ConvertChecked( ConvertChecked( Parameter( y type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) type: System.Double ) } return type: System.Double type: System.Func`3[System.Nullable`1[System.Double],System.Double,System.Double] ) -=-=-=-=-=-=-=-=- Double And Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Nullable`1[System.Double] ) body { Convert( And( ConvertChecked( ConvertChecked( Parameter( x type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Double,System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Double? And Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) Parameter( y type: System.Nullable`1[System.Double] ) body { Convert( And( ConvertChecked( Parameter( x type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Nullable`1[System.Double],System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Decimal And Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Decimal ) body { Convert( And( ConvertChecked( Parameter( x type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) ConvertChecked( Parameter( y type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`3[System.Decimal,System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- Decimal And Decimal => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Decimal ) body { Convert( Convert( And( ConvertChecked( Parameter( x type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) ConvertChecked( Parameter( y type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) method: System.Nullable`1[System.Decimal] op_Implicit(System.Decimal) in System.Nullable`1[System.Decimal] type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Decimal,System.Decimal,System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Decimal? And Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) Parameter( y type: System.Decimal ) body { Convert( ConvertChecked( And( ConvertChecked( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) ConvertChecked( ConvertChecked( Parameter( y type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`3[System.Nullable`1[System.Decimal],System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- Decimal And Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Nullable`1[System.Decimal] ) body { Convert( And( ConvertChecked( ConvertChecked( Parameter( x type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Decimal,System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Decimal? And Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) Parameter( y type: System.Nullable`1[System.Decimal] ) body { Convert( And( ConvertChecked( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- String And String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.String ) body { Convert( And( ConvertChecked( Parameter( x type: System.String ) method: Int64 ToLong(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int64 ) ConvertChecked( Parameter( y type: System.String ) method: Int64 ToLong(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int64 ) type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.String,System.String] ) -=-=-=-=-=-=-=-=- Object And Object => Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) Parameter( y type: System.Object ) body { And( Parameter( x type: System.Object ) Parameter( y type: System.Object ) method: System.Object AndObject(System.Object, System.Object) in Microsoft.VisualBasic.CompilerServices.Operators type: System.Object ) } return type: System.Object type: System.Func`3[System.Object,System.Object,System.Object] ) -=-=-=-=-=-=-=-=- SByte Or SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.SByte ) body { ConvertChecked( Or( ConvertChecked( Parameter( x type: System.SByte ) type: System.Int32 ) ConvertChecked( Parameter( y type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) } return type: System.SByte type: System.Func`3[System.SByte,System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- SByte Or SByte => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.SByte ) body { ConvertChecked( ConvertChecked( Or( ConvertChecked( Parameter( x type: System.SByte ) type: System.Int32 ) ConvertChecked( Parameter( y type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.SByte,System.SByte,System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- SByte? Or SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) Parameter( y type: System.SByte ) body { ConvertChecked( ConvertChecked( Or( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( ConvertChecked( Parameter( y type: System.SByte ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted type: System.SByte ) } return type: System.SByte type: System.Func`3[System.Nullable`1[System.SByte],System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- SByte Or SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.Nullable`1[System.SByte] ) body { ConvertChecked( Or( ConvertChecked( ConvertChecked( Parameter( x type: System.SByte ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.SByte,System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- SByte? Or SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) Parameter( y type: System.Nullable`1[System.SByte] ) body { ConvertChecked( Or( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.Nullable`1[System.SByte],System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- E_SByte Or E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: E_SByte ) body { Convert( ConvertChecked( Or( ConvertChecked( Convert( Parameter( x type: E_SByte ) type: System.SByte ) type: System.Int32 ) ConvertChecked( Convert( Parameter( y type: E_SByte ) type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) type: E_SByte ) } return type: E_SByte type: System.Func`3[E_SByte,E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- E_SByte Or E_SByte => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: E_SByte ) body { ConvertChecked( Convert( ConvertChecked( Or( ConvertChecked( Convert( Parameter( x type: E_SByte ) type: System.SByte ) type: System.Int32 ) ConvertChecked( Convert( Parameter( y type: E_SByte ) type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) type: E_SByte ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[E_SByte,E_SByte,System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- E_SByte? Or E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: E_SByte ) body { ConvertChecked( Convert( ConvertChecked( Or( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( ConvertChecked( Parameter( y type: E_SByte ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) Lifted type: E_SByte ) } return type: E_SByte type: System.Func`3[System.Nullable`1[E_SByte],E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- E_SByte Or E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( Or( ConvertChecked( Convert( ConvertChecked( Parameter( x type: E_SByte ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( Parameter( y type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[E_SByte,System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- E_SByte? Or E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( Or( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( Parameter( y type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[System.Nullable`1[E_SByte],System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- Byte Or Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Byte ) body { ConvertChecked( Or( ConvertChecked( Parameter( x type: System.Byte ) type: System.Int32 ) ConvertChecked( Parameter( y type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) } return type: System.Byte type: System.Func`3[System.Byte,System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- Byte Or Byte => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Byte ) body { ConvertChecked( ConvertChecked( Or( ConvertChecked( Parameter( x type: System.Byte ) type: System.Int32 ) ConvertChecked( Parameter( y type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Byte,System.Byte,System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Byte? Or Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) Parameter( y type: System.Byte ) body { ConvertChecked( ConvertChecked( Or( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( ConvertChecked( Parameter( y type: System.Byte ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted type: System.Byte ) } return type: System.Byte type: System.Func`3[System.Nullable`1[System.Byte],System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- Byte Or Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Nullable`1[System.Byte] ) body { ConvertChecked( Or( ConvertChecked( ConvertChecked( Parameter( x type: System.Byte ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Byte,System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Byte? Or Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) Parameter( y type: System.Nullable`1[System.Byte] ) body { ConvertChecked( Or( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Nullable`1[System.Byte],System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- E_Byte Or E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: E_Byte ) body { Convert( ConvertChecked( Or( ConvertChecked( Convert( Parameter( x type: E_Byte ) type: System.Byte ) type: System.Int32 ) ConvertChecked( Convert( Parameter( y type: E_Byte ) type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) type: E_Byte ) } return type: E_Byte type: System.Func`3[E_Byte,E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- E_Byte Or E_Byte => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: E_Byte ) body { ConvertChecked( Convert( ConvertChecked( Or( ConvertChecked( Convert( Parameter( x type: E_Byte ) type: System.Byte ) type: System.Int32 ) ConvertChecked( Convert( Parameter( y type: E_Byte ) type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) type: E_Byte ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[E_Byte,E_Byte,System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- E_Byte? Or E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) Parameter( y type: E_Byte ) body { ConvertChecked( Convert( ConvertChecked( Or( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( ConvertChecked( Parameter( y type: E_Byte ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) Lifted type: E_Byte ) } return type: E_Byte type: System.Func`3[System.Nullable`1[E_Byte],E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- E_Byte Or E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( Or( ConvertChecked( Convert( ConvertChecked( Parameter( x type: E_Byte ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( Parameter( y type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[E_Byte,System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- E_Byte? Or E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) Parameter( y type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( Or( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( Parameter( y type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[System.Nullable`1[E_Byte],System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- Short Or Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) body { Or( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`3[System.Int16,System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- Short Or Short => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) body { ConvertChecked( Or( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Int16,System.Int16,System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Short? Or Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Int16 ) body { ConvertChecked( Or( Parameter( x type: System.Nullable`1[System.Int16] ) ConvertChecked( Parameter( y type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted type: System.Int16 ) } return type: System.Int16 type: System.Func`3[System.Nullable`1[System.Int16],System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- Short Or Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Nullable`1[System.Int16] ) body { Or( ConvertChecked( Parameter( x type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Int16,System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Short? Or Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Nullable`1[System.Int16] ) body { Or( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Nullable`1[System.Int16],System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- E_Short Or E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: E_Short ) body { Convert( Or( Convert( Parameter( x type: E_Short ) type: System.Int16 ) Convert( Parameter( y type: E_Short ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) } return type: E_Short type: System.Func`3[E_Short,E_Short,E_Short] ) -=-=-=-=-=-=-=-=- E_Short Or E_Short => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: E_Short ) body { ConvertChecked( Convert( Or( Convert( Parameter( x type: E_Short ) type: System.Int16 ) Convert( Parameter( y type: E_Short ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[E_Short,E_Short,System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- E_Short? Or E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) Parameter( y type: E_Short ) body { ConvertChecked( Convert( Or( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Convert( ConvertChecked( Parameter( y type: E_Short ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) Lifted type: E_Short ) } return type: E_Short type: System.Func`3[System.Nullable`1[E_Short],E_Short,E_Short] ) -=-=-=-=-=-=-=-=- E_Short Or E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: System.Nullable`1[E_Short] ) body { Convert( Or( Convert( ConvertChecked( Parameter( x type: E_Short ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Convert( Parameter( y type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[E_Short,System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- E_Short? Or E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) Parameter( y type: System.Nullable`1[E_Short] ) body { Convert( Or( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Convert( Parameter( y type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[System.Nullable`1[E_Short],System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- UShort Or UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) body { Or( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) type: System.UInt16 ) } return type: System.UInt16 type: System.Func`3[System.UInt16,System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- UShort Or UShort => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) body { ConvertChecked( Or( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) type: System.UInt16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.UInt16,System.UInt16,System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- UShort? Or UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.UInt16 ) body { ConvertChecked( Or( Parameter( x type: System.Nullable`1[System.UInt16] ) ConvertChecked( Parameter( y type: System.UInt16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted type: System.UInt16 ) } return type: System.UInt16 type: System.Func`3[System.Nullable`1[System.UInt16],System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- UShort Or UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.Nullable`1[System.UInt16] ) body { Or( ConvertChecked( Parameter( x type: System.UInt16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.UInt16,System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- UShort? Or UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.Nullable`1[System.UInt16] ) body { Or( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- E_UShort Or E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: E_UShort ) body { Convert( Or( Convert( Parameter( x type: E_UShort ) type: System.UInt16 ) Convert( Parameter( y type: E_UShort ) type: System.UInt16 ) type: System.UInt16 ) type: E_UShort ) } return type: E_UShort type: System.Func`3[E_UShort,E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- E_UShort Or E_UShort => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: E_UShort ) body { ConvertChecked( Convert( Or( Convert( Parameter( x type: E_UShort ) type: System.UInt16 ) Convert( Parameter( y type: E_UShort ) type: System.UInt16 ) type: System.UInt16 ) type: E_UShort ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[E_UShort,E_UShort,System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- E_UShort? Or E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) Parameter( y type: E_UShort ) body { ConvertChecked( Convert( Or( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Convert( ConvertChecked( Parameter( y type: E_UShort ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) Lifted type: E_UShort ) } return type: E_UShort type: System.Func`3[System.Nullable`1[E_UShort],E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- E_UShort Or E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: System.Nullable`1[E_UShort] ) body { Convert( Or( Convert( ConvertChecked( Parameter( x type: E_UShort ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Convert( Parameter( y type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[E_UShort,System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- E_UShort? Or E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) Parameter( y type: System.Nullable`1[E_UShort] ) body { Convert( Or( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Convert( Parameter( y type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[System.Nullable`1[E_UShort],System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- Integer Or Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) body { Or( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`3[System.Int32,System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- Integer Or Integer => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) body { ConvertChecked( Or( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Int32,System.Int32,System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Integer? Or Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Int32 ) body { ConvertChecked( Or( Parameter( x type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted type: System.Int32 ) } return type: System.Int32 type: System.Func`3[System.Nullable`1[System.Int32],System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- Integer Or Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Nullable`1[System.Int32] ) body { Or( ConvertChecked( Parameter( x type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Int32,System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Integer? Or Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Nullable`1[System.Int32] ) body { Or( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Nullable`1[System.Int32],System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- E_Integer Or E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: E_Integer ) body { Convert( Or( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) Convert( Parameter( y type: E_Integer ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) } return type: E_Integer type: System.Func`3[E_Integer,E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- E_Integer Or E_Integer => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: E_Integer ) body { ConvertChecked( Convert( Or( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) Convert( Parameter( y type: E_Integer ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[E_Integer,E_Integer,System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- E_Integer? Or E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) Parameter( y type: E_Integer ) body { ConvertChecked( Convert( Or( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Convert( ConvertChecked( Parameter( y type: E_Integer ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) Lifted type: E_Integer ) } return type: E_Integer type: System.Func`3[System.Nullable`1[E_Integer],E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- E_Integer Or E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: System.Nullable`1[E_Integer] ) body { Convert( Or( Convert( ConvertChecked( Parameter( x type: E_Integer ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Convert( Parameter( y type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[E_Integer,System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- E_Integer? Or E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) Parameter( y type: System.Nullable`1[E_Integer] ) body { Convert( Or( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Convert( Parameter( y type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[System.Nullable`1[E_Integer],System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- UInteger Or UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) body { Or( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) type: System.UInt32 ) } return type: System.UInt32 type: System.Func`3[System.UInt32,System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- UInteger Or UInteger => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) body { ConvertChecked( Or( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) type: System.UInt32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.UInt32,System.UInt32,System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- UInteger? Or UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.UInt32 ) body { ConvertChecked( Or( Parameter( x type: System.Nullable`1[System.UInt32] ) ConvertChecked( Parameter( y type: System.UInt32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted type: System.UInt32 ) } return type: System.UInt32 type: System.Func`3[System.Nullable`1[System.UInt32],System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- UInteger Or UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.Nullable`1[System.UInt32] ) body { Or( ConvertChecked( Parameter( x type: System.UInt32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.UInt32,System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- UInteger? Or UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.Nullable`1[System.UInt32] ) body { Or( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- E_UInteger Or E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: E_UInteger ) body { Convert( Or( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) Convert( Parameter( y type: E_UInteger ) type: System.UInt32 ) type: System.UInt32 ) type: E_UInteger ) } return type: E_UInteger type: System.Func`3[E_UInteger,E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- E_UInteger Or E_UInteger => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: E_UInteger ) body { ConvertChecked( Convert( Or( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) Convert( Parameter( y type: E_UInteger ) type: System.UInt32 ) type: System.UInt32 ) type: E_UInteger ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[E_UInteger,E_UInteger,System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- E_UInteger? Or E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) Parameter( y type: E_UInteger ) body { ConvertChecked( Convert( Or( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Convert( ConvertChecked( Parameter( y type: E_UInteger ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) Lifted type: E_UInteger ) } return type: E_UInteger type: System.Func`3[System.Nullable`1[E_UInteger],E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- E_UInteger Or E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: System.Nullable`1[E_UInteger] ) body { Convert( Or( Convert( ConvertChecked( Parameter( x type: E_UInteger ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Convert( Parameter( y type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[E_UInteger,System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- E_UInteger? Or E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) Parameter( y type: System.Nullable`1[E_UInteger] ) body { Convert( Or( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Convert( Parameter( y type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- Long Or Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) body { Or( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`3[System.Int64,System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- Long Or Long => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) body { ConvertChecked( Or( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Int64,System.Int64,System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Long? Or Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Int64 ) body { ConvertChecked( Or( Parameter( x type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted type: System.Int64 ) } return type: System.Int64 type: System.Func`3[System.Nullable`1[System.Int64],System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- Long Or Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Nullable`1[System.Int64] ) body { Or( ConvertChecked( Parameter( x type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Int64,System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Long? Or Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Nullable`1[System.Int64] ) body { Or( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Nullable`1[System.Int64],System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- E_Long Or E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: E_Long ) body { Convert( Or( Convert( Parameter( x type: E_Long ) type: System.Int64 ) Convert( Parameter( y type: E_Long ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) } return type: E_Long type: System.Func`3[E_Long,E_Long,E_Long] ) -=-=-=-=-=-=-=-=- E_Long Or E_Long => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: E_Long ) body { ConvertChecked( Convert( Or( Convert( Parameter( x type: E_Long ) type: System.Int64 ) Convert( Parameter( y type: E_Long ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[E_Long,E_Long,System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- E_Long? Or E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) Parameter( y type: E_Long ) body { ConvertChecked( Convert( Or( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Convert( ConvertChecked( Parameter( y type: E_Long ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) Lifted type: E_Long ) } return type: E_Long type: System.Func`3[System.Nullable`1[E_Long],E_Long,E_Long] ) -=-=-=-=-=-=-=-=- E_Long Or E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: System.Nullable`1[E_Long] ) body { Convert( Or( Convert( ConvertChecked( Parameter( x type: E_Long ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Convert( Parameter( y type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[E_Long,System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- E_Long? Or E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) Parameter( y type: System.Nullable`1[E_Long] ) body { Convert( Or( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Convert( Parameter( y type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[System.Nullable`1[E_Long],System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- ULong Or ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) body { Or( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) type: System.UInt64 ) } return type: System.UInt64 type: System.Func`3[System.UInt64,System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- ULong Or ULong => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) body { ConvertChecked( Or( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) type: System.UInt64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.UInt64,System.UInt64,System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- ULong? Or ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.UInt64 ) body { ConvertChecked( Or( Parameter( x type: System.Nullable`1[System.UInt64] ) ConvertChecked( Parameter( y type: System.UInt64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted type: System.UInt64 ) } return type: System.UInt64 type: System.Func`3[System.Nullable`1[System.UInt64],System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- ULong Or ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.Nullable`1[System.UInt64] ) body { Or( ConvertChecked( Parameter( x type: System.UInt64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.UInt64,System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- ULong? Or ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.Nullable`1[System.UInt64] ) body { Or( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- E_ULong Or E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: E_ULong ) body { Convert( Or( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) Convert( Parameter( y type: E_ULong ) type: System.UInt64 ) type: System.UInt64 ) type: E_ULong ) } return type: E_ULong type: System.Func`3[E_ULong,E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- E_ULong Or E_ULong => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: E_ULong ) body { ConvertChecked( Convert( Or( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) Convert( Parameter( y type: E_ULong ) type: System.UInt64 ) type: System.UInt64 ) type: E_ULong ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[E_ULong,E_ULong,System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- E_ULong? Or E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) Parameter( y type: E_ULong ) body { ConvertChecked( Convert( Or( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Convert( ConvertChecked( Parameter( y type: E_ULong ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) Lifted type: E_ULong ) } return type: E_ULong type: System.Func`3[System.Nullable`1[E_ULong],E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- E_ULong Or E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: System.Nullable`1[E_ULong] ) body { Convert( Or( Convert( ConvertChecked( Parameter( x type: E_ULong ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Convert( Parameter( y type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[E_ULong,System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- E_ULong? Or E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) Parameter( y type: System.Nullable`1[E_ULong] ) body { Convert( Or( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Convert( Parameter( y type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[System.Nullable`1[E_ULong],System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- Boolean Or Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) body { Or( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) type: System.Boolean ) } return type: System.Boolean type: System.Func`3[System.Boolean,System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- Boolean Or Boolean => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) body { Convert( Or( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Boolean,System.Boolean,System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Boolean? Or Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Boolean ) body { Convert( Or( Parameter( x type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Boolean ) } return type: System.Boolean type: System.Func`3[System.Nullable`1[System.Boolean],System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- Boolean Or Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Nullable`1[System.Boolean] ) body { Or( Convert( Parameter( x type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Boolean,System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Boolean? Or Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) body { Or( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Single Or Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Single ) body { Convert( Or( ConvertChecked( Parameter( x type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) ConvertChecked( Parameter( y type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Single ) } return type: System.Single type: System.Func`3[System.Single,System.Single,System.Single] ) -=-=-=-=-=-=-=-=- Single Or Single => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Single ) body { Convert( Convert( Or( ConvertChecked( Parameter( x type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) ConvertChecked( Parameter( y type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Single ) method: System.Nullable`1[System.Single] op_Implicit(Single) in System.Nullable`1[System.Single] type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Single,System.Single,System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Single? Or Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) Parameter( y type: System.Single ) body { Convert( ConvertChecked( Or( ConvertChecked( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) ConvertChecked( ConvertChecked( Parameter( y type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) type: System.Single ) } return type: System.Single type: System.Func`3[System.Nullable`1[System.Single],System.Single,System.Single] ) -=-=-=-=-=-=-=-=- Single Or Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Nullable`1[System.Single] ) body { Convert( Or( ConvertChecked( ConvertChecked( Parameter( x type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Single,System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Single? Or Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) Parameter( y type: System.Nullable`1[System.Single] ) body { Convert( Or( ConvertChecked( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Nullable`1[System.Single],System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Double Or Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Double ) body { Convert( Or( ConvertChecked( Parameter( x type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) ConvertChecked( Parameter( y type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Double ) } return type: System.Double type: System.Func`3[System.Double,System.Double,System.Double] ) -=-=-=-=-=-=-=-=- Double Or Double => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Double ) body { Convert( Convert( Or( ConvertChecked( Parameter( x type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) ConvertChecked( Parameter( y type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Double,System.Double,System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Double? Or Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) Parameter( y type: System.Double ) body { Convert( ConvertChecked( Or( ConvertChecked( Parameter( x type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) ConvertChecked( ConvertChecked( Parameter( y type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) type: System.Double ) } return type: System.Double type: System.Func`3[System.Nullable`1[System.Double],System.Double,System.Double] ) -=-=-=-=-=-=-=-=- Double Or Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Nullable`1[System.Double] ) body { Convert( Or( ConvertChecked( ConvertChecked( Parameter( x type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Double,System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Double? Or Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) Parameter( y type: System.Nullable`1[System.Double] ) body { Convert( Or( ConvertChecked( Parameter( x type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Nullable`1[System.Double],System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Decimal Or Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Decimal ) body { Convert( Or( ConvertChecked( Parameter( x type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) ConvertChecked( Parameter( y type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`3[System.Decimal,System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- Decimal Or Decimal => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Decimal ) body { Convert( Convert( Or( ConvertChecked( Parameter( x type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) ConvertChecked( Parameter( y type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) method: System.Nullable`1[System.Decimal] op_Implicit(System.Decimal) in System.Nullable`1[System.Decimal] type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Decimal,System.Decimal,System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Decimal? Or Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) Parameter( y type: System.Decimal ) body { Convert( ConvertChecked( Or( ConvertChecked( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) ConvertChecked( ConvertChecked( Parameter( y type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`3[System.Nullable`1[System.Decimal],System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- Decimal Or Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Nullable`1[System.Decimal] ) body { Convert( Or( ConvertChecked( ConvertChecked( Parameter( x type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Decimal,System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Decimal? Or Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) Parameter( y type: System.Nullable`1[System.Decimal] ) body { Convert( Or( ConvertChecked( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- String Or String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.String ) body { Convert( Or( ConvertChecked( Parameter( x type: System.String ) method: Int64 ToLong(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int64 ) ConvertChecked( Parameter( y type: System.String ) method: Int64 ToLong(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int64 ) type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.String,System.String] ) -=-=-=-=-=-=-=-=- Object Or Object => Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) Parameter( y type: System.Object ) body { Or( Parameter( x type: System.Object ) Parameter( y type: System.Object ) method: System.Object OrObject(System.Object, System.Object) in Microsoft.VisualBasic.CompilerServices.Operators type: System.Object ) } return type: System.Object type: System.Func`3[System.Object,System.Object,System.Object] ) -=-=-=-=-=-=-=-=- SByte Xor SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.SByte ) body { ConvertChecked( ExclusiveOr( ConvertChecked( Parameter( x type: System.SByte ) type: System.Int32 ) ConvertChecked( Parameter( y type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) } return type: System.SByte type: System.Func`3[System.SByte,System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- SByte Xor SByte => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.SByte ) body { ConvertChecked( ConvertChecked( ExclusiveOr( ConvertChecked( Parameter( x type: System.SByte ) type: System.Int32 ) ConvertChecked( Parameter( y type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.SByte,System.SByte,System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- SByte? Xor SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) Parameter( y type: System.SByte ) body { ConvertChecked( ConvertChecked( ExclusiveOr( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( ConvertChecked( Parameter( y type: System.SByte ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted type: System.SByte ) } return type: System.SByte type: System.Func`3[System.Nullable`1[System.SByte],System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- SByte Xor SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.Nullable`1[System.SByte] ) body { ConvertChecked( ExclusiveOr( ConvertChecked( ConvertChecked( Parameter( x type: System.SByte ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.SByte,System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- SByte? Xor SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) Parameter( y type: System.Nullable`1[System.SByte] ) body { ConvertChecked( ExclusiveOr( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.Nullable`1[System.SByte],System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- E_SByte Xor E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: E_SByte ) body { Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Convert( Parameter( x type: E_SByte ) type: System.SByte ) type: System.Int32 ) ConvertChecked( Convert( Parameter( y type: E_SByte ) type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) type: E_SByte ) } return type: E_SByte type: System.Func`3[E_SByte,E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- E_SByte Xor E_SByte => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: E_SByte ) body { ConvertChecked( Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Convert( Parameter( x type: E_SByte ) type: System.SByte ) type: System.Int32 ) ConvertChecked( Convert( Parameter( y type: E_SByte ) type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) type: E_SByte ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[E_SByte,E_SByte,System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- E_SByte? Xor E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: E_SByte ) body { ConvertChecked( Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( ConvertChecked( Parameter( y type: E_SByte ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) Lifted type: E_SByte ) } return type: E_SByte type: System.Func`3[System.Nullable`1[E_SByte],E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- E_SByte Xor E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Convert( ConvertChecked( Parameter( x type: E_SByte ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( Parameter( y type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[E_SByte,System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- E_SByte? Xor E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( Parameter( y type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[System.Nullable`1[E_SByte],System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- Byte Xor Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Byte ) body { ConvertChecked( ExclusiveOr( ConvertChecked( Parameter( x type: System.Byte ) type: System.Int32 ) ConvertChecked( Parameter( y type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) } return type: System.Byte type: System.Func`3[System.Byte,System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- Byte Xor Byte => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Byte ) body { ConvertChecked( ConvertChecked( ExclusiveOr( ConvertChecked( Parameter( x type: System.Byte ) type: System.Int32 ) ConvertChecked( Parameter( y type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Byte,System.Byte,System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Byte? Xor Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) Parameter( y type: System.Byte ) body { ConvertChecked( ConvertChecked( ExclusiveOr( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( ConvertChecked( Parameter( y type: System.Byte ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted type: System.Byte ) } return type: System.Byte type: System.Func`3[System.Nullable`1[System.Byte],System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- Byte Xor Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Nullable`1[System.Byte] ) body { ConvertChecked( ExclusiveOr( ConvertChecked( ConvertChecked( Parameter( x type: System.Byte ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Byte,System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Byte? Xor Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) Parameter( y type: System.Nullable`1[System.Byte] ) body { ConvertChecked( ExclusiveOr( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Nullable`1[System.Byte],System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- E_Byte Xor E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: E_Byte ) body { Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Convert( Parameter( x type: E_Byte ) type: System.Byte ) type: System.Int32 ) ConvertChecked( Convert( Parameter( y type: E_Byte ) type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) type: E_Byte ) } return type: E_Byte type: System.Func`3[E_Byte,E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- E_Byte Xor E_Byte => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: E_Byte ) body { ConvertChecked( Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Convert( Parameter( x type: E_Byte ) type: System.Byte ) type: System.Int32 ) ConvertChecked( Convert( Parameter( y type: E_Byte ) type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) type: E_Byte ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[E_Byte,E_Byte,System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- E_Byte? Xor E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) Parameter( y type: E_Byte ) body { ConvertChecked( Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( ConvertChecked( Parameter( y type: E_Byte ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) Lifted type: E_Byte ) } return type: E_Byte type: System.Func`3[System.Nullable`1[E_Byte],E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- E_Byte Xor E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Convert( ConvertChecked( Parameter( x type: E_Byte ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( Parameter( y type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[E_Byte,System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- E_Byte? Xor E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) Parameter( y type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( Parameter( y type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[System.Nullable`1[E_Byte],System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- Short Xor Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) body { ExclusiveOr( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`3[System.Int16,System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- Short Xor Short => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) body { ConvertChecked( ExclusiveOr( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Int16,System.Int16,System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Short? Xor Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Int16 ) body { ConvertChecked( ExclusiveOr( Parameter( x type: System.Nullable`1[System.Int16] ) ConvertChecked( Parameter( y type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted type: System.Int16 ) } return type: System.Int16 type: System.Func`3[System.Nullable`1[System.Int16],System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- Short Xor Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Nullable`1[System.Int16] ) body { ExclusiveOr( ConvertChecked( Parameter( x type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Int16,System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Short? Xor Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Nullable`1[System.Int16] ) body { ExclusiveOr( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Nullable`1[System.Int16],System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- E_Short Xor E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: E_Short ) body { Convert( ExclusiveOr( Convert( Parameter( x type: E_Short ) type: System.Int16 ) Convert( Parameter( y type: E_Short ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) } return type: E_Short type: System.Func`3[E_Short,E_Short,E_Short] ) -=-=-=-=-=-=-=-=- E_Short Xor E_Short => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: E_Short ) body { ConvertChecked( Convert( ExclusiveOr( Convert( Parameter( x type: E_Short ) type: System.Int16 ) Convert( Parameter( y type: E_Short ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[E_Short,E_Short,System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- E_Short? Xor E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) Parameter( y type: E_Short ) body { ConvertChecked( Convert( ExclusiveOr( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Convert( ConvertChecked( Parameter( y type: E_Short ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) Lifted type: E_Short ) } return type: E_Short type: System.Func`3[System.Nullable`1[E_Short],E_Short,E_Short] ) -=-=-=-=-=-=-=-=- E_Short Xor E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: System.Nullable`1[E_Short] ) body { Convert( ExclusiveOr( Convert( ConvertChecked( Parameter( x type: E_Short ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Convert( Parameter( y type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[E_Short,System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- E_Short? Xor E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) Parameter( y type: System.Nullable`1[E_Short] ) body { Convert( ExclusiveOr( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Convert( Parameter( y type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[System.Nullable`1[E_Short],System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- UShort Xor UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) body { ExclusiveOr( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) type: System.UInt16 ) } return type: System.UInt16 type: System.Func`3[System.UInt16,System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- UShort Xor UShort => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) body { ConvertChecked( ExclusiveOr( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) type: System.UInt16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.UInt16,System.UInt16,System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- UShort? Xor UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.UInt16 ) body { ConvertChecked( ExclusiveOr( Parameter( x type: System.Nullable`1[System.UInt16] ) ConvertChecked( Parameter( y type: System.UInt16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted type: System.UInt16 ) } return type: System.UInt16 type: System.Func`3[System.Nullable`1[System.UInt16],System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- UShort Xor UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.Nullable`1[System.UInt16] ) body { ExclusiveOr( ConvertChecked( Parameter( x type: System.UInt16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.UInt16,System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- UShort? Xor UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.Nullable`1[System.UInt16] ) body { ExclusiveOr( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- E_UShort Xor E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: E_UShort ) body { Convert( ExclusiveOr( Convert( Parameter( x type: E_UShort ) type: System.UInt16 ) Convert( Parameter( y type: E_UShort ) type: System.UInt16 ) type: System.UInt16 ) type: E_UShort ) } return type: E_UShort type: System.Func`3[E_UShort,E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- E_UShort Xor E_UShort => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: E_UShort ) body { ConvertChecked( Convert( ExclusiveOr( Convert( Parameter( x type: E_UShort ) type: System.UInt16 ) Convert( Parameter( y type: E_UShort ) type: System.UInt16 ) type: System.UInt16 ) type: E_UShort ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[E_UShort,E_UShort,System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- E_UShort? Xor E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) Parameter( y type: E_UShort ) body { ConvertChecked( Convert( ExclusiveOr( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Convert( ConvertChecked( Parameter( y type: E_UShort ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) Lifted type: E_UShort ) } return type: E_UShort type: System.Func`3[System.Nullable`1[E_UShort],E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- E_UShort Xor E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: System.Nullable`1[E_UShort] ) body { Convert( ExclusiveOr( Convert( ConvertChecked( Parameter( x type: E_UShort ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Convert( Parameter( y type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[E_UShort,System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- E_UShort? Xor E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) Parameter( y type: System.Nullable`1[E_UShort] ) body { Convert( ExclusiveOr( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Convert( Parameter( y type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[System.Nullable`1[E_UShort],System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- Integer Xor Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) body { ExclusiveOr( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`3[System.Int32,System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- Integer Xor Integer => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) body { ConvertChecked( ExclusiveOr( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Int32,System.Int32,System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Integer? Xor Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Int32 ) body { ConvertChecked( ExclusiveOr( Parameter( x type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted type: System.Int32 ) } return type: System.Int32 type: System.Func`3[System.Nullable`1[System.Int32],System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- Integer Xor Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Nullable`1[System.Int32] ) body { ExclusiveOr( ConvertChecked( Parameter( x type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Int32,System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Integer? Xor Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Nullable`1[System.Int32] ) body { ExclusiveOr( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Nullable`1[System.Int32],System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- E_Integer Xor E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: E_Integer ) body { Convert( ExclusiveOr( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) Convert( Parameter( y type: E_Integer ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) } return type: E_Integer type: System.Func`3[E_Integer,E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- E_Integer Xor E_Integer => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: E_Integer ) body { ConvertChecked( Convert( ExclusiveOr( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) Convert( Parameter( y type: E_Integer ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[E_Integer,E_Integer,System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- E_Integer? Xor E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) Parameter( y type: E_Integer ) body { ConvertChecked( Convert( ExclusiveOr( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Convert( ConvertChecked( Parameter( y type: E_Integer ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) Lifted type: E_Integer ) } return type: E_Integer type: System.Func`3[System.Nullable`1[E_Integer],E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- E_Integer Xor E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: System.Nullable`1[E_Integer] ) body { Convert( ExclusiveOr( Convert( ConvertChecked( Parameter( x type: E_Integer ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Convert( Parameter( y type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[E_Integer,System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- E_Integer? Xor E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) Parameter( y type: System.Nullable`1[E_Integer] ) body { Convert( ExclusiveOr( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Convert( Parameter( y type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[System.Nullable`1[E_Integer],System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- UInteger Xor UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) body { ExclusiveOr( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) type: System.UInt32 ) } return type: System.UInt32 type: System.Func`3[System.UInt32,System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- UInteger Xor UInteger => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) body { ConvertChecked( ExclusiveOr( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) type: System.UInt32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.UInt32,System.UInt32,System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- UInteger? Xor UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.UInt32 ) body { ConvertChecked( ExclusiveOr( Parameter( x type: System.Nullable`1[System.UInt32] ) ConvertChecked( Parameter( y type: System.UInt32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted type: System.UInt32 ) } return type: System.UInt32 type: System.Func`3[System.Nullable`1[System.UInt32],System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- UInteger Xor UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.Nullable`1[System.UInt32] ) body { ExclusiveOr( ConvertChecked( Parameter( x type: System.UInt32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.UInt32,System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- UInteger? Xor UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.Nullable`1[System.UInt32] ) body { ExclusiveOr( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- E_UInteger Xor E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: E_UInteger ) body { Convert( ExclusiveOr( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) Convert( Parameter( y type: E_UInteger ) type: System.UInt32 ) type: System.UInt32 ) type: E_UInteger ) } return type: E_UInteger type: System.Func`3[E_UInteger,E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- E_UInteger Xor E_UInteger => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: E_UInteger ) body { ConvertChecked( Convert( ExclusiveOr( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) Convert( Parameter( y type: E_UInteger ) type: System.UInt32 ) type: System.UInt32 ) type: E_UInteger ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[E_UInteger,E_UInteger,System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- E_UInteger? Xor E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) Parameter( y type: E_UInteger ) body { ConvertChecked( Convert( ExclusiveOr( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Convert( ConvertChecked( Parameter( y type: E_UInteger ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) Lifted type: E_UInteger ) } return type: E_UInteger type: System.Func`3[System.Nullable`1[E_UInteger],E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- E_UInteger Xor E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: System.Nullable`1[E_UInteger] ) body { Convert( ExclusiveOr( Convert( ConvertChecked( Parameter( x type: E_UInteger ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Convert( Parameter( y type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[E_UInteger,System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- E_UInteger? Xor E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) Parameter( y type: System.Nullable`1[E_UInteger] ) body { Convert( ExclusiveOr( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Convert( Parameter( y type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- Long Xor Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) body { ExclusiveOr( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`3[System.Int64,System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- Long Xor Long => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) body { ConvertChecked( ExclusiveOr( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Int64,System.Int64,System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Long? Xor Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Int64 ) body { ConvertChecked( ExclusiveOr( Parameter( x type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted type: System.Int64 ) } return type: System.Int64 type: System.Func`3[System.Nullable`1[System.Int64],System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- Long Xor Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Nullable`1[System.Int64] ) body { ExclusiveOr( ConvertChecked( Parameter( x type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Int64,System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Long? Xor Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Nullable`1[System.Int64] ) body { ExclusiveOr( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Nullable`1[System.Int64],System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- E_Long Xor E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: E_Long ) body { Convert( ExclusiveOr( Convert( Parameter( x type: E_Long ) type: System.Int64 ) Convert( Parameter( y type: E_Long ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) } return type: E_Long type: System.Func`3[E_Long,E_Long,E_Long] ) -=-=-=-=-=-=-=-=- E_Long Xor E_Long => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: E_Long ) body { ConvertChecked( Convert( ExclusiveOr( Convert( Parameter( x type: E_Long ) type: System.Int64 ) Convert( Parameter( y type: E_Long ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[E_Long,E_Long,System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- E_Long? Xor E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) Parameter( y type: E_Long ) body { ConvertChecked( Convert( ExclusiveOr( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Convert( ConvertChecked( Parameter( y type: E_Long ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) Lifted type: E_Long ) } return type: E_Long type: System.Func`3[System.Nullable`1[E_Long],E_Long,E_Long] ) -=-=-=-=-=-=-=-=- E_Long Xor E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: System.Nullable`1[E_Long] ) body { Convert( ExclusiveOr( Convert( ConvertChecked( Parameter( x type: E_Long ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Convert( Parameter( y type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[E_Long,System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- E_Long? Xor E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) Parameter( y type: System.Nullable`1[E_Long] ) body { Convert( ExclusiveOr( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Convert( Parameter( y type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[System.Nullable`1[E_Long],System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- ULong Xor ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) body { ExclusiveOr( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) type: System.UInt64 ) } return type: System.UInt64 type: System.Func`3[System.UInt64,System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- ULong Xor ULong => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) body { ConvertChecked( ExclusiveOr( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) type: System.UInt64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.UInt64,System.UInt64,System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- ULong? Xor ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.UInt64 ) body { ConvertChecked( ExclusiveOr( Parameter( x type: System.Nullable`1[System.UInt64] ) ConvertChecked( Parameter( y type: System.UInt64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted type: System.UInt64 ) } return type: System.UInt64 type: System.Func`3[System.Nullable`1[System.UInt64],System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- ULong Xor ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.Nullable`1[System.UInt64] ) body { ExclusiveOr( ConvertChecked( Parameter( x type: System.UInt64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.UInt64,System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- ULong? Xor ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.Nullable`1[System.UInt64] ) body { ExclusiveOr( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- E_ULong Xor E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: E_ULong ) body { Convert( ExclusiveOr( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) Convert( Parameter( y type: E_ULong ) type: System.UInt64 ) type: System.UInt64 ) type: E_ULong ) } return type: E_ULong type: System.Func`3[E_ULong,E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- E_ULong Xor E_ULong => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: E_ULong ) body { ConvertChecked( Convert( ExclusiveOr( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) Convert( Parameter( y type: E_ULong ) type: System.UInt64 ) type: System.UInt64 ) type: E_ULong ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[E_ULong,E_ULong,System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- E_ULong? Xor E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) Parameter( y type: E_ULong ) body { ConvertChecked( Convert( ExclusiveOr( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Convert( ConvertChecked( Parameter( y type: E_ULong ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) Lifted type: E_ULong ) } return type: E_ULong type: System.Func`3[System.Nullable`1[E_ULong],E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- E_ULong Xor E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: System.Nullable`1[E_ULong] ) body { Convert( ExclusiveOr( Convert( ConvertChecked( Parameter( x type: E_ULong ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Convert( Parameter( y type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[E_ULong,System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- E_ULong? Xor E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) Parameter( y type: System.Nullable`1[E_ULong] ) body { Convert( ExclusiveOr( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Convert( Parameter( y type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[System.Nullable`1[E_ULong],System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- Boolean Xor Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) body { ExclusiveOr( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) type: System.Boolean ) } return type: System.Boolean type: System.Func`3[System.Boolean,System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- Boolean Xor Boolean => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) body { Convert( ExclusiveOr( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Boolean,System.Boolean,System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Boolean? Xor Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Boolean ) body { Convert( ExclusiveOr( Parameter( x type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Boolean ) } return type: System.Boolean type: System.Func`3[System.Nullable`1[System.Boolean],System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- Boolean Xor Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Nullable`1[System.Boolean] ) body { ExclusiveOr( Convert( Parameter( x type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Boolean,System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Boolean? Xor Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) body { ExclusiveOr( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Single Xor Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Single ) body { Convert( ExclusiveOr( ConvertChecked( Parameter( x type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) ConvertChecked( Parameter( y type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Single ) } return type: System.Single type: System.Func`3[System.Single,System.Single,System.Single] ) -=-=-=-=-=-=-=-=- Single Xor Single => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Single ) body { Convert( Convert( ExclusiveOr( ConvertChecked( Parameter( x type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) ConvertChecked( Parameter( y type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Single ) method: System.Nullable`1[System.Single] op_Implicit(Single) in System.Nullable`1[System.Single] type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Single,System.Single,System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Single? Xor Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) Parameter( y type: System.Single ) body { Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) ConvertChecked( ConvertChecked( Parameter( y type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) type: System.Single ) } return type: System.Single type: System.Func`3[System.Nullable`1[System.Single],System.Single,System.Single] ) -=-=-=-=-=-=-=-=- Single Xor Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Nullable`1[System.Single] ) body { Convert( ExclusiveOr( ConvertChecked( ConvertChecked( Parameter( x type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Single,System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Single? Xor Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) Parameter( y type: System.Nullable`1[System.Single] ) body { Convert( ExclusiveOr( ConvertChecked( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Nullable`1[System.Single],System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Double Xor Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Double ) body { Convert( ExclusiveOr( ConvertChecked( Parameter( x type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) ConvertChecked( Parameter( y type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Double ) } return type: System.Double type: System.Func`3[System.Double,System.Double,System.Double] ) -=-=-=-=-=-=-=-=- Double Xor Double => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Double ) body { Convert( Convert( ExclusiveOr( ConvertChecked( Parameter( x type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) ConvertChecked( Parameter( y type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Double,System.Double,System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Double? Xor Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) Parameter( y type: System.Double ) body { Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Parameter( x type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) ConvertChecked( ConvertChecked( Parameter( y type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) type: System.Double ) } return type: System.Double type: System.Func`3[System.Nullable`1[System.Double],System.Double,System.Double] ) -=-=-=-=-=-=-=-=- Double Xor Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Nullable`1[System.Double] ) body { Convert( ExclusiveOr( ConvertChecked( ConvertChecked( Parameter( x type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Double,System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Double? Xor Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) Parameter( y type: System.Nullable`1[System.Double] ) body { Convert( ExclusiveOr( ConvertChecked( Parameter( x type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Nullable`1[System.Double],System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Decimal Xor Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Decimal ) body { Convert( ExclusiveOr( ConvertChecked( Parameter( x type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) ConvertChecked( Parameter( y type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`3[System.Decimal,System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- Decimal Xor Decimal => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Decimal ) body { Convert( Convert( ExclusiveOr( ConvertChecked( Parameter( x type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) ConvertChecked( Parameter( y type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) method: System.Nullable`1[System.Decimal] op_Implicit(System.Decimal) in System.Nullable`1[System.Decimal] type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Decimal,System.Decimal,System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Decimal? Xor Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) Parameter( y type: System.Decimal ) body { Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) ConvertChecked( ConvertChecked( Parameter( y type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`3[System.Nullable`1[System.Decimal],System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- Decimal Xor Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Nullable`1[System.Decimal] ) body { Convert( ExclusiveOr( ConvertChecked( ConvertChecked( Parameter( x type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Decimal,System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Decimal? Xor Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) Parameter( y type: System.Nullable`1[System.Decimal] ) body { Convert( ExclusiveOr( ConvertChecked( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- String Xor String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.String ) body { Convert( ExclusiveOr( ConvertChecked( Parameter( x type: System.String ) method: Int64 ToLong(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int64 ) ConvertChecked( Parameter( y type: System.String ) method: Int64 ToLong(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int64 ) type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.String,System.String] ) -=-=-=-=-=-=-=-=- Object Xor Object => Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) Parameter( y type: System.Object ) body { ExclusiveOr( Parameter( x type: System.Object ) Parameter( y type: System.Object ) method: System.Object XorObject(System.Object, System.Object) in Microsoft.VisualBasic.CompilerServices.Operators type: System.Object ) } return type: System.Object type: System.Func`3[System.Object,System.Object,System.Object] )
-=-=-=-=-=-=-=-=- SByte And SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.SByte ) body { ConvertChecked( And( ConvertChecked( Parameter( x type: System.SByte ) type: System.Int32 ) ConvertChecked( Parameter( y type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) } return type: System.SByte type: System.Func`3[System.SByte,System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- SByte And SByte => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.SByte ) body { ConvertChecked( ConvertChecked( And( ConvertChecked( Parameter( x type: System.SByte ) type: System.Int32 ) ConvertChecked( Parameter( y type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.SByte,System.SByte,System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- SByte? And SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) Parameter( y type: System.SByte ) body { ConvertChecked( ConvertChecked( And( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( ConvertChecked( Parameter( y type: System.SByte ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted type: System.SByte ) } return type: System.SByte type: System.Func`3[System.Nullable`1[System.SByte],System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- SByte And SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.Nullable`1[System.SByte] ) body { ConvertChecked( And( ConvertChecked( ConvertChecked( Parameter( x type: System.SByte ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.SByte,System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- SByte? And SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) Parameter( y type: System.Nullable`1[System.SByte] ) body { ConvertChecked( And( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.Nullable`1[System.SByte],System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- E_SByte And E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: E_SByte ) body { Convert( ConvertChecked( And( ConvertChecked( Convert( Parameter( x type: E_SByte ) type: System.SByte ) type: System.Int32 ) ConvertChecked( Convert( Parameter( y type: E_SByte ) type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) type: E_SByte ) } return type: E_SByte type: System.Func`3[E_SByte,E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- E_SByte And E_SByte => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: E_SByte ) body { ConvertChecked( Convert( ConvertChecked( And( ConvertChecked( Convert( Parameter( x type: E_SByte ) type: System.SByte ) type: System.Int32 ) ConvertChecked( Convert( Parameter( y type: E_SByte ) type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) type: E_SByte ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[E_SByte,E_SByte,System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- E_SByte? And E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: E_SByte ) body { ConvertChecked( Convert( ConvertChecked( And( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( ConvertChecked( Parameter( y type: E_SByte ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) Lifted type: E_SByte ) } return type: E_SByte type: System.Func`3[System.Nullable`1[E_SByte],E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- E_SByte And E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( And( ConvertChecked( Convert( ConvertChecked( Parameter( x type: E_SByte ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( Parameter( y type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[E_SByte,System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- E_SByte? And E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( And( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( Parameter( y type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[System.Nullable`1[E_SByte],System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- Byte And Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Byte ) body { ConvertChecked( And( ConvertChecked( Parameter( x type: System.Byte ) type: System.Int32 ) ConvertChecked( Parameter( y type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) } return type: System.Byte type: System.Func`3[System.Byte,System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- Byte And Byte => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Byte ) body { ConvertChecked( ConvertChecked( And( ConvertChecked( Parameter( x type: System.Byte ) type: System.Int32 ) ConvertChecked( Parameter( y type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Byte,System.Byte,System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Byte? And Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) Parameter( y type: System.Byte ) body { ConvertChecked( ConvertChecked( And( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( ConvertChecked( Parameter( y type: System.Byte ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted type: System.Byte ) } return type: System.Byte type: System.Func`3[System.Nullable`1[System.Byte],System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- Byte And Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Nullable`1[System.Byte] ) body { ConvertChecked( And( ConvertChecked( ConvertChecked( Parameter( x type: System.Byte ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Byte,System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Byte? And Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) Parameter( y type: System.Nullable`1[System.Byte] ) body { ConvertChecked( And( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Nullable`1[System.Byte],System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- E_Byte And E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: E_Byte ) body { Convert( ConvertChecked( And( ConvertChecked( Convert( Parameter( x type: E_Byte ) type: System.Byte ) type: System.Int32 ) ConvertChecked( Convert( Parameter( y type: E_Byte ) type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) type: E_Byte ) } return type: E_Byte type: System.Func`3[E_Byte,E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- E_Byte And E_Byte => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: E_Byte ) body { ConvertChecked( Convert( ConvertChecked( And( ConvertChecked( Convert( Parameter( x type: E_Byte ) type: System.Byte ) type: System.Int32 ) ConvertChecked( Convert( Parameter( y type: E_Byte ) type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) type: E_Byte ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[E_Byte,E_Byte,System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- E_Byte? And E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) Parameter( y type: E_Byte ) body { ConvertChecked( Convert( ConvertChecked( And( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( ConvertChecked( Parameter( y type: E_Byte ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) Lifted type: E_Byte ) } return type: E_Byte type: System.Func`3[System.Nullable`1[E_Byte],E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- E_Byte And E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( And( ConvertChecked( Convert( ConvertChecked( Parameter( x type: E_Byte ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( Parameter( y type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[E_Byte,System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- E_Byte? And E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) Parameter( y type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( And( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( Parameter( y type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[System.Nullable`1[E_Byte],System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- Short And Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) body { And( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`3[System.Int16,System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- Short And Short => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) body { ConvertChecked( And( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Int16,System.Int16,System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Short? And Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Int16 ) body { ConvertChecked( And( Parameter( x type: System.Nullable`1[System.Int16] ) ConvertChecked( Parameter( y type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted type: System.Int16 ) } return type: System.Int16 type: System.Func`3[System.Nullable`1[System.Int16],System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- Short And Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Nullable`1[System.Int16] ) body { And( ConvertChecked( Parameter( x type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Int16,System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Short? And Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Nullable`1[System.Int16] ) body { And( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Nullable`1[System.Int16],System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- E_Short And E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: E_Short ) body { Convert( And( Convert( Parameter( x type: E_Short ) type: System.Int16 ) Convert( Parameter( y type: E_Short ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) } return type: E_Short type: System.Func`3[E_Short,E_Short,E_Short] ) -=-=-=-=-=-=-=-=- E_Short And E_Short => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: E_Short ) body { ConvertChecked( Convert( And( Convert( Parameter( x type: E_Short ) type: System.Int16 ) Convert( Parameter( y type: E_Short ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[E_Short,E_Short,System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- E_Short? And E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) Parameter( y type: E_Short ) body { ConvertChecked( Convert( And( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Convert( ConvertChecked( Parameter( y type: E_Short ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) Lifted type: E_Short ) } return type: E_Short type: System.Func`3[System.Nullable`1[E_Short],E_Short,E_Short] ) -=-=-=-=-=-=-=-=- E_Short And E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: System.Nullable`1[E_Short] ) body { Convert( And( Convert( ConvertChecked( Parameter( x type: E_Short ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Convert( Parameter( y type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[E_Short,System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- E_Short? And E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) Parameter( y type: System.Nullable`1[E_Short] ) body { Convert( And( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Convert( Parameter( y type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[System.Nullable`1[E_Short],System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- UShort And UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) body { And( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) type: System.UInt16 ) } return type: System.UInt16 type: System.Func`3[System.UInt16,System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- UShort And UShort => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) body { ConvertChecked( And( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) type: System.UInt16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.UInt16,System.UInt16,System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- UShort? And UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.UInt16 ) body { ConvertChecked( And( Parameter( x type: System.Nullable`1[System.UInt16] ) ConvertChecked( Parameter( y type: System.UInt16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted type: System.UInt16 ) } return type: System.UInt16 type: System.Func`3[System.Nullable`1[System.UInt16],System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- UShort And UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.Nullable`1[System.UInt16] ) body { And( ConvertChecked( Parameter( x type: System.UInt16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.UInt16,System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- UShort? And UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.Nullable`1[System.UInt16] ) body { And( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- E_UShort And E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: E_UShort ) body { Convert( And( Convert( Parameter( x type: E_UShort ) type: System.UInt16 ) Convert( Parameter( y type: E_UShort ) type: System.UInt16 ) type: System.UInt16 ) type: E_UShort ) } return type: E_UShort type: System.Func`3[E_UShort,E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- E_UShort And E_UShort => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: E_UShort ) body { ConvertChecked( Convert( And( Convert( Parameter( x type: E_UShort ) type: System.UInt16 ) Convert( Parameter( y type: E_UShort ) type: System.UInt16 ) type: System.UInt16 ) type: E_UShort ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[E_UShort,E_UShort,System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- E_UShort? And E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) Parameter( y type: E_UShort ) body { ConvertChecked( Convert( And( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Convert( ConvertChecked( Parameter( y type: E_UShort ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) Lifted type: E_UShort ) } return type: E_UShort type: System.Func`3[System.Nullable`1[E_UShort],E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- E_UShort And E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: System.Nullable`1[E_UShort] ) body { Convert( And( Convert( ConvertChecked( Parameter( x type: E_UShort ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Convert( Parameter( y type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[E_UShort,System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- E_UShort? And E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) Parameter( y type: System.Nullable`1[E_UShort] ) body { Convert( And( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Convert( Parameter( y type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[System.Nullable`1[E_UShort],System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- Integer And Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) body { And( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`3[System.Int32,System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- Integer And Integer => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) body { ConvertChecked( And( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Int32,System.Int32,System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Integer? And Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Int32 ) body { ConvertChecked( And( Parameter( x type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted type: System.Int32 ) } return type: System.Int32 type: System.Func`3[System.Nullable`1[System.Int32],System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- Integer And Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Nullable`1[System.Int32] ) body { And( ConvertChecked( Parameter( x type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Int32,System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Integer? And Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Nullable`1[System.Int32] ) body { And( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Nullable`1[System.Int32],System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- E_Integer And E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: E_Integer ) body { Convert( And( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) Convert( Parameter( y type: E_Integer ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) } return type: E_Integer type: System.Func`3[E_Integer,E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- E_Integer And E_Integer => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: E_Integer ) body { ConvertChecked( Convert( And( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) Convert( Parameter( y type: E_Integer ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[E_Integer,E_Integer,System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- E_Integer? And E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) Parameter( y type: E_Integer ) body { ConvertChecked( Convert( And( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Convert( ConvertChecked( Parameter( y type: E_Integer ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) Lifted type: E_Integer ) } return type: E_Integer type: System.Func`3[System.Nullable`1[E_Integer],E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- E_Integer And E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: System.Nullable`1[E_Integer] ) body { Convert( And( Convert( ConvertChecked( Parameter( x type: E_Integer ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Convert( Parameter( y type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[E_Integer,System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- E_Integer? And E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) Parameter( y type: System.Nullable`1[E_Integer] ) body { Convert( And( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Convert( Parameter( y type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[System.Nullable`1[E_Integer],System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- UInteger And UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) body { And( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) type: System.UInt32 ) } return type: System.UInt32 type: System.Func`3[System.UInt32,System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- UInteger And UInteger => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) body { ConvertChecked( And( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) type: System.UInt32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.UInt32,System.UInt32,System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- UInteger? And UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.UInt32 ) body { ConvertChecked( And( Parameter( x type: System.Nullable`1[System.UInt32] ) ConvertChecked( Parameter( y type: System.UInt32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted type: System.UInt32 ) } return type: System.UInt32 type: System.Func`3[System.Nullable`1[System.UInt32],System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- UInteger And UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.Nullable`1[System.UInt32] ) body { And( ConvertChecked( Parameter( x type: System.UInt32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.UInt32,System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- UInteger? And UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.Nullable`1[System.UInt32] ) body { And( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- E_UInteger And E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: E_UInteger ) body { Convert( And( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) Convert( Parameter( y type: E_UInteger ) type: System.UInt32 ) type: System.UInt32 ) type: E_UInteger ) } return type: E_UInteger type: System.Func`3[E_UInteger,E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- E_UInteger And E_UInteger => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: E_UInteger ) body { ConvertChecked( Convert( And( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) Convert( Parameter( y type: E_UInteger ) type: System.UInt32 ) type: System.UInt32 ) type: E_UInteger ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[E_UInteger,E_UInteger,System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- E_UInteger? And E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) Parameter( y type: E_UInteger ) body { ConvertChecked( Convert( And( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Convert( ConvertChecked( Parameter( y type: E_UInteger ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) Lifted type: E_UInteger ) } return type: E_UInteger type: System.Func`3[System.Nullable`1[E_UInteger],E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- E_UInteger And E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: System.Nullable`1[E_UInteger] ) body { Convert( And( Convert( ConvertChecked( Parameter( x type: E_UInteger ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Convert( Parameter( y type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[E_UInteger,System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- E_UInteger? And E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) Parameter( y type: System.Nullable`1[E_UInteger] ) body { Convert( And( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Convert( Parameter( y type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- Long And Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) body { And( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`3[System.Int64,System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- Long And Long => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) body { ConvertChecked( And( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Int64,System.Int64,System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Long? And Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Int64 ) body { ConvertChecked( And( Parameter( x type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted type: System.Int64 ) } return type: System.Int64 type: System.Func`3[System.Nullable`1[System.Int64],System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- Long And Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Nullable`1[System.Int64] ) body { And( ConvertChecked( Parameter( x type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Int64,System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Long? And Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Nullable`1[System.Int64] ) body { And( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Nullable`1[System.Int64],System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- E_Long And E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: E_Long ) body { Convert( And( Convert( Parameter( x type: E_Long ) type: System.Int64 ) Convert( Parameter( y type: E_Long ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) } return type: E_Long type: System.Func`3[E_Long,E_Long,E_Long] ) -=-=-=-=-=-=-=-=- E_Long And E_Long => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: E_Long ) body { ConvertChecked( Convert( And( Convert( Parameter( x type: E_Long ) type: System.Int64 ) Convert( Parameter( y type: E_Long ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[E_Long,E_Long,System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- E_Long? And E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) Parameter( y type: E_Long ) body { ConvertChecked( Convert( And( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Convert( ConvertChecked( Parameter( y type: E_Long ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) Lifted type: E_Long ) } return type: E_Long type: System.Func`3[System.Nullable`1[E_Long],E_Long,E_Long] ) -=-=-=-=-=-=-=-=- E_Long And E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: System.Nullable`1[E_Long] ) body { Convert( And( Convert( ConvertChecked( Parameter( x type: E_Long ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Convert( Parameter( y type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[E_Long,System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- E_Long? And E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) Parameter( y type: System.Nullable`1[E_Long] ) body { Convert( And( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Convert( Parameter( y type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[System.Nullable`1[E_Long],System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- ULong And ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) body { And( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) type: System.UInt64 ) } return type: System.UInt64 type: System.Func`3[System.UInt64,System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- ULong And ULong => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) body { ConvertChecked( And( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) type: System.UInt64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.UInt64,System.UInt64,System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- ULong? And ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.UInt64 ) body { ConvertChecked( And( Parameter( x type: System.Nullable`1[System.UInt64] ) ConvertChecked( Parameter( y type: System.UInt64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted type: System.UInt64 ) } return type: System.UInt64 type: System.Func`3[System.Nullable`1[System.UInt64],System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- ULong And ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.Nullable`1[System.UInt64] ) body { And( ConvertChecked( Parameter( x type: System.UInt64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.UInt64,System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- ULong? And ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.Nullable`1[System.UInt64] ) body { And( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- E_ULong And E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: E_ULong ) body { Convert( And( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) Convert( Parameter( y type: E_ULong ) type: System.UInt64 ) type: System.UInt64 ) type: E_ULong ) } return type: E_ULong type: System.Func`3[E_ULong,E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- E_ULong And E_ULong => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: E_ULong ) body { ConvertChecked( Convert( And( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) Convert( Parameter( y type: E_ULong ) type: System.UInt64 ) type: System.UInt64 ) type: E_ULong ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[E_ULong,E_ULong,System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- E_ULong? And E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) Parameter( y type: E_ULong ) body { ConvertChecked( Convert( And( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Convert( ConvertChecked( Parameter( y type: E_ULong ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) Lifted type: E_ULong ) } return type: E_ULong type: System.Func`3[System.Nullable`1[E_ULong],E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- E_ULong And E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: System.Nullable`1[E_ULong] ) body { Convert( And( Convert( ConvertChecked( Parameter( x type: E_ULong ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Convert( Parameter( y type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[E_ULong,System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- E_ULong? And E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) Parameter( y type: System.Nullable`1[E_ULong] ) body { Convert( And( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Convert( Parameter( y type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[System.Nullable`1[E_ULong],System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- Boolean And Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) body { And( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) type: System.Boolean ) } return type: System.Boolean type: System.Func`3[System.Boolean,System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- Boolean And Boolean => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) body { Convert( And( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Boolean,System.Boolean,System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Boolean? And Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Boolean ) body { Convert( And( Parameter( x type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Boolean ) } return type: System.Boolean type: System.Func`3[System.Nullable`1[System.Boolean],System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- Boolean And Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Nullable`1[System.Boolean] ) body { And( Convert( Parameter( x type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Boolean,System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Boolean? And Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) body { And( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Single And Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Single ) body { Convert( And( ConvertChecked( Parameter( x type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) ConvertChecked( Parameter( y type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Single ) } return type: System.Single type: System.Func`3[System.Single,System.Single,System.Single] ) -=-=-=-=-=-=-=-=- Single And Single => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Single ) body { Convert( Convert( And( ConvertChecked( Parameter( x type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) ConvertChecked( Parameter( y type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Single ) method: System.Nullable`1[System.Single] op_Implicit(Single) in System.Nullable`1[System.Single] type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Single,System.Single,System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Single? And Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) Parameter( y type: System.Single ) body { Convert( ConvertChecked( And( ConvertChecked( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) ConvertChecked( ConvertChecked( Parameter( y type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) type: System.Single ) } return type: System.Single type: System.Func`3[System.Nullable`1[System.Single],System.Single,System.Single] ) -=-=-=-=-=-=-=-=- Single And Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Nullable`1[System.Single] ) body { Convert( And( ConvertChecked( ConvertChecked( Parameter( x type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Single,System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Single? And Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) Parameter( y type: System.Nullable`1[System.Single] ) body { Convert( And( ConvertChecked( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Nullable`1[System.Single],System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Double And Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Double ) body { Convert( And( ConvertChecked( Parameter( x type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) ConvertChecked( Parameter( y type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Double ) } return type: System.Double type: System.Func`3[System.Double,System.Double,System.Double] ) -=-=-=-=-=-=-=-=- Double And Double => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Double ) body { Convert( Convert( And( ConvertChecked( Parameter( x type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) ConvertChecked( Parameter( y type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Double,System.Double,System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Double? And Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) Parameter( y type: System.Double ) body { Convert( ConvertChecked( And( ConvertChecked( Parameter( x type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) ConvertChecked( ConvertChecked( Parameter( y type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) type: System.Double ) } return type: System.Double type: System.Func`3[System.Nullable`1[System.Double],System.Double,System.Double] ) -=-=-=-=-=-=-=-=- Double And Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Nullable`1[System.Double] ) body { Convert( And( ConvertChecked( ConvertChecked( Parameter( x type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Double,System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Double? And Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) Parameter( y type: System.Nullable`1[System.Double] ) body { Convert( And( ConvertChecked( Parameter( x type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Nullable`1[System.Double],System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Decimal And Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Decimal ) body { Convert( And( ConvertChecked( Parameter( x type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) ConvertChecked( Parameter( y type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`3[System.Decimal,System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- Decimal And Decimal => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Decimal ) body { Convert( Convert( And( ConvertChecked( Parameter( x type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) ConvertChecked( Parameter( y type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) method: System.Nullable`1[System.Decimal] op_Implicit(System.Decimal) in System.Nullable`1[System.Decimal] type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Decimal,System.Decimal,System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Decimal? And Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) Parameter( y type: System.Decimal ) body { Convert( ConvertChecked( And( ConvertChecked( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) ConvertChecked( ConvertChecked( Parameter( y type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`3[System.Nullable`1[System.Decimal],System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- Decimal And Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Nullable`1[System.Decimal] ) body { Convert( And( ConvertChecked( ConvertChecked( Parameter( x type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Decimal,System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Decimal? And Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) Parameter( y type: System.Nullable`1[System.Decimal] ) body { Convert( And( ConvertChecked( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- String And String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.String ) body { Convert( And( ConvertChecked( Parameter( x type: System.String ) method: Int64 ToLong(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int64 ) ConvertChecked( Parameter( y type: System.String ) method: Int64 ToLong(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int64 ) type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.String,System.String] ) -=-=-=-=-=-=-=-=- Object And Object => Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) Parameter( y type: System.Object ) body { And( Parameter( x type: System.Object ) Parameter( y type: System.Object ) method: System.Object AndObject(System.Object, System.Object) in Microsoft.VisualBasic.CompilerServices.Operators type: System.Object ) } return type: System.Object type: System.Func`3[System.Object,System.Object,System.Object] ) -=-=-=-=-=-=-=-=- SByte Or SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.SByte ) body { ConvertChecked( Or( ConvertChecked( Parameter( x type: System.SByte ) type: System.Int32 ) ConvertChecked( Parameter( y type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) } return type: System.SByte type: System.Func`3[System.SByte,System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- SByte Or SByte => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.SByte ) body { ConvertChecked( ConvertChecked( Or( ConvertChecked( Parameter( x type: System.SByte ) type: System.Int32 ) ConvertChecked( Parameter( y type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.SByte,System.SByte,System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- SByte? Or SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) Parameter( y type: System.SByte ) body { ConvertChecked( ConvertChecked( Or( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( ConvertChecked( Parameter( y type: System.SByte ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted type: System.SByte ) } return type: System.SByte type: System.Func`3[System.Nullable`1[System.SByte],System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- SByte Or SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.Nullable`1[System.SByte] ) body { ConvertChecked( Or( ConvertChecked( ConvertChecked( Parameter( x type: System.SByte ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.SByte,System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- SByte? Or SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) Parameter( y type: System.Nullable`1[System.SByte] ) body { ConvertChecked( Or( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.Nullable`1[System.SByte],System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- E_SByte Or E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: E_SByte ) body { Convert( ConvertChecked( Or( ConvertChecked( Convert( Parameter( x type: E_SByte ) type: System.SByte ) type: System.Int32 ) ConvertChecked( Convert( Parameter( y type: E_SByte ) type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) type: E_SByte ) } return type: E_SByte type: System.Func`3[E_SByte,E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- E_SByte Or E_SByte => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: E_SByte ) body { ConvertChecked( Convert( ConvertChecked( Or( ConvertChecked( Convert( Parameter( x type: E_SByte ) type: System.SByte ) type: System.Int32 ) ConvertChecked( Convert( Parameter( y type: E_SByte ) type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) type: E_SByte ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[E_SByte,E_SByte,System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- E_SByte? Or E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: E_SByte ) body { ConvertChecked( Convert( ConvertChecked( Or( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( ConvertChecked( Parameter( y type: E_SByte ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) Lifted type: E_SByte ) } return type: E_SByte type: System.Func`3[System.Nullable`1[E_SByte],E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- E_SByte Or E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( Or( ConvertChecked( Convert( ConvertChecked( Parameter( x type: E_SByte ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( Parameter( y type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[E_SByte,System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- E_SByte? Or E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( Or( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( Parameter( y type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[System.Nullable`1[E_SByte],System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- Byte Or Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Byte ) body { ConvertChecked( Or( ConvertChecked( Parameter( x type: System.Byte ) type: System.Int32 ) ConvertChecked( Parameter( y type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) } return type: System.Byte type: System.Func`3[System.Byte,System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- Byte Or Byte => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Byte ) body { ConvertChecked( ConvertChecked( Or( ConvertChecked( Parameter( x type: System.Byte ) type: System.Int32 ) ConvertChecked( Parameter( y type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Byte,System.Byte,System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Byte? Or Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) Parameter( y type: System.Byte ) body { ConvertChecked( ConvertChecked( Or( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( ConvertChecked( Parameter( y type: System.Byte ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted type: System.Byte ) } return type: System.Byte type: System.Func`3[System.Nullable`1[System.Byte],System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- Byte Or Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Nullable`1[System.Byte] ) body { ConvertChecked( Or( ConvertChecked( ConvertChecked( Parameter( x type: System.Byte ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Byte,System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Byte? Or Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) Parameter( y type: System.Nullable`1[System.Byte] ) body { ConvertChecked( Or( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Nullable`1[System.Byte],System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- E_Byte Or E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: E_Byte ) body { Convert( ConvertChecked( Or( ConvertChecked( Convert( Parameter( x type: E_Byte ) type: System.Byte ) type: System.Int32 ) ConvertChecked( Convert( Parameter( y type: E_Byte ) type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) type: E_Byte ) } return type: E_Byte type: System.Func`3[E_Byte,E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- E_Byte Or E_Byte => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: E_Byte ) body { ConvertChecked( Convert( ConvertChecked( Or( ConvertChecked( Convert( Parameter( x type: E_Byte ) type: System.Byte ) type: System.Int32 ) ConvertChecked( Convert( Parameter( y type: E_Byte ) type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) type: E_Byte ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[E_Byte,E_Byte,System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- E_Byte? Or E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) Parameter( y type: E_Byte ) body { ConvertChecked( Convert( ConvertChecked( Or( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( ConvertChecked( Parameter( y type: E_Byte ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) Lifted type: E_Byte ) } return type: E_Byte type: System.Func`3[System.Nullable`1[E_Byte],E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- E_Byte Or E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( Or( ConvertChecked( Convert( ConvertChecked( Parameter( x type: E_Byte ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( Parameter( y type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[E_Byte,System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- E_Byte? Or E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) Parameter( y type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( Or( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( Parameter( y type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[System.Nullable`1[E_Byte],System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- Short Or Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) body { Or( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`3[System.Int16,System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- Short Or Short => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) body { ConvertChecked( Or( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Int16,System.Int16,System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Short? Or Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Int16 ) body { ConvertChecked( Or( Parameter( x type: System.Nullable`1[System.Int16] ) ConvertChecked( Parameter( y type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted type: System.Int16 ) } return type: System.Int16 type: System.Func`3[System.Nullable`1[System.Int16],System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- Short Or Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Nullable`1[System.Int16] ) body { Or( ConvertChecked( Parameter( x type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Int16,System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Short? Or Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Nullable`1[System.Int16] ) body { Or( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Nullable`1[System.Int16],System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- E_Short Or E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: E_Short ) body { Convert( Or( Convert( Parameter( x type: E_Short ) type: System.Int16 ) Convert( Parameter( y type: E_Short ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) } return type: E_Short type: System.Func`3[E_Short,E_Short,E_Short] ) -=-=-=-=-=-=-=-=- E_Short Or E_Short => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: E_Short ) body { ConvertChecked( Convert( Or( Convert( Parameter( x type: E_Short ) type: System.Int16 ) Convert( Parameter( y type: E_Short ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[E_Short,E_Short,System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- E_Short? Or E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) Parameter( y type: E_Short ) body { ConvertChecked( Convert( Or( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Convert( ConvertChecked( Parameter( y type: E_Short ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) Lifted type: E_Short ) } return type: E_Short type: System.Func`3[System.Nullable`1[E_Short],E_Short,E_Short] ) -=-=-=-=-=-=-=-=- E_Short Or E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: System.Nullable`1[E_Short] ) body { Convert( Or( Convert( ConvertChecked( Parameter( x type: E_Short ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Convert( Parameter( y type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[E_Short,System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- E_Short? Or E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) Parameter( y type: System.Nullable`1[E_Short] ) body { Convert( Or( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Convert( Parameter( y type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[System.Nullable`1[E_Short],System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- UShort Or UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) body { Or( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) type: System.UInt16 ) } return type: System.UInt16 type: System.Func`3[System.UInt16,System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- UShort Or UShort => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) body { ConvertChecked( Or( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) type: System.UInt16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.UInt16,System.UInt16,System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- UShort? Or UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.UInt16 ) body { ConvertChecked( Or( Parameter( x type: System.Nullable`1[System.UInt16] ) ConvertChecked( Parameter( y type: System.UInt16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted type: System.UInt16 ) } return type: System.UInt16 type: System.Func`3[System.Nullable`1[System.UInt16],System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- UShort Or UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.Nullable`1[System.UInt16] ) body { Or( ConvertChecked( Parameter( x type: System.UInt16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.UInt16,System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- UShort? Or UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.Nullable`1[System.UInt16] ) body { Or( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- E_UShort Or E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: E_UShort ) body { Convert( Or( Convert( Parameter( x type: E_UShort ) type: System.UInt16 ) Convert( Parameter( y type: E_UShort ) type: System.UInt16 ) type: System.UInt16 ) type: E_UShort ) } return type: E_UShort type: System.Func`3[E_UShort,E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- E_UShort Or E_UShort => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: E_UShort ) body { ConvertChecked( Convert( Or( Convert( Parameter( x type: E_UShort ) type: System.UInt16 ) Convert( Parameter( y type: E_UShort ) type: System.UInt16 ) type: System.UInt16 ) type: E_UShort ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[E_UShort,E_UShort,System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- E_UShort? Or E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) Parameter( y type: E_UShort ) body { ConvertChecked( Convert( Or( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Convert( ConvertChecked( Parameter( y type: E_UShort ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) Lifted type: E_UShort ) } return type: E_UShort type: System.Func`3[System.Nullable`1[E_UShort],E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- E_UShort Or E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: System.Nullable`1[E_UShort] ) body { Convert( Or( Convert( ConvertChecked( Parameter( x type: E_UShort ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Convert( Parameter( y type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[E_UShort,System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- E_UShort? Or E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) Parameter( y type: System.Nullable`1[E_UShort] ) body { Convert( Or( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Convert( Parameter( y type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[System.Nullable`1[E_UShort],System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- Integer Or Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) body { Or( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`3[System.Int32,System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- Integer Or Integer => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) body { ConvertChecked( Or( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Int32,System.Int32,System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Integer? Or Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Int32 ) body { ConvertChecked( Or( Parameter( x type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted type: System.Int32 ) } return type: System.Int32 type: System.Func`3[System.Nullable`1[System.Int32],System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- Integer Or Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Nullable`1[System.Int32] ) body { Or( ConvertChecked( Parameter( x type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Int32,System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Integer? Or Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Nullable`1[System.Int32] ) body { Or( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Nullable`1[System.Int32],System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- E_Integer Or E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: E_Integer ) body { Convert( Or( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) Convert( Parameter( y type: E_Integer ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) } return type: E_Integer type: System.Func`3[E_Integer,E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- E_Integer Or E_Integer => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: E_Integer ) body { ConvertChecked( Convert( Or( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) Convert( Parameter( y type: E_Integer ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[E_Integer,E_Integer,System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- E_Integer? Or E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) Parameter( y type: E_Integer ) body { ConvertChecked( Convert( Or( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Convert( ConvertChecked( Parameter( y type: E_Integer ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) Lifted type: E_Integer ) } return type: E_Integer type: System.Func`3[System.Nullable`1[E_Integer],E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- E_Integer Or E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: System.Nullable`1[E_Integer] ) body { Convert( Or( Convert( ConvertChecked( Parameter( x type: E_Integer ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Convert( Parameter( y type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[E_Integer,System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- E_Integer? Or E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) Parameter( y type: System.Nullable`1[E_Integer] ) body { Convert( Or( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Convert( Parameter( y type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[System.Nullable`1[E_Integer],System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- UInteger Or UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) body { Or( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) type: System.UInt32 ) } return type: System.UInt32 type: System.Func`3[System.UInt32,System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- UInteger Or UInteger => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) body { ConvertChecked( Or( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) type: System.UInt32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.UInt32,System.UInt32,System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- UInteger? Or UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.UInt32 ) body { ConvertChecked( Or( Parameter( x type: System.Nullable`1[System.UInt32] ) ConvertChecked( Parameter( y type: System.UInt32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted type: System.UInt32 ) } return type: System.UInt32 type: System.Func`3[System.Nullable`1[System.UInt32],System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- UInteger Or UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.Nullable`1[System.UInt32] ) body { Or( ConvertChecked( Parameter( x type: System.UInt32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.UInt32,System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- UInteger? Or UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.Nullable`1[System.UInt32] ) body { Or( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- E_UInteger Or E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: E_UInteger ) body { Convert( Or( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) Convert( Parameter( y type: E_UInteger ) type: System.UInt32 ) type: System.UInt32 ) type: E_UInteger ) } return type: E_UInteger type: System.Func`3[E_UInteger,E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- E_UInteger Or E_UInteger => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: E_UInteger ) body { ConvertChecked( Convert( Or( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) Convert( Parameter( y type: E_UInteger ) type: System.UInt32 ) type: System.UInt32 ) type: E_UInteger ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[E_UInteger,E_UInteger,System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- E_UInteger? Or E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) Parameter( y type: E_UInteger ) body { ConvertChecked( Convert( Or( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Convert( ConvertChecked( Parameter( y type: E_UInteger ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) Lifted type: E_UInteger ) } return type: E_UInteger type: System.Func`3[System.Nullable`1[E_UInteger],E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- E_UInteger Or E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: System.Nullable`1[E_UInteger] ) body { Convert( Or( Convert( ConvertChecked( Parameter( x type: E_UInteger ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Convert( Parameter( y type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[E_UInteger,System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- E_UInteger? Or E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) Parameter( y type: System.Nullable`1[E_UInteger] ) body { Convert( Or( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Convert( Parameter( y type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- Long Or Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) body { Or( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`3[System.Int64,System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- Long Or Long => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) body { ConvertChecked( Or( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Int64,System.Int64,System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Long? Or Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Int64 ) body { ConvertChecked( Or( Parameter( x type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted type: System.Int64 ) } return type: System.Int64 type: System.Func`3[System.Nullable`1[System.Int64],System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- Long Or Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Nullable`1[System.Int64] ) body { Or( ConvertChecked( Parameter( x type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Int64,System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Long? Or Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Nullable`1[System.Int64] ) body { Or( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Nullable`1[System.Int64],System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- E_Long Or E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: E_Long ) body { Convert( Or( Convert( Parameter( x type: E_Long ) type: System.Int64 ) Convert( Parameter( y type: E_Long ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) } return type: E_Long type: System.Func`3[E_Long,E_Long,E_Long] ) -=-=-=-=-=-=-=-=- E_Long Or E_Long => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: E_Long ) body { ConvertChecked( Convert( Or( Convert( Parameter( x type: E_Long ) type: System.Int64 ) Convert( Parameter( y type: E_Long ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[E_Long,E_Long,System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- E_Long? Or E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) Parameter( y type: E_Long ) body { ConvertChecked( Convert( Or( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Convert( ConvertChecked( Parameter( y type: E_Long ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) Lifted type: E_Long ) } return type: E_Long type: System.Func`3[System.Nullable`1[E_Long],E_Long,E_Long] ) -=-=-=-=-=-=-=-=- E_Long Or E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: System.Nullable`1[E_Long] ) body { Convert( Or( Convert( ConvertChecked( Parameter( x type: E_Long ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Convert( Parameter( y type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[E_Long,System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- E_Long? Or E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) Parameter( y type: System.Nullable`1[E_Long] ) body { Convert( Or( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Convert( Parameter( y type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[System.Nullable`1[E_Long],System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- ULong Or ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) body { Or( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) type: System.UInt64 ) } return type: System.UInt64 type: System.Func`3[System.UInt64,System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- ULong Or ULong => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) body { ConvertChecked( Or( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) type: System.UInt64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.UInt64,System.UInt64,System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- ULong? Or ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.UInt64 ) body { ConvertChecked( Or( Parameter( x type: System.Nullable`1[System.UInt64] ) ConvertChecked( Parameter( y type: System.UInt64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted type: System.UInt64 ) } return type: System.UInt64 type: System.Func`3[System.Nullable`1[System.UInt64],System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- ULong Or ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.Nullable`1[System.UInt64] ) body { Or( ConvertChecked( Parameter( x type: System.UInt64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.UInt64,System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- ULong? Or ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.Nullable`1[System.UInt64] ) body { Or( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- E_ULong Or E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: E_ULong ) body { Convert( Or( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) Convert( Parameter( y type: E_ULong ) type: System.UInt64 ) type: System.UInt64 ) type: E_ULong ) } return type: E_ULong type: System.Func`3[E_ULong,E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- E_ULong Or E_ULong => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: E_ULong ) body { ConvertChecked( Convert( Or( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) Convert( Parameter( y type: E_ULong ) type: System.UInt64 ) type: System.UInt64 ) type: E_ULong ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[E_ULong,E_ULong,System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- E_ULong? Or E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) Parameter( y type: E_ULong ) body { ConvertChecked( Convert( Or( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Convert( ConvertChecked( Parameter( y type: E_ULong ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) Lifted type: E_ULong ) } return type: E_ULong type: System.Func`3[System.Nullable`1[E_ULong],E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- E_ULong Or E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: System.Nullable`1[E_ULong] ) body { Convert( Or( Convert( ConvertChecked( Parameter( x type: E_ULong ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Convert( Parameter( y type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[E_ULong,System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- E_ULong? Or E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) Parameter( y type: System.Nullable`1[E_ULong] ) body { Convert( Or( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Convert( Parameter( y type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[System.Nullable`1[E_ULong],System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- Boolean Or Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) body { Or( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) type: System.Boolean ) } return type: System.Boolean type: System.Func`3[System.Boolean,System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- Boolean Or Boolean => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) body { Convert( Or( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Boolean,System.Boolean,System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Boolean? Or Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Boolean ) body { Convert( Or( Parameter( x type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Boolean ) } return type: System.Boolean type: System.Func`3[System.Nullable`1[System.Boolean],System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- Boolean Or Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Nullable`1[System.Boolean] ) body { Or( Convert( Parameter( x type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Boolean,System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Boolean? Or Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) body { Or( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Single Or Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Single ) body { Convert( Or( ConvertChecked( Parameter( x type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) ConvertChecked( Parameter( y type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Single ) } return type: System.Single type: System.Func`3[System.Single,System.Single,System.Single] ) -=-=-=-=-=-=-=-=- Single Or Single => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Single ) body { Convert( Convert( Or( ConvertChecked( Parameter( x type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) ConvertChecked( Parameter( y type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Single ) method: System.Nullable`1[System.Single] op_Implicit(Single) in System.Nullable`1[System.Single] type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Single,System.Single,System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Single? Or Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) Parameter( y type: System.Single ) body { Convert( ConvertChecked( Or( ConvertChecked( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) ConvertChecked( ConvertChecked( Parameter( y type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) type: System.Single ) } return type: System.Single type: System.Func`3[System.Nullable`1[System.Single],System.Single,System.Single] ) -=-=-=-=-=-=-=-=- Single Or Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Nullable`1[System.Single] ) body { Convert( Or( ConvertChecked( ConvertChecked( Parameter( x type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Single,System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Single? Or Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) Parameter( y type: System.Nullable`1[System.Single] ) body { Convert( Or( ConvertChecked( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Nullable`1[System.Single],System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Double Or Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Double ) body { Convert( Or( ConvertChecked( Parameter( x type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) ConvertChecked( Parameter( y type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Double ) } return type: System.Double type: System.Func`3[System.Double,System.Double,System.Double] ) -=-=-=-=-=-=-=-=- Double Or Double => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Double ) body { Convert( Convert( Or( ConvertChecked( Parameter( x type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) ConvertChecked( Parameter( y type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Double,System.Double,System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Double? Or Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) Parameter( y type: System.Double ) body { Convert( ConvertChecked( Or( ConvertChecked( Parameter( x type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) ConvertChecked( ConvertChecked( Parameter( y type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) type: System.Double ) } return type: System.Double type: System.Func`3[System.Nullable`1[System.Double],System.Double,System.Double] ) -=-=-=-=-=-=-=-=- Double Or Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Nullable`1[System.Double] ) body { Convert( Or( ConvertChecked( ConvertChecked( Parameter( x type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Double,System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Double? Or Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) Parameter( y type: System.Nullable`1[System.Double] ) body { Convert( Or( ConvertChecked( Parameter( x type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Nullable`1[System.Double],System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Decimal Or Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Decimal ) body { Convert( Or( ConvertChecked( Parameter( x type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) ConvertChecked( Parameter( y type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`3[System.Decimal,System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- Decimal Or Decimal => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Decimal ) body { Convert( Convert( Or( ConvertChecked( Parameter( x type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) ConvertChecked( Parameter( y type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) method: System.Nullable`1[System.Decimal] op_Implicit(System.Decimal) in System.Nullable`1[System.Decimal] type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Decimal,System.Decimal,System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Decimal? Or Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) Parameter( y type: System.Decimal ) body { Convert( ConvertChecked( Or( ConvertChecked( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) ConvertChecked( ConvertChecked( Parameter( y type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`3[System.Nullable`1[System.Decimal],System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- Decimal Or Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Nullable`1[System.Decimal] ) body { Convert( Or( ConvertChecked( ConvertChecked( Parameter( x type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Decimal,System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Decimal? Or Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) Parameter( y type: System.Nullable`1[System.Decimal] ) body { Convert( Or( ConvertChecked( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- String Or String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.String ) body { Convert( Or( ConvertChecked( Parameter( x type: System.String ) method: Int64 ToLong(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int64 ) ConvertChecked( Parameter( y type: System.String ) method: Int64 ToLong(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int64 ) type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.String,System.String] ) -=-=-=-=-=-=-=-=- Object Or Object => Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) Parameter( y type: System.Object ) body { Or( Parameter( x type: System.Object ) Parameter( y type: System.Object ) method: System.Object OrObject(System.Object, System.Object) in Microsoft.VisualBasic.CompilerServices.Operators type: System.Object ) } return type: System.Object type: System.Func`3[System.Object,System.Object,System.Object] ) -=-=-=-=-=-=-=-=- SByte Xor SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.SByte ) body { ConvertChecked( ExclusiveOr( ConvertChecked( Parameter( x type: System.SByte ) type: System.Int32 ) ConvertChecked( Parameter( y type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) } return type: System.SByte type: System.Func`3[System.SByte,System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- SByte Xor SByte => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.SByte ) body { ConvertChecked( ConvertChecked( ExclusiveOr( ConvertChecked( Parameter( x type: System.SByte ) type: System.Int32 ) ConvertChecked( Parameter( y type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.SByte,System.SByte,System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- SByte? Xor SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) Parameter( y type: System.SByte ) body { ConvertChecked( ConvertChecked( ExclusiveOr( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( ConvertChecked( Parameter( y type: System.SByte ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted type: System.SByte ) } return type: System.SByte type: System.Func`3[System.Nullable`1[System.SByte],System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- SByte Xor SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.Nullable`1[System.SByte] ) body { ConvertChecked( ExclusiveOr( ConvertChecked( ConvertChecked( Parameter( x type: System.SByte ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.SByte,System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- SByte? Xor SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) Parameter( y type: System.Nullable`1[System.SByte] ) body { ConvertChecked( ExclusiveOr( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.Nullable`1[System.SByte],System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- E_SByte Xor E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: E_SByte ) body { Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Convert( Parameter( x type: E_SByte ) type: System.SByte ) type: System.Int32 ) ConvertChecked( Convert( Parameter( y type: E_SByte ) type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) type: E_SByte ) } return type: E_SByte type: System.Func`3[E_SByte,E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- E_SByte Xor E_SByte => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: E_SByte ) body { ConvertChecked( Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Convert( Parameter( x type: E_SByte ) type: System.SByte ) type: System.Int32 ) ConvertChecked( Convert( Parameter( y type: E_SByte ) type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) type: E_SByte ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[E_SByte,E_SByte,System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- E_SByte? Xor E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: E_SByte ) body { ConvertChecked( Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( ConvertChecked( Parameter( y type: E_SByte ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) Lifted type: E_SByte ) } return type: E_SByte type: System.Func`3[System.Nullable`1[E_SByte],E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- E_SByte Xor E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Convert( ConvertChecked( Parameter( x type: E_SByte ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( Parameter( y type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[E_SByte,System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- E_SByte? Xor E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( Parameter( y type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[System.Nullable`1[E_SByte],System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- Byte Xor Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Byte ) body { ConvertChecked( ExclusiveOr( ConvertChecked( Parameter( x type: System.Byte ) type: System.Int32 ) ConvertChecked( Parameter( y type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) } return type: System.Byte type: System.Func`3[System.Byte,System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- Byte Xor Byte => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Byte ) body { ConvertChecked( ConvertChecked( ExclusiveOr( ConvertChecked( Parameter( x type: System.Byte ) type: System.Int32 ) ConvertChecked( Parameter( y type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Byte,System.Byte,System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Byte? Xor Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) Parameter( y type: System.Byte ) body { ConvertChecked( ConvertChecked( ExclusiveOr( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( ConvertChecked( Parameter( y type: System.Byte ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted type: System.Byte ) } return type: System.Byte type: System.Func`3[System.Nullable`1[System.Byte],System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- Byte Xor Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Nullable`1[System.Byte] ) body { ConvertChecked( ExclusiveOr( ConvertChecked( ConvertChecked( Parameter( x type: System.Byte ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Byte,System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Byte? Xor Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) Parameter( y type: System.Nullable`1[System.Byte] ) body { ConvertChecked( ExclusiveOr( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Nullable`1[System.Byte],System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- E_Byte Xor E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: E_Byte ) body { Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Convert( Parameter( x type: E_Byte ) type: System.Byte ) type: System.Int32 ) ConvertChecked( Convert( Parameter( y type: E_Byte ) type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) type: E_Byte ) } return type: E_Byte type: System.Func`3[E_Byte,E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- E_Byte Xor E_Byte => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: E_Byte ) body { ConvertChecked( Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Convert( Parameter( x type: E_Byte ) type: System.Byte ) type: System.Int32 ) ConvertChecked( Convert( Parameter( y type: E_Byte ) type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) type: E_Byte ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[E_Byte,E_Byte,System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- E_Byte? Xor E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) Parameter( y type: E_Byte ) body { ConvertChecked( Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( ConvertChecked( Parameter( y type: E_Byte ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) Lifted type: E_Byte ) } return type: E_Byte type: System.Func`3[System.Nullable`1[E_Byte],E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- E_Byte Xor E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Convert( ConvertChecked( Parameter( x type: E_Byte ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( Parameter( y type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[E_Byte,System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- E_Byte? Xor E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) Parameter( y type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) ConvertChecked( Convert( Parameter( y type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[System.Nullable`1[E_Byte],System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- Short Xor Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) body { ExclusiveOr( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`3[System.Int16,System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- Short Xor Short => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) body { ConvertChecked( ExclusiveOr( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Int16,System.Int16,System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Short? Xor Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Int16 ) body { ConvertChecked( ExclusiveOr( Parameter( x type: System.Nullable`1[System.Int16] ) ConvertChecked( Parameter( y type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted type: System.Int16 ) } return type: System.Int16 type: System.Func`3[System.Nullable`1[System.Int16],System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- Short Xor Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Nullable`1[System.Int16] ) body { ExclusiveOr( ConvertChecked( Parameter( x type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Int16,System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Short? Xor Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Nullable`1[System.Int16] ) body { ExclusiveOr( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Nullable`1[System.Int16],System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- E_Short Xor E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: E_Short ) body { Convert( ExclusiveOr( Convert( Parameter( x type: E_Short ) type: System.Int16 ) Convert( Parameter( y type: E_Short ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) } return type: E_Short type: System.Func`3[E_Short,E_Short,E_Short] ) -=-=-=-=-=-=-=-=- E_Short Xor E_Short => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: E_Short ) body { ConvertChecked( Convert( ExclusiveOr( Convert( Parameter( x type: E_Short ) type: System.Int16 ) Convert( Parameter( y type: E_Short ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[E_Short,E_Short,System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- E_Short? Xor E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) Parameter( y type: E_Short ) body { ConvertChecked( Convert( ExclusiveOr( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Convert( ConvertChecked( Parameter( y type: E_Short ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) Lifted type: E_Short ) } return type: E_Short type: System.Func`3[System.Nullable`1[E_Short],E_Short,E_Short] ) -=-=-=-=-=-=-=-=- E_Short Xor E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: System.Nullable`1[E_Short] ) body { Convert( ExclusiveOr( Convert( ConvertChecked( Parameter( x type: E_Short ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Convert( Parameter( y type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[E_Short,System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- E_Short? Xor E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) Parameter( y type: System.Nullable`1[E_Short] ) body { Convert( ExclusiveOr( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Convert( Parameter( y type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[System.Nullable`1[E_Short],System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- UShort Xor UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) body { ExclusiveOr( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) type: System.UInt16 ) } return type: System.UInt16 type: System.Func`3[System.UInt16,System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- UShort Xor UShort => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) body { ConvertChecked( ExclusiveOr( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) type: System.UInt16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.UInt16,System.UInt16,System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- UShort? Xor UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.UInt16 ) body { ConvertChecked( ExclusiveOr( Parameter( x type: System.Nullable`1[System.UInt16] ) ConvertChecked( Parameter( y type: System.UInt16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted type: System.UInt16 ) } return type: System.UInt16 type: System.Func`3[System.Nullable`1[System.UInt16],System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- UShort Xor UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.Nullable`1[System.UInt16] ) body { ExclusiveOr( ConvertChecked( Parameter( x type: System.UInt16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.UInt16,System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- UShort? Xor UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.Nullable`1[System.UInt16] ) body { ExclusiveOr( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- E_UShort Xor E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: E_UShort ) body { Convert( ExclusiveOr( Convert( Parameter( x type: E_UShort ) type: System.UInt16 ) Convert( Parameter( y type: E_UShort ) type: System.UInt16 ) type: System.UInt16 ) type: E_UShort ) } return type: E_UShort type: System.Func`3[E_UShort,E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- E_UShort Xor E_UShort => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: E_UShort ) body { ConvertChecked( Convert( ExclusiveOr( Convert( Parameter( x type: E_UShort ) type: System.UInt16 ) Convert( Parameter( y type: E_UShort ) type: System.UInt16 ) type: System.UInt16 ) type: E_UShort ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[E_UShort,E_UShort,System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- E_UShort? Xor E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) Parameter( y type: E_UShort ) body { ConvertChecked( Convert( ExclusiveOr( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Convert( ConvertChecked( Parameter( y type: E_UShort ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) Lifted type: E_UShort ) } return type: E_UShort type: System.Func`3[System.Nullable`1[E_UShort],E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- E_UShort Xor E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: System.Nullable`1[E_UShort] ) body { Convert( ExclusiveOr( Convert( ConvertChecked( Parameter( x type: E_UShort ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Convert( Parameter( y type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[E_UShort,System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- E_UShort? Xor E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) Parameter( y type: System.Nullable`1[E_UShort] ) body { Convert( ExclusiveOr( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Convert( Parameter( y type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[System.Nullable`1[E_UShort],System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- Integer Xor Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) body { ExclusiveOr( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`3[System.Int32,System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- Integer Xor Integer => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) body { ConvertChecked( ExclusiveOr( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Int32,System.Int32,System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Integer? Xor Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Int32 ) body { ConvertChecked( ExclusiveOr( Parameter( x type: System.Nullable`1[System.Int32] ) ConvertChecked( Parameter( y type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted type: System.Int32 ) } return type: System.Int32 type: System.Func`3[System.Nullable`1[System.Int32],System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- Integer Xor Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Nullable`1[System.Int32] ) body { ExclusiveOr( ConvertChecked( Parameter( x type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Int32,System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Integer? Xor Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Nullable`1[System.Int32] ) body { ExclusiveOr( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Nullable`1[System.Int32],System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- E_Integer Xor E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: E_Integer ) body { Convert( ExclusiveOr( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) Convert( Parameter( y type: E_Integer ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) } return type: E_Integer type: System.Func`3[E_Integer,E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- E_Integer Xor E_Integer => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: E_Integer ) body { ConvertChecked( Convert( ExclusiveOr( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) Convert( Parameter( y type: E_Integer ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[E_Integer,E_Integer,System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- E_Integer? Xor E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) Parameter( y type: E_Integer ) body { ConvertChecked( Convert( ExclusiveOr( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Convert( ConvertChecked( Parameter( y type: E_Integer ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) Lifted type: E_Integer ) } return type: E_Integer type: System.Func`3[System.Nullable`1[E_Integer],E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- E_Integer Xor E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: System.Nullable`1[E_Integer] ) body { Convert( ExclusiveOr( Convert( ConvertChecked( Parameter( x type: E_Integer ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Convert( Parameter( y type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[E_Integer,System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- E_Integer? Xor E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) Parameter( y type: System.Nullable`1[E_Integer] ) body { Convert( ExclusiveOr( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Convert( Parameter( y type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[System.Nullable`1[E_Integer],System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- UInteger Xor UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) body { ExclusiveOr( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) type: System.UInt32 ) } return type: System.UInt32 type: System.Func`3[System.UInt32,System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- UInteger Xor UInteger => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) body { ConvertChecked( ExclusiveOr( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) type: System.UInt32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.UInt32,System.UInt32,System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- UInteger? Xor UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.UInt32 ) body { ConvertChecked( ExclusiveOr( Parameter( x type: System.Nullable`1[System.UInt32] ) ConvertChecked( Parameter( y type: System.UInt32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted type: System.UInt32 ) } return type: System.UInt32 type: System.Func`3[System.Nullable`1[System.UInt32],System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- UInteger Xor UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.Nullable`1[System.UInt32] ) body { ExclusiveOr( ConvertChecked( Parameter( x type: System.UInt32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.UInt32,System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- UInteger? Xor UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.Nullable`1[System.UInt32] ) body { ExclusiveOr( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- E_UInteger Xor E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: E_UInteger ) body { Convert( ExclusiveOr( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) Convert( Parameter( y type: E_UInteger ) type: System.UInt32 ) type: System.UInt32 ) type: E_UInteger ) } return type: E_UInteger type: System.Func`3[E_UInteger,E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- E_UInteger Xor E_UInteger => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: E_UInteger ) body { ConvertChecked( Convert( ExclusiveOr( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) Convert( Parameter( y type: E_UInteger ) type: System.UInt32 ) type: System.UInt32 ) type: E_UInteger ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[E_UInteger,E_UInteger,System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- E_UInteger? Xor E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) Parameter( y type: E_UInteger ) body { ConvertChecked( Convert( ExclusiveOr( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Convert( ConvertChecked( Parameter( y type: E_UInteger ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) Lifted type: E_UInteger ) } return type: E_UInteger type: System.Func`3[System.Nullable`1[E_UInteger],E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- E_UInteger Xor E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: System.Nullable`1[E_UInteger] ) body { Convert( ExclusiveOr( Convert( ConvertChecked( Parameter( x type: E_UInteger ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Convert( Parameter( y type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[E_UInteger,System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- E_UInteger? Xor E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) Parameter( y type: System.Nullable`1[E_UInteger] ) body { Convert( ExclusiveOr( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Convert( Parameter( y type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- Long Xor Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) body { ExclusiveOr( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`3[System.Int64,System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- Long Xor Long => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) body { ConvertChecked( ExclusiveOr( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Int64,System.Int64,System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Long? Xor Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Int64 ) body { ConvertChecked( ExclusiveOr( Parameter( x type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted type: System.Int64 ) } return type: System.Int64 type: System.Func`3[System.Nullable`1[System.Int64],System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- Long Xor Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Nullable`1[System.Int64] ) body { ExclusiveOr( ConvertChecked( Parameter( x type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Int64,System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Long? Xor Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Nullable`1[System.Int64] ) body { ExclusiveOr( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Nullable`1[System.Int64],System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- E_Long Xor E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: E_Long ) body { Convert( ExclusiveOr( Convert( Parameter( x type: E_Long ) type: System.Int64 ) Convert( Parameter( y type: E_Long ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) } return type: E_Long type: System.Func`3[E_Long,E_Long,E_Long] ) -=-=-=-=-=-=-=-=- E_Long Xor E_Long => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: E_Long ) body { ConvertChecked( Convert( ExclusiveOr( Convert( Parameter( x type: E_Long ) type: System.Int64 ) Convert( Parameter( y type: E_Long ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[E_Long,E_Long,System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- E_Long? Xor E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) Parameter( y type: E_Long ) body { ConvertChecked( Convert( ExclusiveOr( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Convert( ConvertChecked( Parameter( y type: E_Long ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) Lifted type: E_Long ) } return type: E_Long type: System.Func`3[System.Nullable`1[E_Long],E_Long,E_Long] ) -=-=-=-=-=-=-=-=- E_Long Xor E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: System.Nullable`1[E_Long] ) body { Convert( ExclusiveOr( Convert( ConvertChecked( Parameter( x type: E_Long ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Convert( Parameter( y type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[E_Long,System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- E_Long? Xor E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) Parameter( y type: System.Nullable`1[E_Long] ) body { Convert( ExclusiveOr( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Convert( Parameter( y type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[System.Nullable`1[E_Long],System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- ULong Xor ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) body { ExclusiveOr( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) type: System.UInt64 ) } return type: System.UInt64 type: System.Func`3[System.UInt64,System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- ULong Xor ULong => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) body { ConvertChecked( ExclusiveOr( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) type: System.UInt64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.UInt64,System.UInt64,System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- ULong? Xor ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.UInt64 ) body { ConvertChecked( ExclusiveOr( Parameter( x type: System.Nullable`1[System.UInt64] ) ConvertChecked( Parameter( y type: System.UInt64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted type: System.UInt64 ) } return type: System.UInt64 type: System.Func`3[System.Nullable`1[System.UInt64],System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- ULong Xor ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.Nullable`1[System.UInt64] ) body { ExclusiveOr( ConvertChecked( Parameter( x type: System.UInt64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.UInt64,System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- ULong? Xor ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.Nullable`1[System.UInt64] ) body { ExclusiveOr( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- E_ULong Xor E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: E_ULong ) body { Convert( ExclusiveOr( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) Convert( Parameter( y type: E_ULong ) type: System.UInt64 ) type: System.UInt64 ) type: E_ULong ) } return type: E_ULong type: System.Func`3[E_ULong,E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- E_ULong Xor E_ULong => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: E_ULong ) body { ConvertChecked( Convert( ExclusiveOr( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) Convert( Parameter( y type: E_ULong ) type: System.UInt64 ) type: System.UInt64 ) type: E_ULong ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[E_ULong,E_ULong,System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- E_ULong? Xor E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) Parameter( y type: E_ULong ) body { ConvertChecked( Convert( ExclusiveOr( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Convert( ConvertChecked( Parameter( y type: E_ULong ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) Lifted type: E_ULong ) } return type: E_ULong type: System.Func`3[System.Nullable`1[E_ULong],E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- E_ULong Xor E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: System.Nullable`1[E_ULong] ) body { Convert( ExclusiveOr( Convert( ConvertChecked( Parameter( x type: E_ULong ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Convert( Parameter( y type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[E_ULong,System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- E_ULong? Xor E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) Parameter( y type: System.Nullable`1[E_ULong] ) body { Convert( ExclusiveOr( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Convert( Parameter( y type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[System.Nullable`1[E_ULong],System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- Boolean Xor Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) body { ExclusiveOr( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) type: System.Boolean ) } return type: System.Boolean type: System.Func`3[System.Boolean,System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- Boolean Xor Boolean => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) body { Convert( ExclusiveOr( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Boolean,System.Boolean,System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Boolean? Xor Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Boolean ) body { Convert( ExclusiveOr( Parameter( x type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Boolean ) } return type: System.Boolean type: System.Func`3[System.Nullable`1[System.Boolean],System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- Boolean Xor Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Nullable`1[System.Boolean] ) body { ExclusiveOr( Convert( Parameter( x type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Boolean,System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Boolean? Xor Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) body { ExclusiveOr( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Single Xor Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Single ) body { Convert( ExclusiveOr( ConvertChecked( Parameter( x type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) ConvertChecked( Parameter( y type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Single ) } return type: System.Single type: System.Func`3[System.Single,System.Single,System.Single] ) -=-=-=-=-=-=-=-=- Single Xor Single => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Single ) body { Convert( Convert( ExclusiveOr( ConvertChecked( Parameter( x type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) ConvertChecked( Parameter( y type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Single ) method: System.Nullable`1[System.Single] op_Implicit(Single) in System.Nullable`1[System.Single] type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Single,System.Single,System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Single? Xor Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) Parameter( y type: System.Single ) body { Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) ConvertChecked( ConvertChecked( Parameter( y type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) type: System.Single ) } return type: System.Single type: System.Func`3[System.Nullable`1[System.Single],System.Single,System.Single] ) -=-=-=-=-=-=-=-=- Single Xor Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Nullable`1[System.Single] ) body { Convert( ExclusiveOr( ConvertChecked( ConvertChecked( Parameter( x type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Single,System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Single? Xor Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) Parameter( y type: System.Nullable`1[System.Single] ) body { Convert( ExclusiveOr( ConvertChecked( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Nullable`1[System.Single],System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Double Xor Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Double ) body { Convert( ExclusiveOr( ConvertChecked( Parameter( x type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) ConvertChecked( Parameter( y type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Double ) } return type: System.Double type: System.Func`3[System.Double,System.Double,System.Double] ) -=-=-=-=-=-=-=-=- Double Xor Double => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Double ) body { Convert( Convert( ExclusiveOr( ConvertChecked( Parameter( x type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) ConvertChecked( Parameter( y type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Double,System.Double,System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Double? Xor Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) Parameter( y type: System.Double ) body { Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Parameter( x type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) ConvertChecked( ConvertChecked( Parameter( y type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) type: System.Double ) } return type: System.Double type: System.Func`3[System.Nullable`1[System.Double],System.Double,System.Double] ) -=-=-=-=-=-=-=-=- Double Xor Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Nullable`1[System.Double] ) body { Convert( ExclusiveOr( ConvertChecked( ConvertChecked( Parameter( x type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Double,System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Double? Xor Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) Parameter( y type: System.Nullable`1[System.Double] ) body { Convert( ExclusiveOr( ConvertChecked( Parameter( x type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Nullable`1[System.Double],System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Decimal Xor Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Decimal ) body { Convert( ExclusiveOr( ConvertChecked( Parameter( x type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) ConvertChecked( Parameter( y type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`3[System.Decimal,System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- Decimal Xor Decimal => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Decimal ) body { Convert( Convert( ExclusiveOr( ConvertChecked( Parameter( x type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) ConvertChecked( Parameter( y type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) method: System.Nullable`1[System.Decimal] op_Implicit(System.Decimal) in System.Nullable`1[System.Decimal] type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Decimal,System.Decimal,System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Decimal? Xor Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) Parameter( y type: System.Decimal ) body { Convert( ConvertChecked( ExclusiveOr( ConvertChecked( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) ConvertChecked( ConvertChecked( Parameter( y type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`3[System.Nullable`1[System.Decimal],System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- Decimal Xor Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Nullable`1[System.Decimal] ) body { Convert( ExclusiveOr( ConvertChecked( ConvertChecked( Parameter( x type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Decimal,System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Decimal? Xor Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) Parameter( y type: System.Nullable`1[System.Decimal] ) body { Convert( ExclusiveOr( ConvertChecked( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) ConvertChecked( Parameter( y type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- String Xor String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.String ) body { Convert( ExclusiveOr( ConvertChecked( Parameter( x type: System.String ) method: Int64 ToLong(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int64 ) ConvertChecked( Parameter( y type: System.String ) method: Int64 ToLong(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int64 ) type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.String,System.String] ) -=-=-=-=-=-=-=-=- Object Xor Object => Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) Parameter( y type: System.Object ) body { ExclusiveOr( Parameter( x type: System.Object ) Parameter( y type: System.Object ) method: System.Object XorObject(System.Object, System.Object) in Microsoft.VisualBasic.CompilerServices.Operators type: System.Object ) } return type: System.Object type: System.Func`3[System.Object,System.Object,System.Object] )
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Analyzers/CSharp/CodeFixes/ConvertTypeOfToNameOf/CSharpConvertTypeOfToNameOfCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.ConvertTypeOfToNameOf; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.ConvertTypeOfToNameOf { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.ConvertTypeOfToNameOf), Shared] internal class CSharpConvertTypeOfToNameOfCodeFixProvider : AbstractConvertTypeOfToNameOfCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertTypeOfToNameOfCodeFixProvider() { } protected override string GetCodeFixTitle() => CSharpCodeFixesResources.Convert_typeof_to_nameof; protected override SyntaxNode? GetSymbolTypeExpression(SemanticModel model, SyntaxNode node, CancellationToken cancellationToken) { if (node is MemberAccessExpressionSyntax { Expression: TypeOfExpressionSyntax typeOfExpression }) { var typeSymbol = model.GetSymbolInfo(typeOfExpression.Type, cancellationToken).Symbol.GetSymbolType(); return typeSymbol?.GenerateExpressionSyntax(); } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.ConvertTypeOfToNameOf; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.ConvertTypeOfToNameOf { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.ConvertTypeOfToNameOf), Shared] internal class CSharpConvertTypeOfToNameOfCodeFixProvider : AbstractConvertTypeOfToNameOfCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertTypeOfToNameOfCodeFixProvider() { } protected override string GetCodeFixTitle() => CSharpCodeFixesResources.Convert_typeof_to_nameof; protected override SyntaxNode? GetSymbolTypeExpression(SemanticModel model, SyntaxNode node, CancellationToken cancellationToken) { if (node is MemberAccessExpressionSyntax { Expression: TypeOfExpressionSyntax typeOfExpression }) { var typeSymbol = model.GetSymbolInfo(typeOfExpression.Type, cancellationToken).Symbol.GetSymbolType(); return typeSymbol?.GenerateExpressionSyntax(); } return null; } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Scripting/CoreTestUtilities/ScriptTaskExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Scripting; namespace Roslyn.Test.Utilities { public static class ScriptTaskExtensions { public static async Task<ScriptState<object>> ContinueWith(this Task<ScriptState> task, string code, ScriptOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { return await (await task.ConfigureAwait(false)).ContinueWithAsync(code, options, cancellationToken).ConfigureAwait(false); } public static async Task<ScriptState<object>> ContinueWith(this Task<ScriptState<object>> task, string code, ScriptOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { return await (await task.ConfigureAwait(false)).ContinueWithAsync(code, options, cancellationToken).ConfigureAwait(false); } public static async Task<ScriptState<T>> ContinueWith<T>(this Task<ScriptState> task, string code, ScriptOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { return await (await task.ConfigureAwait(false)).ContinueWithAsync<T>(code, options, cancellationToken).ConfigureAwait(false); } public static async Task<ScriptState<T>> ContinueWith<T>(this Task<ScriptState<object>> task, string code, ScriptOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { return await (await task.ConfigureAwait(false)).ContinueWithAsync<T>(code, options, cancellationToken).ConfigureAwait(false); } public static async Task<ScriptState<object>> ContinueWith<S>(this Task<ScriptState<S>> task, string code, ScriptOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { return await (await task.ConfigureAwait(false)).ContinueWithAsync(code, options, cancellationToken).ConfigureAwait(false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Scripting; namespace Roslyn.Test.Utilities { public static class ScriptTaskExtensions { public static async Task<ScriptState<object>> ContinueWith(this Task<ScriptState> task, string code, ScriptOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { return await (await task.ConfigureAwait(false)).ContinueWithAsync(code, options, cancellationToken).ConfigureAwait(false); } public static async Task<ScriptState<object>> ContinueWith(this Task<ScriptState<object>> task, string code, ScriptOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { return await (await task.ConfigureAwait(false)).ContinueWithAsync(code, options, cancellationToken).ConfigureAwait(false); } public static async Task<ScriptState<T>> ContinueWith<T>(this Task<ScriptState> task, string code, ScriptOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { return await (await task.ConfigureAwait(false)).ContinueWithAsync<T>(code, options, cancellationToken).ConfigureAwait(false); } public static async Task<ScriptState<T>> ContinueWith<T>(this Task<ScriptState<object>> task, string code, ScriptOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { return await (await task.ConfigureAwait(false)).ContinueWithAsync<T>(code, options, cancellationToken).ConfigureAwait(false); } public static async Task<ScriptState<object>> ContinueWith<S>(this Task<ScriptState<S>> task, string code, ScriptOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { return await (await task.ConfigureAwait(false)).ContinueWithAsync(code, options, cancellationToken).ConfigureAwait(false); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/VisualStudio/Core/Def/Implementation/Library/ObjectBrowser/AbstractDescriptionBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser { internal abstract partial class AbstractDescriptionBuilder { private readonly IVsObjectBrowserDescription3 _description; private readonly AbstractObjectBrowserLibraryManager _libraryManager; private readonly ObjectListItem _listItem; private readonly Project _project; private static readonly SymbolDisplayFormat s_typeDisplay = new( miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); protected AbstractDescriptionBuilder( IVsObjectBrowserDescription3 description, AbstractObjectBrowserLibraryManager libraryManager, ObjectListItem listItem, Project project) { _description = description; _libraryManager = libraryManager; _listItem = listItem; _project = project; } private Compilation GetCompilation() { return _project .GetCompilationAsync(CancellationToken.None) .WaitAndGetResult_ObjectBrowser(CancellationToken.None); } protected void AddAssemblyLink(IAssemblySymbol assemblySymbol) { var name = assemblySymbol.Identity.Name; var navInfo = _libraryManager.LibraryService.NavInfoFactory.CreateForAssembly(assemblySymbol); _description.AddDescriptionText3(name, VSOBDESCRIPTIONSECTION.OBDS_TYPE, navInfo); } protected void AddComma() => _description.AddDescriptionText3(", ", VSOBDESCRIPTIONSECTION.OBDS_COMMA, null); protected void AddEndDeclaration() => _description.AddDescriptionText3("\n", VSOBDESCRIPTIONSECTION.OBDS_ENDDECL, null); protected void AddIndent() => _description.AddDescriptionText3(" ", VSOBDESCRIPTIONSECTION.OBDS_MISC, null); protected void AddLineBreak() => _description.AddDescriptionText3("\n", VSOBDESCRIPTIONSECTION.OBDS_MISC, null); protected void AddName(string text) => _description.AddDescriptionText3(text, VSOBDESCRIPTIONSECTION.OBDS_NAME, null); protected void AddNamespaceLink(INamespaceSymbol namespaceSymbol) { if (namespaceSymbol.IsGlobalNamespace) { return; } var text = namespaceSymbol.ToDisplayString(); var navInfo = _libraryManager.LibraryService.NavInfoFactory.CreateForNamespace(namespaceSymbol, _project, GetCompilation(), useExpandedHierarchy: false); _description.AddDescriptionText3(text, VSOBDESCRIPTIONSECTION.OBDS_TYPE, navInfo); } protected void AddParam(string text) => _description.AddDescriptionText3(text, VSOBDESCRIPTIONSECTION.OBDS_PARAM, null); protected void AddText(string text) => _description.AddDescriptionText3(text, VSOBDESCRIPTIONSECTION.OBDS_MISC, null); protected void AddTypeLink(ITypeSymbol typeSymbol, LinkFlags flags) { if (typeSymbol.TypeKind == TypeKind.Unknown || typeSymbol.TypeKind == TypeKind.Error || typeSymbol.TypeKind == TypeKind.TypeParameter || typeSymbol.SpecialType == SpecialType.System_Void) { AddName(typeSymbol.ToDisplayString(s_typeDisplay)); return; } var useSpecialTypes = (flags & LinkFlags.ExpandPredefinedTypes) == 0; var splitLink = !useSpecialTypes & (flags & LinkFlags.SplitNamespaceAndType) != 0; if (splitLink && !typeSymbol.ContainingNamespace.IsGlobalNamespace) { AddNamespaceLink(typeSymbol.ContainingNamespace); AddText("."); } var typeQualificationStyle = splitLink ? SymbolDisplayTypeQualificationStyle.NameAndContainingTypes : SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces; var miscellaneousOptions = useSpecialTypes ? SymbolDisplayMiscellaneousOptions.UseSpecialTypes : SymbolDisplayMiscellaneousOptions.ExpandNullable; var typeDisplayFormat = new SymbolDisplayFormat( typeQualificationStyle: typeQualificationStyle, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, miscellaneousOptions: miscellaneousOptions); var text = typeSymbol.ToDisplayString(typeDisplayFormat); var navInfo = _libraryManager.LibraryService.NavInfoFactory.CreateForType(typeSymbol, _project, GetCompilation(), useExpandedHierarchy: false); _description.AddDescriptionText3(text, VSOBDESCRIPTIONSECTION.OBDS_TYPE, navInfo); } private void BuildProject(ProjectListItem projectListItem) { AddText(ServicesVSResources.Project); AddName(projectListItem.DisplayText); } private void BuildReference(ReferenceListItem referenceListItem) { AddText(ServicesVSResources.Assembly); AddName(referenceListItem.DisplayText); AddEndDeclaration(); AddIndent(); if (referenceListItem.MetadataReference is PortableExecutableReference portableExecutableReference) { AddText(portableExecutableReference.FilePath); } } private void BuildNamespace(NamespaceListItem namespaceListItem, _VSOBJDESCOPTIONS options) { var compilation = GetCompilation(); if (compilation == null) { return; } var namespaceSymbol = namespaceListItem.ResolveTypedSymbol(compilation); if (namespaceSymbol == null) { return; } BuildNamespaceDeclaration(namespaceSymbol, options); AddEndDeclaration(); BuildMemberOf(namespaceSymbol.ContainingAssembly); } private void BuildType(TypeListItem typeListItem, _VSOBJDESCOPTIONS options) { var compilation = GetCompilation(); if (compilation == null) { return; } var symbol = typeListItem.ResolveTypedSymbol(compilation); if (symbol == null) { return; } if (symbol.TypeKind == TypeKind.Delegate) { BuildDelegateDeclaration(symbol, options); } else { BuildTypeDeclaration(symbol, options); } AddEndDeclaration(); BuildMemberOf(symbol.ContainingNamespace); BuildXmlDocumentation(symbol, compilation); } private void BuildMember(MemberListItem memberListItem, _VSOBJDESCOPTIONS options) { var compilation = GetCompilation(); if (compilation == null) { return; } var symbol = memberListItem.ResolveTypedSymbol(compilation); if (symbol == null) { return; } switch (symbol.Kind) { case SymbolKind.Method: BuildMethodDeclaration((IMethodSymbol)symbol, options); break; case SymbolKind.Field: BuildFieldDeclaration((IFieldSymbol)symbol, options); break; case SymbolKind.Property: BuildPropertyDeclaration((IPropertySymbol)symbol, options); break; case SymbolKind.Event: BuildEventDeclaration((IEventSymbol)symbol, options); break; default: Debug.Fail("Unsupported member kind: " + symbol.Kind.ToString()); return; } AddEndDeclaration(); BuildMemberOf(symbol.ContainingType); BuildXmlDocumentation(symbol, compilation); } protected abstract void BuildNamespaceDeclaration(INamespaceSymbol namespaceSymbol, _VSOBJDESCOPTIONS options); protected abstract void BuildDelegateDeclaration(INamedTypeSymbol typeSymbol, _VSOBJDESCOPTIONS options); protected abstract void BuildTypeDeclaration(INamedTypeSymbol typeSymbol, _VSOBJDESCOPTIONS options); protected abstract void BuildMethodDeclaration(IMethodSymbol methodSymbol, _VSOBJDESCOPTIONS options); protected abstract void BuildFieldDeclaration(IFieldSymbol fieldSymbol, _VSOBJDESCOPTIONS options); protected abstract void BuildPropertyDeclaration(IPropertySymbol propertySymbol, _VSOBJDESCOPTIONS options); protected abstract void BuildEventDeclaration(IEventSymbol eventSymbol, _VSOBJDESCOPTIONS options); private void BuildMemberOf(ISymbol containingSymbol) { if (containingSymbol is INamespaceSymbol && ((INamespaceSymbol)containingSymbol).IsGlobalNamespace) { containingSymbol = containingSymbol.ContainingAssembly; } var memberOfText = ServicesVSResources.Member_of_0; const string specifier = "{0}"; var index = memberOfText.IndexOf(specifier, StringComparison.Ordinal); if (index < 0) { Debug.Fail("MemberOf string resource is incorrect."); return; } var left = memberOfText.Substring(0, index); var right = memberOfText.Substring(index + specifier.Length); AddIndent(); AddText(left); if (containingSymbol is IAssemblySymbol assemblySymbol) { AddAssemblyLink(assemblySymbol); } else if (containingSymbol is ITypeSymbol typeSymbol) { AddTypeLink(typeSymbol, LinkFlags.SplitNamespaceAndType | LinkFlags.ExpandPredefinedTypes); } else if (containingSymbol is INamespaceSymbol namespaceSymbol) { AddNamespaceLink(namespaceSymbol); } AddText(right); AddEndDeclaration(); } private void BuildXmlDocumentation(ISymbol symbol, Compilation compilation) { var documentationComment = symbol.GetDocumentationComment(compilation, expandIncludes: true, expandInheritdoc: true, cancellationToken: CancellationToken.None); if (documentationComment == null) { return; } var formattingService = _project.LanguageServices.GetService<IDocumentationCommentFormattingService>(); if (formattingService == null) { return; } var emittedDocs = false; if (documentationComment.SummaryText != null) { AddLineBreak(); AddName(ServicesVSResources.Summary_colon); AddLineBreak(); AddText(formattingService.Format(documentationComment.SummaryText, compilation)); emittedDocs = true; } if (documentationComment.TypeParameterNames.Length > 0) { if (emittedDocs) { AddLineBreak(); } AddLineBreak(); AddName(ServicesVSResources.Type_Parameters_colon); foreach (var typeParameterName in documentationComment.TypeParameterNames) { AddLineBreak(); var typeParameterText = documentationComment.GetTypeParameterText(typeParameterName); if (typeParameterText != null) { AddParam(typeParameterName); AddText(": "); AddText(formattingService.Format(typeParameterText, compilation)); emittedDocs = true; } } } if (documentationComment.ParameterNames.Length > 0) { if (emittedDocs) { AddLineBreak(); } AddLineBreak(); AddName(ServicesVSResources.Parameters_colon1); foreach (var parameterName in documentationComment.ParameterNames) { AddLineBreak(); var parameterText = documentationComment.GetParameterText(parameterName); if (parameterText != null) { AddParam(parameterName); AddText(": "); AddText(formattingService.Format(parameterText, compilation)); emittedDocs = true; } } } if (ShowReturnsDocumentation(symbol) && documentationComment.ReturnsText != null) { if (emittedDocs) { AddLineBreak(); } AddLineBreak(); AddName(ServicesVSResources.Returns_colon); AddLineBreak(); AddText(formattingService.Format(documentationComment.ReturnsText, compilation)); emittedDocs = true; } if (ShowValueDocumentation(symbol) && documentationComment.ValueText != null) { if (emittedDocs) { AddLineBreak(); } AddLineBreak(); AddName(ServicesVSResources.Value_colon); AddLineBreak(); AddText(formattingService.Format(documentationComment.ValueText, compilation)); emittedDocs = true; } if (documentationComment.RemarksText != null) { if (emittedDocs) { AddLineBreak(); } AddLineBreak(); AddName(ServicesVSResources.Remarks_colon); AddLineBreak(); AddText(formattingService.Format(documentationComment.RemarksText, compilation)); emittedDocs = true; } if (documentationComment.ExceptionTypes.Length > 0) { if (emittedDocs) { AddLineBreak(); } AddLineBreak(); AddName(ServicesVSResources.Exceptions_colon); foreach (var exceptionType in documentationComment.ExceptionTypes) { if (DocumentationCommentId.GetFirstSymbolForDeclarationId(exceptionType, compilation) is INamedTypeSymbol exceptionTypeSymbol) { AddLineBreak(); var exceptionTexts = documentationComment.GetExceptionTexts(exceptionType); if (exceptionTexts.Length == 0) { AddTypeLink(exceptionTypeSymbol, LinkFlags.None); } else { foreach (var exceptionText in exceptionTexts) { AddTypeLink(exceptionTypeSymbol, LinkFlags.None); AddText(": "); AddText(formattingService.Format(exceptionText, compilation)); } } } } } } private bool ShowReturnsDocumentation(ISymbol symbol) { return (symbol.Kind == SymbolKind.NamedType && ((INamedTypeSymbol)symbol).TypeKind == TypeKind.Delegate) || symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.Property; } private bool ShowValueDocumentation(ISymbol symbol) { // <returns> is often used in places where <value> was originally intended. Allow either to be used in // documentation comments since they are not likely to be used together and it's not clear which one a // particular code base will be using more often. return ShowReturnsDocumentation(symbol); } internal bool TryBuild(_VSOBJDESCOPTIONS options) { switch (_listItem) { case ProjectListItem projectListItem: BuildProject(projectListItem); return true; case ReferenceListItem referenceListItem: BuildReference(referenceListItem); return true; case NamespaceListItem namespaceListItem: BuildNamespace(namespaceListItem, options); return true; case TypeListItem typeListItem: BuildType(typeListItem, options); return true; case MemberListItem memberListItem: BuildMember(memberListItem, options); return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser { internal abstract partial class AbstractDescriptionBuilder { private readonly IVsObjectBrowserDescription3 _description; private readonly AbstractObjectBrowserLibraryManager _libraryManager; private readonly ObjectListItem _listItem; private readonly Project _project; private static readonly SymbolDisplayFormat s_typeDisplay = new( miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); protected AbstractDescriptionBuilder( IVsObjectBrowserDescription3 description, AbstractObjectBrowserLibraryManager libraryManager, ObjectListItem listItem, Project project) { _description = description; _libraryManager = libraryManager; _listItem = listItem; _project = project; } private Compilation GetCompilation() { return _project .GetCompilationAsync(CancellationToken.None) .WaitAndGetResult_ObjectBrowser(CancellationToken.None); } protected void AddAssemblyLink(IAssemblySymbol assemblySymbol) { var name = assemblySymbol.Identity.Name; var navInfo = _libraryManager.LibraryService.NavInfoFactory.CreateForAssembly(assemblySymbol); _description.AddDescriptionText3(name, VSOBDESCRIPTIONSECTION.OBDS_TYPE, navInfo); } protected void AddComma() => _description.AddDescriptionText3(", ", VSOBDESCRIPTIONSECTION.OBDS_COMMA, null); protected void AddEndDeclaration() => _description.AddDescriptionText3("\n", VSOBDESCRIPTIONSECTION.OBDS_ENDDECL, null); protected void AddIndent() => _description.AddDescriptionText3(" ", VSOBDESCRIPTIONSECTION.OBDS_MISC, null); protected void AddLineBreak() => _description.AddDescriptionText3("\n", VSOBDESCRIPTIONSECTION.OBDS_MISC, null); protected void AddName(string text) => _description.AddDescriptionText3(text, VSOBDESCRIPTIONSECTION.OBDS_NAME, null); protected void AddNamespaceLink(INamespaceSymbol namespaceSymbol) { if (namespaceSymbol.IsGlobalNamespace) { return; } var text = namespaceSymbol.ToDisplayString(); var navInfo = _libraryManager.LibraryService.NavInfoFactory.CreateForNamespace(namespaceSymbol, _project, GetCompilation(), useExpandedHierarchy: false); _description.AddDescriptionText3(text, VSOBDESCRIPTIONSECTION.OBDS_TYPE, navInfo); } protected void AddParam(string text) => _description.AddDescriptionText3(text, VSOBDESCRIPTIONSECTION.OBDS_PARAM, null); protected void AddText(string text) => _description.AddDescriptionText3(text, VSOBDESCRIPTIONSECTION.OBDS_MISC, null); protected void AddTypeLink(ITypeSymbol typeSymbol, LinkFlags flags) { if (typeSymbol.TypeKind == TypeKind.Unknown || typeSymbol.TypeKind == TypeKind.Error || typeSymbol.TypeKind == TypeKind.TypeParameter || typeSymbol.SpecialType == SpecialType.System_Void) { AddName(typeSymbol.ToDisplayString(s_typeDisplay)); return; } var useSpecialTypes = (flags & LinkFlags.ExpandPredefinedTypes) == 0; var splitLink = !useSpecialTypes & (flags & LinkFlags.SplitNamespaceAndType) != 0; if (splitLink && !typeSymbol.ContainingNamespace.IsGlobalNamespace) { AddNamespaceLink(typeSymbol.ContainingNamespace); AddText("."); } var typeQualificationStyle = splitLink ? SymbolDisplayTypeQualificationStyle.NameAndContainingTypes : SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces; var miscellaneousOptions = useSpecialTypes ? SymbolDisplayMiscellaneousOptions.UseSpecialTypes : SymbolDisplayMiscellaneousOptions.ExpandNullable; var typeDisplayFormat = new SymbolDisplayFormat( typeQualificationStyle: typeQualificationStyle, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, miscellaneousOptions: miscellaneousOptions); var text = typeSymbol.ToDisplayString(typeDisplayFormat); var navInfo = _libraryManager.LibraryService.NavInfoFactory.CreateForType(typeSymbol, _project, GetCompilation(), useExpandedHierarchy: false); _description.AddDescriptionText3(text, VSOBDESCRIPTIONSECTION.OBDS_TYPE, navInfo); } private void BuildProject(ProjectListItem projectListItem) { AddText(ServicesVSResources.Project); AddName(projectListItem.DisplayText); } private void BuildReference(ReferenceListItem referenceListItem) { AddText(ServicesVSResources.Assembly); AddName(referenceListItem.DisplayText); AddEndDeclaration(); AddIndent(); if (referenceListItem.MetadataReference is PortableExecutableReference portableExecutableReference) { AddText(portableExecutableReference.FilePath); } } private void BuildNamespace(NamespaceListItem namespaceListItem, _VSOBJDESCOPTIONS options) { var compilation = GetCompilation(); if (compilation == null) { return; } var namespaceSymbol = namespaceListItem.ResolveTypedSymbol(compilation); if (namespaceSymbol == null) { return; } BuildNamespaceDeclaration(namespaceSymbol, options); AddEndDeclaration(); BuildMemberOf(namespaceSymbol.ContainingAssembly); } private void BuildType(TypeListItem typeListItem, _VSOBJDESCOPTIONS options) { var compilation = GetCompilation(); if (compilation == null) { return; } var symbol = typeListItem.ResolveTypedSymbol(compilation); if (symbol == null) { return; } if (symbol.TypeKind == TypeKind.Delegate) { BuildDelegateDeclaration(symbol, options); } else { BuildTypeDeclaration(symbol, options); } AddEndDeclaration(); BuildMemberOf(symbol.ContainingNamespace); BuildXmlDocumentation(symbol, compilation); } private void BuildMember(MemberListItem memberListItem, _VSOBJDESCOPTIONS options) { var compilation = GetCompilation(); if (compilation == null) { return; } var symbol = memberListItem.ResolveTypedSymbol(compilation); if (symbol == null) { return; } switch (symbol.Kind) { case SymbolKind.Method: BuildMethodDeclaration((IMethodSymbol)symbol, options); break; case SymbolKind.Field: BuildFieldDeclaration((IFieldSymbol)symbol, options); break; case SymbolKind.Property: BuildPropertyDeclaration((IPropertySymbol)symbol, options); break; case SymbolKind.Event: BuildEventDeclaration((IEventSymbol)symbol, options); break; default: Debug.Fail("Unsupported member kind: " + symbol.Kind.ToString()); return; } AddEndDeclaration(); BuildMemberOf(symbol.ContainingType); BuildXmlDocumentation(symbol, compilation); } protected abstract void BuildNamespaceDeclaration(INamespaceSymbol namespaceSymbol, _VSOBJDESCOPTIONS options); protected abstract void BuildDelegateDeclaration(INamedTypeSymbol typeSymbol, _VSOBJDESCOPTIONS options); protected abstract void BuildTypeDeclaration(INamedTypeSymbol typeSymbol, _VSOBJDESCOPTIONS options); protected abstract void BuildMethodDeclaration(IMethodSymbol methodSymbol, _VSOBJDESCOPTIONS options); protected abstract void BuildFieldDeclaration(IFieldSymbol fieldSymbol, _VSOBJDESCOPTIONS options); protected abstract void BuildPropertyDeclaration(IPropertySymbol propertySymbol, _VSOBJDESCOPTIONS options); protected abstract void BuildEventDeclaration(IEventSymbol eventSymbol, _VSOBJDESCOPTIONS options); private void BuildMemberOf(ISymbol containingSymbol) { if (containingSymbol is INamespaceSymbol && ((INamespaceSymbol)containingSymbol).IsGlobalNamespace) { containingSymbol = containingSymbol.ContainingAssembly; } var memberOfText = ServicesVSResources.Member_of_0; const string specifier = "{0}"; var index = memberOfText.IndexOf(specifier, StringComparison.Ordinal); if (index < 0) { Debug.Fail("MemberOf string resource is incorrect."); return; } var left = memberOfText.Substring(0, index); var right = memberOfText.Substring(index + specifier.Length); AddIndent(); AddText(left); if (containingSymbol is IAssemblySymbol assemblySymbol) { AddAssemblyLink(assemblySymbol); } else if (containingSymbol is ITypeSymbol typeSymbol) { AddTypeLink(typeSymbol, LinkFlags.SplitNamespaceAndType | LinkFlags.ExpandPredefinedTypes); } else if (containingSymbol is INamespaceSymbol namespaceSymbol) { AddNamespaceLink(namespaceSymbol); } AddText(right); AddEndDeclaration(); } private void BuildXmlDocumentation(ISymbol symbol, Compilation compilation) { var documentationComment = symbol.GetDocumentationComment(compilation, expandIncludes: true, expandInheritdoc: true, cancellationToken: CancellationToken.None); if (documentationComment == null) { return; } var formattingService = _project.LanguageServices.GetService<IDocumentationCommentFormattingService>(); if (formattingService == null) { return; } var emittedDocs = false; if (documentationComment.SummaryText != null) { AddLineBreak(); AddName(ServicesVSResources.Summary_colon); AddLineBreak(); AddText(formattingService.Format(documentationComment.SummaryText, compilation)); emittedDocs = true; } if (documentationComment.TypeParameterNames.Length > 0) { if (emittedDocs) { AddLineBreak(); } AddLineBreak(); AddName(ServicesVSResources.Type_Parameters_colon); foreach (var typeParameterName in documentationComment.TypeParameterNames) { AddLineBreak(); var typeParameterText = documentationComment.GetTypeParameterText(typeParameterName); if (typeParameterText != null) { AddParam(typeParameterName); AddText(": "); AddText(formattingService.Format(typeParameterText, compilation)); emittedDocs = true; } } } if (documentationComment.ParameterNames.Length > 0) { if (emittedDocs) { AddLineBreak(); } AddLineBreak(); AddName(ServicesVSResources.Parameters_colon1); foreach (var parameterName in documentationComment.ParameterNames) { AddLineBreak(); var parameterText = documentationComment.GetParameterText(parameterName); if (parameterText != null) { AddParam(parameterName); AddText(": "); AddText(formattingService.Format(parameterText, compilation)); emittedDocs = true; } } } if (ShowReturnsDocumentation(symbol) && documentationComment.ReturnsText != null) { if (emittedDocs) { AddLineBreak(); } AddLineBreak(); AddName(ServicesVSResources.Returns_colon); AddLineBreak(); AddText(formattingService.Format(documentationComment.ReturnsText, compilation)); emittedDocs = true; } if (ShowValueDocumentation(symbol) && documentationComment.ValueText != null) { if (emittedDocs) { AddLineBreak(); } AddLineBreak(); AddName(ServicesVSResources.Value_colon); AddLineBreak(); AddText(formattingService.Format(documentationComment.ValueText, compilation)); emittedDocs = true; } if (documentationComment.RemarksText != null) { if (emittedDocs) { AddLineBreak(); } AddLineBreak(); AddName(ServicesVSResources.Remarks_colon); AddLineBreak(); AddText(formattingService.Format(documentationComment.RemarksText, compilation)); emittedDocs = true; } if (documentationComment.ExceptionTypes.Length > 0) { if (emittedDocs) { AddLineBreak(); } AddLineBreak(); AddName(ServicesVSResources.Exceptions_colon); foreach (var exceptionType in documentationComment.ExceptionTypes) { if (DocumentationCommentId.GetFirstSymbolForDeclarationId(exceptionType, compilation) is INamedTypeSymbol exceptionTypeSymbol) { AddLineBreak(); var exceptionTexts = documentationComment.GetExceptionTexts(exceptionType); if (exceptionTexts.Length == 0) { AddTypeLink(exceptionTypeSymbol, LinkFlags.None); } else { foreach (var exceptionText in exceptionTexts) { AddTypeLink(exceptionTypeSymbol, LinkFlags.None); AddText(": "); AddText(formattingService.Format(exceptionText, compilation)); } } } } } } private bool ShowReturnsDocumentation(ISymbol symbol) { return (symbol.Kind == SymbolKind.NamedType && ((INamedTypeSymbol)symbol).TypeKind == TypeKind.Delegate) || symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.Property; } private bool ShowValueDocumentation(ISymbol symbol) { // <returns> is often used in places where <value> was originally intended. Allow either to be used in // documentation comments since they are not likely to be used together and it's not clear which one a // particular code base will be using more often. return ShowReturnsDocumentation(symbol); } internal bool TryBuild(_VSOBJDESCOPTIONS options) { switch (_listItem) { case ProjectListItem projectListItem: BuildProject(projectListItem); return true; case ReferenceListItem referenceListItem: BuildReference(referenceListItem); return true; case NamespaceListItem namespaceListItem: BuildNamespace(namespaceListItem, options); return true; case TypeListItem typeListItem: BuildType(typeListItem, options); return true; case MemberListItem memberListItem: BuildMember(memberListItem, options); return true; } return false; } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Workspaces/MSBuildTest/Resources/global.json
{ "comment": "this file is empty to ensure we get the 'standard' behavior as if no global.json was specified in the first place" }
{ "comment": "this file is empty to ensure we get the 'standard' behavior as if no global.json was specified in the first place" }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/EditorFeatures/Core/Implementation/InlineRename/InlineRenameSession.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Undo; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Threading; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal partial class InlineRenameSession : ForegroundThreadAffinitizedObject, IInlineRenameSession, IFeatureController { private readonly Workspace _workspace; private readonly InlineRenameService _renameService; private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; private readonly ITextBufferAssociatedViewService _textBufferAssociatedViewService; private readonly ITextBufferFactoryService _textBufferFactoryService; private readonly IFeatureService _featureService; private readonly IFeatureDisableToken _completionDisabledToken; private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices; private readonly IDebuggingWorkspaceService _debuggingWorkspaceService; private readonly IAsynchronousOperationListener _asyncListener; private readonly Solution _baseSolution; private readonly Document _triggerDocument; private readonly ITextView _triggerView; private readonly IDisposable _inlineRenameSessionDurationLogBlock; private bool _dismissed; private bool _isApplyingEdit; private string _replacementText; private OptionSet _optionSet; private readonly Dictionary<ITextBuffer, OpenTextBufferManager> _openTextBuffers = new Dictionary<ITextBuffer, OpenTextBufferManager>(); /// <summary> /// If non-null, the current text of the replacement. Linked spans added will automatically be updated with this /// text. /// </summary> public string ReplacementText { get { return _replacementText; } private set { _replacementText = value; ReplacementTextChanged?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Information about whether a file rename should be allowed as part /// of the rename operation, as determined by the language /// </summary> public InlineRenameFileRenameInfo FileRenameInfo { get; } /// <summary> /// The task which computes the main rename locations against the original workspace /// snapshot. /// </summary> private JoinableTask<IInlineRenameLocationSet> _allRenameLocationsTask; /// <summary> /// The cancellation token for most work being done by the inline rename session. This /// includes the <see cref="_allRenameLocationsTask"/> tasks. /// </summary> private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); /// <summary> /// This task is a continuation of the <see cref="_allRenameLocationsTask"/> that is the result of computing /// the resolutions of the rename spans for the current replacementText. /// </summary> private JoinableTask<IInlineRenameReplacementInfo> _conflictResolutionTask; /// <summary> /// The cancellation source for <see cref="_conflictResolutionTask"/>. /// </summary> private CancellationTokenSource _conflictResolutionTaskCancellationSource = new CancellationTokenSource(); private readonly IInlineRenameInfo _renameInfo; /// <summary> /// The initial text being renamed. /// </summary> private readonly string _initialRenameText; public InlineRenameSession( IThreadingContext threadingContext, InlineRenameService renameService, Workspace workspace, SnapshotSpan triggerSpan, IInlineRenameInfo renameInfo, IUIThreadOperationExecutor uiThreadOperationExecutor, ITextBufferAssociatedViewService textBufferAssociatedViewService, ITextBufferFactoryService textBufferFactoryService, IFeatureServiceFactory featureServiceFactory, IEnumerable<IRefactorNotifyService> refactorNotifyServices, IAsynchronousOperationListener asyncListener) : base(threadingContext, assertIsForeground: true) { // This should always be touching a symbol since we verified that upon invocation _renameInfo = renameInfo; _triggerDocument = triggerSpan.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (_triggerDocument == null) { throw new InvalidOperationException(EditorFeaturesResources.The_triggerSpan_is_not_included_in_the_given_workspace); } _inlineRenameSessionDurationLogBlock = Logger.LogBlock(FunctionId.Rename_InlineSession, CancellationToken.None); _workspace = workspace; _workspace.WorkspaceChanged += OnWorkspaceChanged; _textBufferFactoryService = textBufferFactoryService; _textBufferAssociatedViewService = textBufferAssociatedViewService; _textBufferAssociatedViewService.SubjectBuffersConnected += OnSubjectBuffersConnected; // Disable completion when an inline rename session starts _featureService = featureServiceFactory.GlobalFeatureService; _completionDisabledToken = _featureService.Disable(PredefinedEditorFeatureNames.Completion, this); _renameService = renameService; _uiThreadOperationExecutor = uiThreadOperationExecutor; _refactorNotifyServices = refactorNotifyServices; _asyncListener = asyncListener; _triggerView = textBufferAssociatedViewService.GetAssociatedTextViews(triggerSpan.Snapshot.TextBuffer).FirstOrDefault(v => v.HasAggregateFocus) ?? textBufferAssociatedViewService.GetAssociatedTextViews(triggerSpan.Snapshot.TextBuffer).First(); _optionSet = renameInfo.ForceRenameOverloads ? workspace.Options.WithChangedOption(RenameOptions.RenameOverloads, true) : workspace.Options; _initialRenameText = triggerSpan.GetText(); this.ReplacementText = _initialRenameText; _baseSolution = _triggerDocument.Project.Solution; this.UndoManager = workspace.Services.GetService<IInlineRenameUndoManager>(); _debuggingWorkspaceService = workspace.Services.GetService<IDebuggingWorkspaceService>(); _debuggingWorkspaceService.BeforeDebuggingStateChanged += OnBeforeDebuggingStateChanged; if (_renameInfo is IInlineRenameInfoWithFileRename renameInfoWithFileRename) { FileRenameInfo = renameInfoWithFileRename.GetFileRenameInfo(); } else { FileRenameInfo = InlineRenameFileRenameInfo.NotAllowed; } InitializeOpenBuffers(triggerSpan); } private void OnBeforeDebuggingStateChanged(object sender, DebuggingStateChangedEventArgs args) { if (args.After == DebuggingState.Run) { // It's too late for us to change anything, which means we can neither commit nor // rollback changes to cancel. End the rename session but keep all open buffers in // their current state. Cancel(rollbackTemporaryEdits: false); } } public string OriginalSymbolName => _renameInfo.DisplayName; // Used to aid the investigation of https://github.com/dotnet/roslyn/issues/7364 private class NullTextBufferException : Exception { #pragma warning disable IDE0052 // Remove unread private members private readonly Document _document; private readonly SourceText _text; #pragma warning restore IDE0052 // Remove unread private members public NullTextBufferException(Document document, SourceText text) : base("Cannot retrieve textbuffer from document.") { _document = document; _text = text; } } private void InitializeOpenBuffers(SnapshotSpan triggerSpan) { using (Logger.LogBlock(FunctionId.Rename_CreateOpenTextBufferManagerForAllOpenDocs, CancellationToken.None)) { var openBuffers = new HashSet<ITextBuffer>(); foreach (var d in _workspace.GetOpenDocumentIds()) { var document = _baseSolution.GetDocument(d); if (document == null) { continue; } Contract.ThrowIfFalse(document.TryGetText(out var text)); Contract.ThrowIfNull(text); var textSnapshot = text.FindCorrespondingEditorTextSnapshot(); if (textSnapshot == null) { FatalError.ReportAndCatch(new NullTextBufferException(document, text)); continue; } Contract.ThrowIfNull(textSnapshot.TextBuffer); openBuffers.Add(textSnapshot.TextBuffer); } foreach (var buffer in openBuffers) { TryPopulateOpenTextBufferManagerForBuffer(buffer); } } var startingSpan = triggerSpan.Span; // Select this span if we didn't already have something selected var selections = _triggerView.Selection.GetSnapshotSpansOnBuffer(triggerSpan.Snapshot.TextBuffer); if (!selections.Any() || selections.First().IsEmpty || !startingSpan.Contains(selections.First())) { _triggerView.SetSelection(new SnapshotSpan(triggerSpan.Snapshot, startingSpan)); } this.UndoManager.CreateInitialState(this.ReplacementText, _triggerView.Selection, new SnapshotSpan(triggerSpan.Snapshot, startingSpan)); _openTextBuffers[triggerSpan.Snapshot.TextBuffer].SetReferenceSpans(SpecializedCollections.SingletonEnumerable(startingSpan.ToTextSpan())); UpdateReferenceLocationsTask(ThreadingContext.JoinableTaskFactory.RunAsync( () => _renameInfo.FindRenameLocationsAsync(_optionSet, _cancellationTokenSource.Token))); RenameTrackingDismisser.DismissRenameTracking(_workspace, _workspace.GetOpenDocumentIds()); } private bool TryPopulateOpenTextBufferManagerForBuffer(ITextBuffer buffer) { AssertIsForeground(); VerifyNotDismissed(); if (_workspace.Kind == WorkspaceKind.Interactive) { Debug.Assert(buffer.GetRelatedDocuments().Count() == 1); Debug.Assert(buffer.IsReadOnly(0) == buffer.IsReadOnly(VisualStudio.Text.Span.FromBounds(0, buffer.CurrentSnapshot.Length))); // All or nothing. if (buffer.IsReadOnly(0)) { return false; } } if (!_openTextBuffers.ContainsKey(buffer) && buffer.SupportsRename()) { _openTextBuffers[buffer] = new OpenTextBufferManager(this, buffer, _workspace, _textBufferFactoryService); return true; } return _openTextBuffers.ContainsKey(buffer); } private void OnSubjectBuffersConnected(object sender, SubjectBuffersConnectedEventArgs e) { AssertIsForeground(); foreach (var buffer in e.SubjectBuffers) { if (buffer.GetWorkspace() == _workspace) { if (TryPopulateOpenTextBufferManagerForBuffer(buffer)) { _openTextBuffers[buffer].ConnectToView(e.TextView); } } } } private void UpdateReferenceLocationsTask(JoinableTask<IInlineRenameLocationSet> findRenameLocationsTask) { AssertIsForeground(); var asyncToken = _asyncListener.BeginAsyncOperation("UpdateReferencesTask"); _allRenameLocationsTask = ThreadingContext.JoinableTaskFactory.RunAsync(async () => { var inlineRenameLocations = await findRenameLocationsTask.JoinAsync().ConfigureAwaitRunInline(); // It's unfortunate that _allRenameLocationsTask has a UI thread dependency (prevents continuations // from running prior to the completion of the UI operation), but the implementation does not currently // follow the originally-intended design. // https://github.com/dotnet/roslyn/issues/40890 await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, _cancellationTokenSource.Token); RaiseSessionSpansUpdated(inlineRenameLocations.Locations.ToImmutableArray()); return inlineRenameLocations; }); _allRenameLocationsTask.Task.CompletesAsyncOperation(asyncToken); UpdateConflictResolutionTask(); QueueApplyReplacements(); } public Workspace Workspace => _workspace; public OptionSet OptionSet => _optionSet; public bool HasRenameOverloads => _renameInfo.HasOverloads; public bool ForceRenameOverloads => _renameInfo.ForceRenameOverloads; public IInlineRenameUndoManager UndoManager { get; } public event EventHandler<ImmutableArray<InlineRenameLocation>> ReferenceLocationsChanged; public event EventHandler<IInlineRenameReplacementInfo> ReplacementsComputed; public event EventHandler ReplacementTextChanged; internal OpenTextBufferManager GetBufferManager(ITextBuffer buffer) => _openTextBuffers[buffer]; internal bool TryGetBufferManager(ITextBuffer buffer, out OpenTextBufferManager bufferManager) => _openTextBuffers.TryGetValue(buffer, out bufferManager); public void RefreshRenameSessionWithOptionsChanged(Option<bool> renameOption, bool newValue) { AssertIsForeground(); VerifyNotDismissed(); // Recompute the result only if the previous result was computed with a different flag if (_optionSet.GetOption(renameOption) != newValue) { _optionSet = _optionSet.WithChangedOption(renameOption, newValue); var cancellationToken = _cancellationTokenSource.Token; UpdateReferenceLocationsTask(ThreadingContext.JoinableTaskFactory.RunAsync(async () => { // Join prior work before proceeding, since it performs a required state update. // https://github.com/dotnet/roslyn/pull/34254#discussion_r267024593 // // The cancellation token is passed to the prior work when it starts, not when it's joined. This is // the equivalent of TaskContinuationOptions.LazyCancellation. await _allRenameLocationsTask.JoinAsync(CancellationToken.None).ConfigureAwait(false); await TaskScheduler.Default; return await _renameInfo.FindRenameLocationsAsync(_optionSet, cancellationToken).ConfigureAwait(false); })); } } private void Dismiss(bool rollbackTemporaryEdits) { _dismissed = true; _workspace.WorkspaceChanged -= OnWorkspaceChanged; _textBufferAssociatedViewService.SubjectBuffersConnected -= OnSubjectBuffersConnected; // Reenable completion now that the inline rename session is done _completionDisabledToken.Dispose(); foreach (var textBuffer in _openTextBuffers.Keys) { var document = textBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); var isClosed = document == null; var openBuffer = _openTextBuffers[textBuffer]; openBuffer.Disconnect(isClosed, rollbackTemporaryEdits); } this.UndoManager.Disconnect(); if (_triggerView != null && !_triggerView.IsClosed) { _triggerView.Selection.Clear(); } _renameService.ActiveSession = null; } private void VerifyNotDismissed() { if (_dismissed) { throw new InvalidOperationException(EditorFeaturesResources.This_session_has_already_been_dismissed); } } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs args) { if (args.Kind != WorkspaceChangeKind.DocumentChanged) { if (!_dismissed) { this.Cancel(); } } } private void RaiseSessionSpansUpdated(ImmutableArray<InlineRenameLocation> locations) { AssertIsForeground(); SetReferenceLocations(locations); // It's OK to call SetReferenceLocations with all documents, including unchangeable ones, // because they can't be opened, so the _openTextBuffers loop won't matter. In fact, the entire // inline rename is oblivious to unchangeable documents, we just need to filter out references // in them to avoid displaying them in the UI. // https://github.com/dotnet/roslyn/issues/41242 if (_workspace.IgnoreUnchangeableDocumentsWhenApplyingChanges) { locations = locations.WhereAsArray(l => l.Document.CanApplyChange()); } ReferenceLocationsChanged?.Invoke(this, locations); } private void SetReferenceLocations(ImmutableArray<InlineRenameLocation> locations) { AssertIsForeground(); var locationsByDocument = locations.ToLookup(l => l.Document.Id); _isApplyingEdit = true; foreach (var textBuffer in _openTextBuffers.Keys) { var documents = textBuffer.AsTextContainer().GetRelatedDocuments(); if (!documents.Any(d => locationsByDocument.Contains(d.Id))) { _openTextBuffers[textBuffer].SetReferenceSpans(SpecializedCollections.EmptyEnumerable<TextSpan>()); } else { var spans = documents.SelectMany(d => locationsByDocument[d.Id]).Select(l => l.TextSpan).Distinct(); _openTextBuffers[textBuffer].SetReferenceSpans(spans); } } _isApplyingEdit = false; } /// <summary> /// Updates the replacement text for the rename session and propagates it to all live buffers. /// </summary> internal void ApplyReplacementText(string replacementText, bool propagateEditImmediately) { AssertIsForeground(); VerifyNotDismissed(); this.ReplacementText = _renameInfo.GetFinalSymbolName(replacementText); var asyncToken = _asyncListener.BeginAsyncOperation(nameof(ApplyReplacementText)); Action propagateEditAction = delegate { AssertIsForeground(); if (_dismissed) { asyncToken.Dispose(); return; } _isApplyingEdit = true; using (Logger.LogBlock(FunctionId.Rename_ApplyReplacementText, replacementText, _cancellationTokenSource.Token)) { foreach (var openBuffer in _openTextBuffers.Values) { openBuffer.ApplyReplacementText(); } } _isApplyingEdit = false; // We already kicked off UpdateConflictResolutionTask below (outside the delegate). // Now that we are certain the replacement text has been propagated to all of the // open buffers, it is safe to actually apply the replacements it has calculated. // See https://devdiv.visualstudio.com/DevDiv/_workitems?_a=edit&id=227513 QueueApplyReplacements(); asyncToken.Dispose(); }; // Start the conflict resolution task but do not apply the results immediately. The // buffer changes performed in propagateEditAction can cause source control modal // dialogs to show. Those dialogs pump, and yield the UI thread to whatever work is // waiting to be done there, including our ApplyReplacements work. If ApplyReplacements // starts running on the UI thread while propagateEditAction is still updating buffers // on the UI thread, we crash because we try to enumerate the undo stack while an undo // transaction is still in process. Therefore, we defer QueueApplyReplacements until // after the buffers have been edited, and any modal dialogs have been completed. // In addition to avoiding the crash, this also ensures that the resolved conflict text // is applied after the simple text change is propagated. // See https://devdiv.visualstudio.com/DevDiv/_workitems?_a=edit&id=227513 UpdateConflictResolutionTask(); if (propagateEditImmediately) { propagateEditAction(); } else { // When responding to a text edit, we delay propagating the edit until the first transaction completes. ThreadingContext.JoinableTaskFactory.RunAsync(async () => { await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true); propagateEditAction(); }); } } private void UpdateConflictResolutionTask() { AssertIsForeground(); _conflictResolutionTaskCancellationSource.Cancel(); _conflictResolutionTaskCancellationSource = new CancellationTokenSource(); // If the replacement text is empty, we do not update the results of the conflict // resolution task. We instead wait for a non-empty identifier. if (this.ReplacementText == string.Empty) { return; } var replacementText = this.ReplacementText; var optionSet = _optionSet; var cancellationToken = _conflictResolutionTaskCancellationSource.Token; var asyncToken = _asyncListener.BeginAsyncOperation(nameof(UpdateConflictResolutionTask)); _conflictResolutionTask = ThreadingContext.JoinableTaskFactory.RunAsync(async () => { // Join prior work before proceeding, since it performs a required state update. // https://github.com/dotnet/roslyn/pull/34254#discussion_r267024593 // // If cancellation of the conflict resolution task is requested before the rename locations task // completes, we do not need to wait for rename before cancelling. The next conflict resolution task // will wait on the latest rename location task if/when necessary. var result = await _allRenameLocationsTask.JoinAsync(cancellationToken).ConfigureAwait(false); await TaskScheduler.Default; return await result.GetReplacementsAsync(replacementText, optionSet, cancellationToken).ConfigureAwait(false); }); _conflictResolutionTask.Task.CompletesAsyncOperation(asyncToken); } [SuppressMessage("Reliability", "CA2007:Consider calling ConfigureAwait on the awaited task", Justification = "False positive in methods using JTF: https://github.com/dotnet/roslyn-analyzers/issues/4283")] private void QueueApplyReplacements() { // If the replacement text is empty, we do not update the results of the conflict // resolution task. We instead wait for a non-empty identifier. if (this.ReplacementText == string.Empty) { return; } var cancellationToken = _conflictResolutionTaskCancellationSource.Token; var asyncToken = _asyncListener.BeginAsyncOperation(nameof(QueueApplyReplacements)); var replacementOperation = ThreadingContext.JoinableTaskFactory.RunAsync(async () => { var replacementInfo = await _conflictResolutionTask.JoinAsync(CancellationToken.None).ConfigureAwait(false); if (replacementInfo == null || cancellationToken.IsCancellationRequested) { return; } // Switch to a background thread for expensive work await TaskScheduler.Default; var computedMergeResult = await ComputeMergeResultAsync(replacementInfo, cancellationToken); await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken); ApplyReplacements(computedMergeResult.replacementInfo, computedMergeResult.mergeResult, cancellationToken); }); replacementOperation.Task.CompletesAsyncOperation(asyncToken); } private async Task<(IInlineRenameReplacementInfo replacementInfo, LinkedFileMergeSessionResult mergeResult)> ComputeMergeResultAsync(IInlineRenameReplacementInfo replacementInfo, CancellationToken cancellationToken) { var diffMergingSession = new LinkedFileDiffMergingSession(_baseSolution, replacementInfo.NewSolution, replacementInfo.NewSolution.GetChanges(_baseSolution)); var mergeResult = await diffMergingSession.MergeDiffsAsync(mergeConflictHandler: null, cancellationToken: cancellationToken).ConfigureAwait(false); return (replacementInfo, mergeResult); } private void ApplyReplacements(IInlineRenameReplacementInfo replacementInfo, LinkedFileMergeSessionResult mergeResult, CancellationToken cancellationToken) { AssertIsForeground(); cancellationToken.ThrowIfCancellationRequested(); RaiseReplacementsComputed(replacementInfo); _isApplyingEdit = true; foreach (var textBuffer in _openTextBuffers.Keys) { var documents = textBuffer.CurrentSnapshot.GetRelatedDocumentsWithChanges(); if (documents.Any()) { var textBufferManager = _openTextBuffers[textBuffer]; textBufferManager.ApplyConflictResolutionEdits(replacementInfo, mergeResult, documents, cancellationToken); } } _isApplyingEdit = false; } private void RaiseReplacementsComputed(IInlineRenameReplacementInfo resolution) { AssertIsForeground(); ReplacementsComputed?.Invoke(this, resolution); } private void LogRenameSession(RenameLogMessage.UserActionOutcome outcome, bool previewChanges) { if (_conflictResolutionTask == null) { return; } var conflictResolutionFinishedComputing = _conflictResolutionTask.Task.Status == TaskStatus.RanToCompletion; if (conflictResolutionFinishedComputing) { var result = _conflictResolutionTask.Task.Result; var replacementKinds = result.GetAllReplacementKinds().ToList(); Logger.Log(FunctionId.Rename_InlineSession_Session, RenameLogMessage.Create( _optionSet, outcome, conflictResolutionFinishedComputing, previewChanges, replacementKinds)); } else { Debug.Assert(outcome.HasFlag(RenameLogMessage.UserActionOutcome.Canceled)); Logger.Log(FunctionId.Rename_InlineSession_Session, RenameLogMessage.Create( _optionSet, outcome, conflictResolutionFinishedComputing, previewChanges, SpecializedCollections.EmptyList<InlineRenameReplacementKind>())); } } public void Cancel() => Cancel(rollbackTemporaryEdits: true); private void Cancel(bool rollbackTemporaryEdits) { AssertIsForeground(); VerifyNotDismissed(); LogRenameSession(RenameLogMessage.UserActionOutcome.Canceled, previewChanges: false); Dismiss(rollbackTemporaryEdits); EndRenameSession(); } public void Commit(bool previewChanges = false) => CommitWorker(previewChanges); /// <returns><see langword="true"/> if the rename operation was commited, <see /// langword="false"/> otherwise</returns> private bool CommitWorker(bool previewChanges) { AssertIsForeground(); VerifyNotDismissed(); // If the identifier was deleted (or didn't change at all) then cancel the operation. // Note: an alternative approach would be for the work we're doing (like detecting // conflicts) to quickly bail in the case of no change. However, that involves deeper // changes to the system and is less easy to validate that nothing happens. // // The only potential downside here would be if there was a language that wanted to // still 'rename' even if the identifier went away (or was unchanged). But that isn't // a case we're aware of, so it's fine to be opinionated here that we can quickly bail // in these cases. if (this.ReplacementText == string.Empty || this.ReplacementText == _initialRenameText) { Cancel(); return false; } previewChanges = previewChanges || OptionSet.GetOption(RenameOptions.PreviewChanges); var result = _uiThreadOperationExecutor.Execute( title: EditorFeaturesResources.Rename, defaultDescription: EditorFeaturesResources.Computing_Rename_information, allowCancellation: true, showProgress: false, action: context => CommitCore(context, previewChanges)); if (result == UIThreadOperationStatus.Canceled) { LogRenameSession(RenameLogMessage.UserActionOutcome.Canceled | RenameLogMessage.UserActionOutcome.Committed, previewChanges); Dismiss(rollbackTemporaryEdits: true); EndRenameSession(); return false; } return true; } private void EndRenameSession() { _debuggingWorkspaceService.BeforeDebuggingStateChanged -= OnBeforeDebuggingStateChanged; CancelAllOpenDocumentTrackingTasks(); RenameTrackingDismisser.DismissRenameTracking(_workspace, _workspace.GetOpenDocumentIds()); _inlineRenameSessionDurationLogBlock.Dispose(); } private void CancelAllOpenDocumentTrackingTasks() { _cancellationTokenSource.Cancel(); _conflictResolutionTaskCancellationSource.Cancel(); } private void CommitCore(IUIThreadOperationContext operationContext, bool previewChanges) { var eventName = previewChanges ? FunctionId.Rename_CommitCoreWithPreview : FunctionId.Rename_CommitCore; using (Logger.LogBlock(eventName, KeyValueLogMessage.Create(LogType.UserAction), operationContext.UserCancellationToken)) { var newSolution = _conflictResolutionTask.Join(operationContext.UserCancellationToken).NewSolution; if (previewChanges) { var previewService = _workspace.Services.GetService<IPreviewDialogService>(); operationContext.TakeOwnership(); newSolution = previewService.PreviewChanges( string.Format(EditorFeaturesResources.Preview_Changes_0, EditorFeaturesResources.Rename), "vs.csharp.refactoring.rename", string.Format(EditorFeaturesResources.Rename_0_to_1_colon, this.OriginalSymbolName, this.ReplacementText), _renameInfo.FullDisplayName, _renameInfo.Glyph, newSolution, _triggerDocument.Project.Solution); if (newSolution == null) { // User clicked cancel. return; } } // The user hasn't cancelled by now, so we're done waiting for them. Off to // rename! using var _ = operationContext.AddScope(allowCancellation: false, EditorFeaturesResources.Updating_files); Dismiss(rollbackTemporaryEdits: true); CancelAllOpenDocumentTrackingTasks(); _triggerView.Caret.PositionChanged += LogPositionChanged; ApplyRename(newSolution, operationContext); LogRenameSession(RenameLogMessage.UserActionOutcome.Committed, previewChanges); EndRenameSession(); _triggerView.Caret.PositionChanged -= LogPositionChanged; void LogPositionChanged(object sender, CaretPositionChangedEventArgs e) { try { throw new InvalidOperationException("Caret position changed during application of rename"); } catch (InvalidOperationException ex) when (FatalError.ReportAndCatch(ex)) { // Unreachable code due to ReportAndCatch Contract.ThrowIfTrue(true); } } } } private void ApplyRename(Solution newSolution, IUIThreadOperationContext operationContext) { var changes = _baseSolution.GetChanges(newSolution); var changedDocumentIDs = changes.GetProjectChanges().SelectMany(c => c.GetChangedDocuments()).ToList(); if (!_renameInfo.TryOnBeforeGlobalSymbolRenamed(_workspace, changedDocumentIDs, this.ReplacementText)) { var notificationService = _workspace.Services.GetService<INotificationService>(); notificationService.SendNotification( EditorFeaturesResources.Rename_operation_was_cancelled_or_is_not_valid, EditorFeaturesResources.Rename_Symbol, NotificationSeverity.Error); return; } using var undoTransaction = _workspace.OpenGlobalUndoTransaction(EditorFeaturesResources.Inline_Rename); var finalSolution = newSolution.Workspace.CurrentSolution; foreach (var id in changedDocumentIDs) { // If the document supports syntax tree, then create the new solution from the // updated syntax root. This should ensure that annotations are preserved, and // prevents the solution from having to reparse documents when we already have // the trees for them. If we don't support syntax, then just use the text of // the document. var newDocument = newSolution.GetDocument(id); if (newDocument.SupportsSyntaxTree) { // We pass CancellationToken.None here because we don't have a usable token to pass. The IUIThreadOperationContext // passed here as a cancellation token, but the caller in CommitCore has already turned off cancellation // because we're committed to the update at this point. If we ever want to pass cancellation here, we'd want to move this // part back out of this method and before the point where we've already opened a global transaction. var root = newDocument.GetSyntaxRootSynchronously(CancellationToken.None); finalSolution = finalSolution.WithDocumentSyntaxRoot(id, root); } else { var newText = newDocument.GetTextSynchronously(CancellationToken.None); finalSolution = finalSolution.WithDocumentText(id, newText); } // Make sure to include any document rename as well finalSolution = finalSolution.WithDocumentName(id, newDocument.Name); } if (_workspace.TryApplyChanges(finalSolution)) { // Since rename can apply file changes as well, and those file // changes can generate new document ids, include added documents // as well as changed documents. This also ensures that any document // that was removed is not included var finalChanges = _workspace.CurrentSolution.GetChanges(_baseSolution); var finalChangedIds = finalChanges .GetProjectChanges() .SelectMany(c => c.GetChangedDocuments().Concat(c.GetAddedDocuments())) .ToList(); if (!_renameInfo.TryOnAfterGlobalSymbolRenamed(_workspace, finalChangedIds, this.ReplacementText)) { var notificationService = _workspace.Services.GetService<INotificationService>(); operationContext.TakeOwnership(); notificationService.SendNotification( EditorFeaturesResources.Rename_operation_was_not_properly_completed_Some_file_might_not_have_been_updated, EditorFeaturesResources.Rename_Symbol, NotificationSeverity.Information); } undoTransaction.Commit(); } } internal bool TryGetContainingEditableSpan(SnapshotPoint point, out SnapshotSpan editableSpan) { editableSpan = default; if (!_openTextBuffers.TryGetValue(point.Snapshot.TextBuffer, out var bufferManager)) { return false; } foreach (var span in bufferManager.GetEditableSpansForSnapshot(point.Snapshot)) { if (span.Contains(point) || span.End == point) { editableSpan = span; return true; } } return false; } internal bool IsInOpenTextBuffer(SnapshotPoint point) => _openTextBuffers.ContainsKey(point.Snapshot.TextBuffer); internal TestAccessor GetTestAccessor() => new TestAccessor(this); public struct TestAccessor { private readonly InlineRenameSession _inlineRenameSession; public TestAccessor(InlineRenameSession inlineRenameSession) => _inlineRenameSession = inlineRenameSession; public bool CommitWorker(bool previewChanges) => _inlineRenameSession.CommitWorker(previewChanges); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Undo; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Threading; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal partial class InlineRenameSession : ForegroundThreadAffinitizedObject, IInlineRenameSession, IFeatureController { private readonly Workspace _workspace; private readonly InlineRenameService _renameService; private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; private readonly ITextBufferAssociatedViewService _textBufferAssociatedViewService; private readonly ITextBufferFactoryService _textBufferFactoryService; private readonly IFeatureService _featureService; private readonly IFeatureDisableToken _completionDisabledToken; private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices; private readonly IDebuggingWorkspaceService _debuggingWorkspaceService; private readonly IAsynchronousOperationListener _asyncListener; private readonly Solution _baseSolution; private readonly Document _triggerDocument; private readonly ITextView _triggerView; private readonly IDisposable _inlineRenameSessionDurationLogBlock; private bool _dismissed; private bool _isApplyingEdit; private string _replacementText; private OptionSet _optionSet; private readonly Dictionary<ITextBuffer, OpenTextBufferManager> _openTextBuffers = new Dictionary<ITextBuffer, OpenTextBufferManager>(); /// <summary> /// If non-null, the current text of the replacement. Linked spans added will automatically be updated with this /// text. /// </summary> public string ReplacementText { get { return _replacementText; } private set { _replacementText = value; ReplacementTextChanged?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Information about whether a file rename should be allowed as part /// of the rename operation, as determined by the language /// </summary> public InlineRenameFileRenameInfo FileRenameInfo { get; } /// <summary> /// The task which computes the main rename locations against the original workspace /// snapshot. /// </summary> private JoinableTask<IInlineRenameLocationSet> _allRenameLocationsTask; /// <summary> /// The cancellation token for most work being done by the inline rename session. This /// includes the <see cref="_allRenameLocationsTask"/> tasks. /// </summary> private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); /// <summary> /// This task is a continuation of the <see cref="_allRenameLocationsTask"/> that is the result of computing /// the resolutions of the rename spans for the current replacementText. /// </summary> private JoinableTask<IInlineRenameReplacementInfo> _conflictResolutionTask; /// <summary> /// The cancellation source for <see cref="_conflictResolutionTask"/>. /// </summary> private CancellationTokenSource _conflictResolutionTaskCancellationSource = new CancellationTokenSource(); private readonly IInlineRenameInfo _renameInfo; /// <summary> /// The initial text being renamed. /// </summary> private readonly string _initialRenameText; public InlineRenameSession( IThreadingContext threadingContext, InlineRenameService renameService, Workspace workspace, SnapshotSpan triggerSpan, IInlineRenameInfo renameInfo, IUIThreadOperationExecutor uiThreadOperationExecutor, ITextBufferAssociatedViewService textBufferAssociatedViewService, ITextBufferFactoryService textBufferFactoryService, IFeatureServiceFactory featureServiceFactory, IEnumerable<IRefactorNotifyService> refactorNotifyServices, IAsynchronousOperationListener asyncListener) : base(threadingContext, assertIsForeground: true) { // This should always be touching a symbol since we verified that upon invocation _renameInfo = renameInfo; _triggerDocument = triggerSpan.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (_triggerDocument == null) { throw new InvalidOperationException(EditorFeaturesResources.The_triggerSpan_is_not_included_in_the_given_workspace); } _inlineRenameSessionDurationLogBlock = Logger.LogBlock(FunctionId.Rename_InlineSession, CancellationToken.None); _workspace = workspace; _workspace.WorkspaceChanged += OnWorkspaceChanged; _textBufferFactoryService = textBufferFactoryService; _textBufferAssociatedViewService = textBufferAssociatedViewService; _textBufferAssociatedViewService.SubjectBuffersConnected += OnSubjectBuffersConnected; // Disable completion when an inline rename session starts _featureService = featureServiceFactory.GlobalFeatureService; _completionDisabledToken = _featureService.Disable(PredefinedEditorFeatureNames.Completion, this); _renameService = renameService; _uiThreadOperationExecutor = uiThreadOperationExecutor; _refactorNotifyServices = refactorNotifyServices; _asyncListener = asyncListener; _triggerView = textBufferAssociatedViewService.GetAssociatedTextViews(triggerSpan.Snapshot.TextBuffer).FirstOrDefault(v => v.HasAggregateFocus) ?? textBufferAssociatedViewService.GetAssociatedTextViews(triggerSpan.Snapshot.TextBuffer).First(); _optionSet = renameInfo.ForceRenameOverloads ? workspace.Options.WithChangedOption(RenameOptions.RenameOverloads, true) : workspace.Options; _initialRenameText = triggerSpan.GetText(); this.ReplacementText = _initialRenameText; _baseSolution = _triggerDocument.Project.Solution; this.UndoManager = workspace.Services.GetService<IInlineRenameUndoManager>(); _debuggingWorkspaceService = workspace.Services.GetService<IDebuggingWorkspaceService>(); _debuggingWorkspaceService.BeforeDebuggingStateChanged += OnBeforeDebuggingStateChanged; if (_renameInfo is IInlineRenameInfoWithFileRename renameInfoWithFileRename) { FileRenameInfo = renameInfoWithFileRename.GetFileRenameInfo(); } else { FileRenameInfo = InlineRenameFileRenameInfo.NotAllowed; } InitializeOpenBuffers(triggerSpan); } private void OnBeforeDebuggingStateChanged(object sender, DebuggingStateChangedEventArgs args) { if (args.After == DebuggingState.Run) { // It's too late for us to change anything, which means we can neither commit nor // rollback changes to cancel. End the rename session but keep all open buffers in // their current state. Cancel(rollbackTemporaryEdits: false); } } public string OriginalSymbolName => _renameInfo.DisplayName; // Used to aid the investigation of https://github.com/dotnet/roslyn/issues/7364 private class NullTextBufferException : Exception { #pragma warning disable IDE0052 // Remove unread private members private readonly Document _document; private readonly SourceText _text; #pragma warning restore IDE0052 // Remove unread private members public NullTextBufferException(Document document, SourceText text) : base("Cannot retrieve textbuffer from document.") { _document = document; _text = text; } } private void InitializeOpenBuffers(SnapshotSpan triggerSpan) { using (Logger.LogBlock(FunctionId.Rename_CreateOpenTextBufferManagerForAllOpenDocs, CancellationToken.None)) { var openBuffers = new HashSet<ITextBuffer>(); foreach (var d in _workspace.GetOpenDocumentIds()) { var document = _baseSolution.GetDocument(d); if (document == null) { continue; } Contract.ThrowIfFalse(document.TryGetText(out var text)); Contract.ThrowIfNull(text); var textSnapshot = text.FindCorrespondingEditorTextSnapshot(); if (textSnapshot == null) { FatalError.ReportAndCatch(new NullTextBufferException(document, text)); continue; } Contract.ThrowIfNull(textSnapshot.TextBuffer); openBuffers.Add(textSnapshot.TextBuffer); } foreach (var buffer in openBuffers) { TryPopulateOpenTextBufferManagerForBuffer(buffer); } } var startingSpan = triggerSpan.Span; // Select this span if we didn't already have something selected var selections = _triggerView.Selection.GetSnapshotSpansOnBuffer(triggerSpan.Snapshot.TextBuffer); if (!selections.Any() || selections.First().IsEmpty || !startingSpan.Contains(selections.First())) { _triggerView.SetSelection(new SnapshotSpan(triggerSpan.Snapshot, startingSpan)); } this.UndoManager.CreateInitialState(this.ReplacementText, _triggerView.Selection, new SnapshotSpan(triggerSpan.Snapshot, startingSpan)); _openTextBuffers[triggerSpan.Snapshot.TextBuffer].SetReferenceSpans(SpecializedCollections.SingletonEnumerable(startingSpan.ToTextSpan())); UpdateReferenceLocationsTask(ThreadingContext.JoinableTaskFactory.RunAsync( () => _renameInfo.FindRenameLocationsAsync(_optionSet, _cancellationTokenSource.Token))); RenameTrackingDismisser.DismissRenameTracking(_workspace, _workspace.GetOpenDocumentIds()); } private bool TryPopulateOpenTextBufferManagerForBuffer(ITextBuffer buffer) { AssertIsForeground(); VerifyNotDismissed(); if (_workspace.Kind == WorkspaceKind.Interactive) { Debug.Assert(buffer.GetRelatedDocuments().Count() == 1); Debug.Assert(buffer.IsReadOnly(0) == buffer.IsReadOnly(VisualStudio.Text.Span.FromBounds(0, buffer.CurrentSnapshot.Length))); // All or nothing. if (buffer.IsReadOnly(0)) { return false; } } if (!_openTextBuffers.ContainsKey(buffer) && buffer.SupportsRename()) { _openTextBuffers[buffer] = new OpenTextBufferManager(this, buffer, _workspace, _textBufferFactoryService); return true; } return _openTextBuffers.ContainsKey(buffer); } private void OnSubjectBuffersConnected(object sender, SubjectBuffersConnectedEventArgs e) { AssertIsForeground(); foreach (var buffer in e.SubjectBuffers) { if (buffer.GetWorkspace() == _workspace) { if (TryPopulateOpenTextBufferManagerForBuffer(buffer)) { _openTextBuffers[buffer].ConnectToView(e.TextView); } } } } private void UpdateReferenceLocationsTask(JoinableTask<IInlineRenameLocationSet> findRenameLocationsTask) { AssertIsForeground(); var asyncToken = _asyncListener.BeginAsyncOperation("UpdateReferencesTask"); _allRenameLocationsTask = ThreadingContext.JoinableTaskFactory.RunAsync(async () => { var inlineRenameLocations = await findRenameLocationsTask.JoinAsync().ConfigureAwaitRunInline(); // It's unfortunate that _allRenameLocationsTask has a UI thread dependency (prevents continuations // from running prior to the completion of the UI operation), but the implementation does not currently // follow the originally-intended design. // https://github.com/dotnet/roslyn/issues/40890 await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, _cancellationTokenSource.Token); RaiseSessionSpansUpdated(inlineRenameLocations.Locations.ToImmutableArray()); return inlineRenameLocations; }); _allRenameLocationsTask.Task.CompletesAsyncOperation(asyncToken); UpdateConflictResolutionTask(); QueueApplyReplacements(); } public Workspace Workspace => _workspace; public OptionSet OptionSet => _optionSet; public bool HasRenameOverloads => _renameInfo.HasOverloads; public bool ForceRenameOverloads => _renameInfo.ForceRenameOverloads; public IInlineRenameUndoManager UndoManager { get; } public event EventHandler<ImmutableArray<InlineRenameLocation>> ReferenceLocationsChanged; public event EventHandler<IInlineRenameReplacementInfo> ReplacementsComputed; public event EventHandler ReplacementTextChanged; internal OpenTextBufferManager GetBufferManager(ITextBuffer buffer) => _openTextBuffers[buffer]; internal bool TryGetBufferManager(ITextBuffer buffer, out OpenTextBufferManager bufferManager) => _openTextBuffers.TryGetValue(buffer, out bufferManager); public void RefreshRenameSessionWithOptionsChanged(Option<bool> renameOption, bool newValue) { AssertIsForeground(); VerifyNotDismissed(); // Recompute the result only if the previous result was computed with a different flag if (_optionSet.GetOption(renameOption) != newValue) { _optionSet = _optionSet.WithChangedOption(renameOption, newValue); var cancellationToken = _cancellationTokenSource.Token; UpdateReferenceLocationsTask(ThreadingContext.JoinableTaskFactory.RunAsync(async () => { // Join prior work before proceeding, since it performs a required state update. // https://github.com/dotnet/roslyn/pull/34254#discussion_r267024593 // // The cancellation token is passed to the prior work when it starts, not when it's joined. This is // the equivalent of TaskContinuationOptions.LazyCancellation. await _allRenameLocationsTask.JoinAsync(CancellationToken.None).ConfigureAwait(false); await TaskScheduler.Default; return await _renameInfo.FindRenameLocationsAsync(_optionSet, cancellationToken).ConfigureAwait(false); })); } } private void Dismiss(bool rollbackTemporaryEdits) { _dismissed = true; _workspace.WorkspaceChanged -= OnWorkspaceChanged; _textBufferAssociatedViewService.SubjectBuffersConnected -= OnSubjectBuffersConnected; // Reenable completion now that the inline rename session is done _completionDisabledToken.Dispose(); foreach (var textBuffer in _openTextBuffers.Keys) { var document = textBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); var isClosed = document == null; var openBuffer = _openTextBuffers[textBuffer]; openBuffer.Disconnect(isClosed, rollbackTemporaryEdits); } this.UndoManager.Disconnect(); if (_triggerView != null && !_triggerView.IsClosed) { _triggerView.Selection.Clear(); } _renameService.ActiveSession = null; } private void VerifyNotDismissed() { if (_dismissed) { throw new InvalidOperationException(EditorFeaturesResources.This_session_has_already_been_dismissed); } } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs args) { if (args.Kind != WorkspaceChangeKind.DocumentChanged) { if (!_dismissed) { this.Cancel(); } } } private void RaiseSessionSpansUpdated(ImmutableArray<InlineRenameLocation> locations) { AssertIsForeground(); SetReferenceLocations(locations); // It's OK to call SetReferenceLocations with all documents, including unchangeable ones, // because they can't be opened, so the _openTextBuffers loop won't matter. In fact, the entire // inline rename is oblivious to unchangeable documents, we just need to filter out references // in them to avoid displaying them in the UI. // https://github.com/dotnet/roslyn/issues/41242 if (_workspace.IgnoreUnchangeableDocumentsWhenApplyingChanges) { locations = locations.WhereAsArray(l => l.Document.CanApplyChange()); } ReferenceLocationsChanged?.Invoke(this, locations); } private void SetReferenceLocations(ImmutableArray<InlineRenameLocation> locations) { AssertIsForeground(); var locationsByDocument = locations.ToLookup(l => l.Document.Id); _isApplyingEdit = true; foreach (var textBuffer in _openTextBuffers.Keys) { var documents = textBuffer.AsTextContainer().GetRelatedDocuments(); if (!documents.Any(d => locationsByDocument.Contains(d.Id))) { _openTextBuffers[textBuffer].SetReferenceSpans(SpecializedCollections.EmptyEnumerable<TextSpan>()); } else { var spans = documents.SelectMany(d => locationsByDocument[d.Id]).Select(l => l.TextSpan).Distinct(); _openTextBuffers[textBuffer].SetReferenceSpans(spans); } } _isApplyingEdit = false; } /// <summary> /// Updates the replacement text for the rename session and propagates it to all live buffers. /// </summary> internal void ApplyReplacementText(string replacementText, bool propagateEditImmediately) { AssertIsForeground(); VerifyNotDismissed(); this.ReplacementText = _renameInfo.GetFinalSymbolName(replacementText); var asyncToken = _asyncListener.BeginAsyncOperation(nameof(ApplyReplacementText)); Action propagateEditAction = delegate { AssertIsForeground(); if (_dismissed) { asyncToken.Dispose(); return; } _isApplyingEdit = true; using (Logger.LogBlock(FunctionId.Rename_ApplyReplacementText, replacementText, _cancellationTokenSource.Token)) { foreach (var openBuffer in _openTextBuffers.Values) { openBuffer.ApplyReplacementText(); } } _isApplyingEdit = false; // We already kicked off UpdateConflictResolutionTask below (outside the delegate). // Now that we are certain the replacement text has been propagated to all of the // open buffers, it is safe to actually apply the replacements it has calculated. // See https://devdiv.visualstudio.com/DevDiv/_workitems?_a=edit&id=227513 QueueApplyReplacements(); asyncToken.Dispose(); }; // Start the conflict resolution task but do not apply the results immediately. The // buffer changes performed in propagateEditAction can cause source control modal // dialogs to show. Those dialogs pump, and yield the UI thread to whatever work is // waiting to be done there, including our ApplyReplacements work. If ApplyReplacements // starts running on the UI thread while propagateEditAction is still updating buffers // on the UI thread, we crash because we try to enumerate the undo stack while an undo // transaction is still in process. Therefore, we defer QueueApplyReplacements until // after the buffers have been edited, and any modal dialogs have been completed. // In addition to avoiding the crash, this also ensures that the resolved conflict text // is applied after the simple text change is propagated. // See https://devdiv.visualstudio.com/DevDiv/_workitems?_a=edit&id=227513 UpdateConflictResolutionTask(); if (propagateEditImmediately) { propagateEditAction(); } else { // When responding to a text edit, we delay propagating the edit until the first transaction completes. ThreadingContext.JoinableTaskFactory.RunAsync(async () => { await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true); propagateEditAction(); }); } } private void UpdateConflictResolutionTask() { AssertIsForeground(); _conflictResolutionTaskCancellationSource.Cancel(); _conflictResolutionTaskCancellationSource = new CancellationTokenSource(); // If the replacement text is empty, we do not update the results of the conflict // resolution task. We instead wait for a non-empty identifier. if (this.ReplacementText == string.Empty) { return; } var replacementText = this.ReplacementText; var optionSet = _optionSet; var cancellationToken = _conflictResolutionTaskCancellationSource.Token; var asyncToken = _asyncListener.BeginAsyncOperation(nameof(UpdateConflictResolutionTask)); _conflictResolutionTask = ThreadingContext.JoinableTaskFactory.RunAsync(async () => { // Join prior work before proceeding, since it performs a required state update. // https://github.com/dotnet/roslyn/pull/34254#discussion_r267024593 // // If cancellation of the conflict resolution task is requested before the rename locations task // completes, we do not need to wait for rename before cancelling. The next conflict resolution task // will wait on the latest rename location task if/when necessary. var result = await _allRenameLocationsTask.JoinAsync(cancellationToken).ConfigureAwait(false); await TaskScheduler.Default; return await result.GetReplacementsAsync(replacementText, optionSet, cancellationToken).ConfigureAwait(false); }); _conflictResolutionTask.Task.CompletesAsyncOperation(asyncToken); } [SuppressMessage("Reliability", "CA2007:Consider calling ConfigureAwait on the awaited task", Justification = "False positive in methods using JTF: https://github.com/dotnet/roslyn-analyzers/issues/4283")] private void QueueApplyReplacements() { // If the replacement text is empty, we do not update the results of the conflict // resolution task. We instead wait for a non-empty identifier. if (this.ReplacementText == string.Empty) { return; } var cancellationToken = _conflictResolutionTaskCancellationSource.Token; var asyncToken = _asyncListener.BeginAsyncOperation(nameof(QueueApplyReplacements)); var replacementOperation = ThreadingContext.JoinableTaskFactory.RunAsync(async () => { var replacementInfo = await _conflictResolutionTask.JoinAsync(CancellationToken.None).ConfigureAwait(false); if (replacementInfo == null || cancellationToken.IsCancellationRequested) { return; } // Switch to a background thread for expensive work await TaskScheduler.Default; var computedMergeResult = await ComputeMergeResultAsync(replacementInfo, cancellationToken); await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken); ApplyReplacements(computedMergeResult.replacementInfo, computedMergeResult.mergeResult, cancellationToken); }); replacementOperation.Task.CompletesAsyncOperation(asyncToken); } private async Task<(IInlineRenameReplacementInfo replacementInfo, LinkedFileMergeSessionResult mergeResult)> ComputeMergeResultAsync(IInlineRenameReplacementInfo replacementInfo, CancellationToken cancellationToken) { var diffMergingSession = new LinkedFileDiffMergingSession(_baseSolution, replacementInfo.NewSolution, replacementInfo.NewSolution.GetChanges(_baseSolution)); var mergeResult = await diffMergingSession.MergeDiffsAsync(mergeConflictHandler: null, cancellationToken: cancellationToken).ConfigureAwait(false); return (replacementInfo, mergeResult); } private void ApplyReplacements(IInlineRenameReplacementInfo replacementInfo, LinkedFileMergeSessionResult mergeResult, CancellationToken cancellationToken) { AssertIsForeground(); cancellationToken.ThrowIfCancellationRequested(); RaiseReplacementsComputed(replacementInfo); _isApplyingEdit = true; foreach (var textBuffer in _openTextBuffers.Keys) { var documents = textBuffer.CurrentSnapshot.GetRelatedDocumentsWithChanges(); if (documents.Any()) { var textBufferManager = _openTextBuffers[textBuffer]; textBufferManager.ApplyConflictResolutionEdits(replacementInfo, mergeResult, documents, cancellationToken); } } _isApplyingEdit = false; } private void RaiseReplacementsComputed(IInlineRenameReplacementInfo resolution) { AssertIsForeground(); ReplacementsComputed?.Invoke(this, resolution); } private void LogRenameSession(RenameLogMessage.UserActionOutcome outcome, bool previewChanges) { if (_conflictResolutionTask == null) { return; } var conflictResolutionFinishedComputing = _conflictResolutionTask.Task.Status == TaskStatus.RanToCompletion; if (conflictResolutionFinishedComputing) { var result = _conflictResolutionTask.Task.Result; var replacementKinds = result.GetAllReplacementKinds().ToList(); Logger.Log(FunctionId.Rename_InlineSession_Session, RenameLogMessage.Create( _optionSet, outcome, conflictResolutionFinishedComputing, previewChanges, replacementKinds)); } else { Debug.Assert(outcome.HasFlag(RenameLogMessage.UserActionOutcome.Canceled)); Logger.Log(FunctionId.Rename_InlineSession_Session, RenameLogMessage.Create( _optionSet, outcome, conflictResolutionFinishedComputing, previewChanges, SpecializedCollections.EmptyList<InlineRenameReplacementKind>())); } } public void Cancel() => Cancel(rollbackTemporaryEdits: true); private void Cancel(bool rollbackTemporaryEdits) { AssertIsForeground(); VerifyNotDismissed(); LogRenameSession(RenameLogMessage.UserActionOutcome.Canceled, previewChanges: false); Dismiss(rollbackTemporaryEdits); EndRenameSession(); } public void Commit(bool previewChanges = false) => CommitWorker(previewChanges); /// <returns><see langword="true"/> if the rename operation was commited, <see /// langword="false"/> otherwise</returns> private bool CommitWorker(bool previewChanges) { AssertIsForeground(); VerifyNotDismissed(); // If the identifier was deleted (or didn't change at all) then cancel the operation. // Note: an alternative approach would be for the work we're doing (like detecting // conflicts) to quickly bail in the case of no change. However, that involves deeper // changes to the system and is less easy to validate that nothing happens. // // The only potential downside here would be if there was a language that wanted to // still 'rename' even if the identifier went away (or was unchanged). But that isn't // a case we're aware of, so it's fine to be opinionated here that we can quickly bail // in these cases. if (this.ReplacementText == string.Empty || this.ReplacementText == _initialRenameText) { Cancel(); return false; } previewChanges = previewChanges || OptionSet.GetOption(RenameOptions.PreviewChanges); var result = _uiThreadOperationExecutor.Execute( title: EditorFeaturesResources.Rename, defaultDescription: EditorFeaturesResources.Computing_Rename_information, allowCancellation: true, showProgress: false, action: context => CommitCore(context, previewChanges)); if (result == UIThreadOperationStatus.Canceled) { LogRenameSession(RenameLogMessage.UserActionOutcome.Canceled | RenameLogMessage.UserActionOutcome.Committed, previewChanges); Dismiss(rollbackTemporaryEdits: true); EndRenameSession(); return false; } return true; } private void EndRenameSession() { _debuggingWorkspaceService.BeforeDebuggingStateChanged -= OnBeforeDebuggingStateChanged; CancelAllOpenDocumentTrackingTasks(); RenameTrackingDismisser.DismissRenameTracking(_workspace, _workspace.GetOpenDocumentIds()); _inlineRenameSessionDurationLogBlock.Dispose(); } private void CancelAllOpenDocumentTrackingTasks() { _cancellationTokenSource.Cancel(); _conflictResolutionTaskCancellationSource.Cancel(); } private void CommitCore(IUIThreadOperationContext operationContext, bool previewChanges) { var eventName = previewChanges ? FunctionId.Rename_CommitCoreWithPreview : FunctionId.Rename_CommitCore; using (Logger.LogBlock(eventName, KeyValueLogMessage.Create(LogType.UserAction), operationContext.UserCancellationToken)) { var newSolution = _conflictResolutionTask.Join(operationContext.UserCancellationToken).NewSolution; if (previewChanges) { var previewService = _workspace.Services.GetService<IPreviewDialogService>(); operationContext.TakeOwnership(); newSolution = previewService.PreviewChanges( string.Format(EditorFeaturesResources.Preview_Changes_0, EditorFeaturesResources.Rename), "vs.csharp.refactoring.rename", string.Format(EditorFeaturesResources.Rename_0_to_1_colon, this.OriginalSymbolName, this.ReplacementText), _renameInfo.FullDisplayName, _renameInfo.Glyph, newSolution, _triggerDocument.Project.Solution); if (newSolution == null) { // User clicked cancel. return; } } // The user hasn't cancelled by now, so we're done waiting for them. Off to // rename! using var _ = operationContext.AddScope(allowCancellation: false, EditorFeaturesResources.Updating_files); Dismiss(rollbackTemporaryEdits: true); CancelAllOpenDocumentTrackingTasks(); _triggerView.Caret.PositionChanged += LogPositionChanged; ApplyRename(newSolution, operationContext); LogRenameSession(RenameLogMessage.UserActionOutcome.Committed, previewChanges); EndRenameSession(); _triggerView.Caret.PositionChanged -= LogPositionChanged; void LogPositionChanged(object sender, CaretPositionChangedEventArgs e) { try { throw new InvalidOperationException("Caret position changed during application of rename"); } catch (InvalidOperationException ex) when (FatalError.ReportAndCatch(ex)) { // Unreachable code due to ReportAndCatch Contract.ThrowIfTrue(true); } } } } private void ApplyRename(Solution newSolution, IUIThreadOperationContext operationContext) { var changes = _baseSolution.GetChanges(newSolution); var changedDocumentIDs = changes.GetProjectChanges().SelectMany(c => c.GetChangedDocuments()).ToList(); if (!_renameInfo.TryOnBeforeGlobalSymbolRenamed(_workspace, changedDocumentIDs, this.ReplacementText)) { var notificationService = _workspace.Services.GetService<INotificationService>(); notificationService.SendNotification( EditorFeaturesResources.Rename_operation_was_cancelled_or_is_not_valid, EditorFeaturesResources.Rename_Symbol, NotificationSeverity.Error); return; } using var undoTransaction = _workspace.OpenGlobalUndoTransaction(EditorFeaturesResources.Inline_Rename); var finalSolution = newSolution.Workspace.CurrentSolution; foreach (var id in changedDocumentIDs) { // If the document supports syntax tree, then create the new solution from the // updated syntax root. This should ensure that annotations are preserved, and // prevents the solution from having to reparse documents when we already have // the trees for them. If we don't support syntax, then just use the text of // the document. var newDocument = newSolution.GetDocument(id); if (newDocument.SupportsSyntaxTree) { // We pass CancellationToken.None here because we don't have a usable token to pass. The IUIThreadOperationContext // passed here as a cancellation token, but the caller in CommitCore has already turned off cancellation // because we're committed to the update at this point. If we ever want to pass cancellation here, we'd want to move this // part back out of this method and before the point where we've already opened a global transaction. var root = newDocument.GetSyntaxRootSynchronously(CancellationToken.None); finalSolution = finalSolution.WithDocumentSyntaxRoot(id, root); } else { var newText = newDocument.GetTextSynchronously(CancellationToken.None); finalSolution = finalSolution.WithDocumentText(id, newText); } // Make sure to include any document rename as well finalSolution = finalSolution.WithDocumentName(id, newDocument.Name); } if (_workspace.TryApplyChanges(finalSolution)) { // Since rename can apply file changes as well, and those file // changes can generate new document ids, include added documents // as well as changed documents. This also ensures that any document // that was removed is not included var finalChanges = _workspace.CurrentSolution.GetChanges(_baseSolution); var finalChangedIds = finalChanges .GetProjectChanges() .SelectMany(c => c.GetChangedDocuments().Concat(c.GetAddedDocuments())) .ToList(); if (!_renameInfo.TryOnAfterGlobalSymbolRenamed(_workspace, finalChangedIds, this.ReplacementText)) { var notificationService = _workspace.Services.GetService<INotificationService>(); operationContext.TakeOwnership(); notificationService.SendNotification( EditorFeaturesResources.Rename_operation_was_not_properly_completed_Some_file_might_not_have_been_updated, EditorFeaturesResources.Rename_Symbol, NotificationSeverity.Information); } undoTransaction.Commit(); } } internal bool TryGetContainingEditableSpan(SnapshotPoint point, out SnapshotSpan editableSpan) { editableSpan = default; if (!_openTextBuffers.TryGetValue(point.Snapshot.TextBuffer, out var bufferManager)) { return false; } foreach (var span in bufferManager.GetEditableSpansForSnapshot(point.Snapshot)) { if (span.Contains(point) || span.End == point) { editableSpan = span; return true; } } return false; } internal bool IsInOpenTextBuffer(SnapshotPoint point) => _openTextBuffers.ContainsKey(point.Snapshot.TextBuffer); internal TestAccessor GetTestAccessor() => new TestAccessor(this); public struct TestAccessor { private readonly InlineRenameSession _inlineRenameSession; public TestAccessor(InlineRenameSession inlineRenameSession) => _inlineRenameSession = inlineRenameSession; public bool CommitWorker(bool previewChanges) => _inlineRenameSession.CommitWorker(previewChanges); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Features/Core/Portable/CodeLens/ReferenceMethodDescriptor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.Serialization; namespace Microsoft.CodeAnalysis.CodeLens { /// <summary> /// A caller method of a callee /// </summary> [DataContract] internal sealed class ReferenceMethodDescriptor { /// <summary> /// Returns method's fully quilified name without parameters /// </summary> [DataMember(Order = 0)] public string FullName { get; private set; } /// <summary> /// Returns method's file path. /// </summary> [DataMember(Order = 1)] public string FilePath { get; private set; } /// <summary> /// Returns output file path for the project containing the method. /// </summary> [DataMember(Order = 2)] public string OutputFilePath { get; private set; } /// <summary> /// Describe a caller method of a callee /// </summary> /// <param name="fullName">Method's fully qualified name</param> /// <param name="filePath">Method full path</param> /// <remarks> /// Method full name is expected to be in the .NET full name type convention. That is, /// namespace/type is delimited by '.' and nested type is delimited by '+' /// </remarks> public ReferenceMethodDescriptor(string fullName, string filePath, string outputFilePath) { FullName = fullName; FilePath = filePath; OutputFilePath = outputFilePath; } } }
// Licensed to the .NET Foundation under one or more 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.Runtime.Serialization; namespace Microsoft.CodeAnalysis.CodeLens { /// <summary> /// A caller method of a callee /// </summary> [DataContract] internal sealed class ReferenceMethodDescriptor { /// <summary> /// Returns method's fully quilified name without parameters /// </summary> [DataMember(Order = 0)] public string FullName { get; private set; } /// <summary> /// Returns method's file path. /// </summary> [DataMember(Order = 1)] public string FilePath { get; private set; } /// <summary> /// Returns output file path for the project containing the method. /// </summary> [DataMember(Order = 2)] public string OutputFilePath { get; private set; } /// <summary> /// Describe a caller method of a callee /// </summary> /// <param name="fullName">Method's fully qualified name</param> /// <param name="filePath">Method full path</param> /// <remarks> /// Method full name is expected to be in the .NET full name type convention. That is, /// namespace/type is delimited by '.' and nested type is delimited by '+' /// </remarks> public ReferenceMethodDescriptor(string fullName, string filePath, string outputFilePath) { FullName = fullName; FilePath = filePath; OutputFilePath = outputFilePath; } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Features/Core/Portable/ExtractMethod/MethodExtractor.VariableInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract partial class MethodExtractor { protected class VariableInfo { private readonly VariableSymbol _variableSymbol; private readonly VariableStyle _variableStyle; private readonly bool _useAsReturnValue; public VariableInfo( VariableSymbol variableSymbol, VariableStyle variableStyle, bool useAsReturnValue = false) { _variableSymbol = variableSymbol; _variableStyle = variableStyle; _useAsReturnValue = useAsReturnValue; } public bool UseAsReturnValue { get { Contract.ThrowIfFalse(!_useAsReturnValue || _variableStyle.ReturnStyle.ReturnBehavior != ReturnBehavior.None); return _useAsReturnValue; } } public bool CanBeUsedAsReturnValue { get { return _variableStyle.ReturnStyle.ReturnBehavior != ReturnBehavior.None; } } public bool UseAsParameter { get { return (!_useAsReturnValue && _variableStyle.ParameterStyle.ParameterBehavior != ParameterBehavior.None) || (_useAsReturnValue && _variableStyle.ReturnStyle.ParameterBehavior != ParameterBehavior.None); } } public ParameterBehavior ParameterModifier { get { return _useAsReturnValue ? _variableStyle.ReturnStyle.ParameterBehavior : _variableStyle.ParameterStyle.ParameterBehavior; } } public DeclarationBehavior GetDeclarationBehavior(CancellationToken cancellationToken) { if (_useAsReturnValue) { return _variableStyle.ReturnStyle.DeclarationBehavior; } if (_variableSymbol.GetUseSaferDeclarationBehavior(cancellationToken)) { return _variableStyle.ParameterStyle.SaferDeclarationBehavior; } return _variableStyle.ParameterStyle.DeclarationBehavior; } public ReturnBehavior ReturnBehavior { get { if (_useAsReturnValue) { return _variableStyle.ReturnStyle.ReturnBehavior; } return ReturnBehavior.None; } } public static VariableInfo CreateReturnValue(VariableInfo variable) { Contract.ThrowIfNull(variable); Contract.ThrowIfFalse(variable.CanBeUsedAsReturnValue); Contract.ThrowIfFalse(variable.ParameterModifier is ParameterBehavior.Out or ParameterBehavior.Ref); return new VariableInfo(variable._variableSymbol, variable._variableStyle, useAsReturnValue: true); } public void AddIdentifierTokenAnnotationPair( List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken) { _variableSymbol.AddIdentifierTokenAnnotationPair(annotations, cancellationToken); } public string Name => _variableSymbol.Name; /// <summary> /// Returns true, if the variable could be either passed as a parameter /// to the new local function or the local function can capture the variable. /// </summary> public bool CanBeCapturedByLocalFunction => _variableSymbol.CanBeCapturedByLocalFunction; public bool OriginalTypeHadAnonymousTypeOrDelegate => _variableSymbol.OriginalTypeHadAnonymousTypeOrDelegate; public ITypeSymbol OriginalType => _variableSymbol.OriginalType; public ITypeSymbol GetVariableType(SemanticDocument document) => document.SemanticModel.ResolveType(_variableSymbol.OriginalType); public SyntaxToken GetIdentifierTokenAtDeclaration(SemanticDocument document) => document.GetTokenWithAnnotation(_variableSymbol.IdentifierTokenAnnotation); public SyntaxToken GetIdentifierTokenAtDeclaration(SyntaxNode node) => node.GetAnnotatedTokens(_variableSymbol.IdentifierTokenAnnotation).SingleOrDefault(); public static void SortVariables(Compilation compilation, ArrayBuilder<VariableInfo> variables) { var cancellationTokenType = compilation.GetTypeByMetadataName(typeof(CancellationToken).FullName); variables.Sort((v1, v2) => Compare(v1, v2, cancellationTokenType)); } private static int Compare(VariableInfo left, VariableInfo right, INamedTypeSymbol cancellationTokenType) => VariableSymbol.Compare(left._variableSymbol, right._variableSymbol, cancellationTokenType); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract partial class MethodExtractor { protected class VariableInfo { private readonly VariableSymbol _variableSymbol; private readonly VariableStyle _variableStyle; private readonly bool _useAsReturnValue; public VariableInfo( VariableSymbol variableSymbol, VariableStyle variableStyle, bool useAsReturnValue = false) { _variableSymbol = variableSymbol; _variableStyle = variableStyle; _useAsReturnValue = useAsReturnValue; } public bool UseAsReturnValue { get { Contract.ThrowIfFalse(!_useAsReturnValue || _variableStyle.ReturnStyle.ReturnBehavior != ReturnBehavior.None); return _useAsReturnValue; } } public bool CanBeUsedAsReturnValue { get { return _variableStyle.ReturnStyle.ReturnBehavior != ReturnBehavior.None; } } public bool UseAsParameter { get { return (!_useAsReturnValue && _variableStyle.ParameterStyle.ParameterBehavior != ParameterBehavior.None) || (_useAsReturnValue && _variableStyle.ReturnStyle.ParameterBehavior != ParameterBehavior.None); } } public ParameterBehavior ParameterModifier { get { return _useAsReturnValue ? _variableStyle.ReturnStyle.ParameterBehavior : _variableStyle.ParameterStyle.ParameterBehavior; } } public DeclarationBehavior GetDeclarationBehavior(CancellationToken cancellationToken) { if (_useAsReturnValue) { return _variableStyle.ReturnStyle.DeclarationBehavior; } if (_variableSymbol.GetUseSaferDeclarationBehavior(cancellationToken)) { return _variableStyle.ParameterStyle.SaferDeclarationBehavior; } return _variableStyle.ParameterStyle.DeclarationBehavior; } public ReturnBehavior ReturnBehavior { get { if (_useAsReturnValue) { return _variableStyle.ReturnStyle.ReturnBehavior; } return ReturnBehavior.None; } } public static VariableInfo CreateReturnValue(VariableInfo variable) { Contract.ThrowIfNull(variable); Contract.ThrowIfFalse(variable.CanBeUsedAsReturnValue); Contract.ThrowIfFalse(variable.ParameterModifier is ParameterBehavior.Out or ParameterBehavior.Ref); return new VariableInfo(variable._variableSymbol, variable._variableStyle, useAsReturnValue: true); } public void AddIdentifierTokenAnnotationPair( List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken) { _variableSymbol.AddIdentifierTokenAnnotationPair(annotations, cancellationToken); } public string Name => _variableSymbol.Name; /// <summary> /// Returns true, if the variable could be either passed as a parameter /// to the new local function or the local function can capture the variable. /// </summary> public bool CanBeCapturedByLocalFunction => _variableSymbol.CanBeCapturedByLocalFunction; public bool OriginalTypeHadAnonymousTypeOrDelegate => _variableSymbol.OriginalTypeHadAnonymousTypeOrDelegate; public ITypeSymbol OriginalType => _variableSymbol.OriginalType; public ITypeSymbol GetVariableType(SemanticDocument document) => document.SemanticModel.ResolveType(_variableSymbol.OriginalType); public SyntaxToken GetIdentifierTokenAtDeclaration(SemanticDocument document) => document.GetTokenWithAnnotation(_variableSymbol.IdentifierTokenAnnotation); public SyntaxToken GetIdentifierTokenAtDeclaration(SyntaxNode node) => node.GetAnnotatedTokens(_variableSymbol.IdentifierTokenAnnotation).SingleOrDefault(); public static void SortVariables(Compilation compilation, ArrayBuilder<VariableInfo> variables) { var cancellationTokenType = compilation.GetTypeByMetadataName(typeof(CancellationToken).FullName); variables.Sort((v1, v2) => Compare(v1, v2, cancellationTokenType)); } private static int Compare(VariableInfo left, VariableInfo right, INamedTypeSymbol cancellationTokenType) => VariableSymbol.Compare(left._variableSymbol, right._variableSymbol, cancellationTokenType); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Compilers/CSharp/Portable/Emitter/Model/SourceAssemblySymbolAdapter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.CSharp.Emit; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal partial class SourceAssemblySymbol { internal IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder, bool emittingRefAssembly, bool emittingAssemblyAttributesInNetModule) { CheckDefinitionInvariant(); ImmutableArray<CSharpAttributeData> userDefined = this.GetAttributes(); ArrayBuilder<SynthesizedAttributeData> synthesized = null; this.AddSynthesizedAttributes(moduleBuilder, ref synthesized); if (emittingRefAssembly && !HasReferenceAssemblyAttribute) { var referenceAssemblyAttribute = this.DeclaringCompilation .TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_ReferenceAssemblyAttribute__ctor, isOptionalUse: true); Symbol.AddSynthesizedAttribute(ref synthesized, referenceAssemblyAttribute); } // Note that callers of this method (CCI and ReflectionEmitter) have to enumerate // all items of the returned iterator, otherwise the synthesized ArrayBuilder may leak. return GetCustomAttributesToEmit(userDefined, synthesized, isReturnType: false, emittingAssemblyAttributesInNetModule: emittingAssemblyAttributesInNetModule); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.CSharp.Emit; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal partial class SourceAssemblySymbol { internal IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder, bool emittingRefAssembly, bool emittingAssemblyAttributesInNetModule) { CheckDefinitionInvariant(); ImmutableArray<CSharpAttributeData> userDefined = this.GetAttributes(); ArrayBuilder<SynthesizedAttributeData> synthesized = null; this.AddSynthesizedAttributes(moduleBuilder, ref synthesized); if (emittingRefAssembly && !HasReferenceAssemblyAttribute) { var referenceAssemblyAttribute = this.DeclaringCompilation .TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_ReferenceAssemblyAttribute__ctor, isOptionalUse: true); Symbol.AddSynthesizedAttribute(ref synthesized, referenceAssemblyAttribute); } // Note that callers of this method (CCI and ReflectionEmitter) have to enumerate // all items of the returned iterator, otherwise the synthesized ArrayBuilder may leak. return GetCustomAttributesToEmit(userDefined, synthesized, isReturnType: false, emittingAssemblyAttributesInNetModule: emittingAssemblyAttributesInNetModule); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/ExpressionEvaluator/CSharp/Test/ResultProvider/FullNameTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class FullNameTests : CSharpResultProviderTestBase { [Fact] public void Null() { IDkmClrFullNameProvider fullNameProvider = new CSharpFormatter(); var inspectionContext = CreateDkmInspectionContext(); Assert.Equal("null", fullNameProvider.GetClrExpressionForNull(inspectionContext)); } [Fact] public void This() { IDkmClrFullNameProvider fullNameProvider = new CSharpFormatter(); var inspectionContext = CreateDkmInspectionContext(); Assert.Equal("this", fullNameProvider.GetClrExpressionForThis(inspectionContext)); } [Fact] public void ArrayIndex() { IDkmClrFullNameProvider fullNameProvider = new CSharpFormatter(); var inspectionContext = CreateDkmInspectionContext(); Assert.Equal("[]", fullNameProvider.GetClrArrayIndexExpression(inspectionContext, new string[0])); Assert.Equal("[]", fullNameProvider.GetClrArrayIndexExpression(inspectionContext, new[] { "" })); Assert.Equal("[ ]", fullNameProvider.GetClrArrayIndexExpression(inspectionContext, new[] { " " })); Assert.Equal("[1]", fullNameProvider.GetClrArrayIndexExpression(inspectionContext, new[] { "1" })); Assert.Equal("[[], 2, 3]", fullNameProvider.GetClrArrayIndexExpression(inspectionContext, new[] { "[]", "2", "3" })); Assert.Equal("[, , ]", fullNameProvider.GetClrArrayIndexExpression(inspectionContext, new[] { "", "", "" })); } [Fact] public void Cast() { var source = @"class C { }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source))); using (runtime.Load()) { IDkmClrFullNameProvider fullNameProvider = new CSharpFormatter(); var inspectionContext = CreateDkmInspectionContext(); var type = runtime.GetType("C"); Assert.Equal("(C)o", fullNameProvider.GetClrCastExpression(inspectionContext, "o", type, null, DkmClrCastExpressionOptions.None)); Assert.Equal("o as C", fullNameProvider.GetClrCastExpression(inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ConditionalCast)); Assert.Equal("(C)(o)", fullNameProvider.GetClrCastExpression(inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ParenthesizeArgument)); Assert.Equal("(o) as C", fullNameProvider.GetClrCastExpression(inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ParenthesizeArgument | DkmClrCastExpressionOptions.ConditionalCast)); Assert.Equal("((C)o)", fullNameProvider.GetClrCastExpression(inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ParenthesizeEntireExpression)); Assert.Equal("(o as C)", fullNameProvider.GetClrCastExpression(inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ParenthesizeEntireExpression | DkmClrCastExpressionOptions.ConditionalCast)); Assert.Equal("((C)(o))", fullNameProvider.GetClrCastExpression(inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ParenthesizeEntireExpression | DkmClrCastExpressionOptions.ParenthesizeArgument)); Assert.Equal("((o) as C)", fullNameProvider.GetClrCastExpression(inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ParenthesizeEntireExpression | DkmClrCastExpressionOptions.ParenthesizeArgument | DkmClrCastExpressionOptions.ConditionalCast)); // Some of the same tests with "..." as the expression ("..." is used // by the debugger when the expression cannot be determined). Assert.Equal("(C)...", fullNameProvider.GetClrCastExpression(inspectionContext, "...", type, null, DkmClrCastExpressionOptions.None)); Assert.Equal("... as C", fullNameProvider.GetClrCastExpression(inspectionContext, "...", type, null, DkmClrCastExpressionOptions.ConditionalCast)); Assert.Equal("(... as C)", fullNameProvider.GetClrCastExpression(inspectionContext, "...", type, null, DkmClrCastExpressionOptions.ParenthesizeEntireExpression | DkmClrCastExpressionOptions.ConditionalCast)); } } [Fact] public void RootComment() { var source = @" class C { public int F; } "; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate()); var root = FormatResult("a // Comment", value); Assert.Equal("a.F", GetChildren(root).Single().FullName); root = FormatResult(" a // Comment", value); Assert.Equal("a.F", GetChildren(root).Single().FullName); root = FormatResult("a// Comment", value); Assert.Equal("a.F", GetChildren(root).Single().FullName); root = FormatResult("a /*b*/ +c /*d*/// Comment", value); Assert.Equal("(a +c).F", GetChildren(root).Single().FullName); root = FormatResult("a /*//*/+ c// Comment", value); Assert.Equal("(a + c).F", GetChildren(root).Single().FullName); root = FormatResult("a /*/**/+ c// Comment", value); Assert.Equal("(a + c).F", GetChildren(root).Single().FullName); root = FormatResult("/**/a// Comment", value); Assert.Equal("a.F", GetChildren(root).Single().FullName); // See https://dev.azure.com/devdiv/DevDiv/_workitems/edit/847849 root = FormatResult(@"""a//b/*"" // c", value); Assert.Equal(@"(""a//b/*"").F", GetChildren(root).Single().FullName); // incorrect - see https://github.com/dotnet/roslyn/issues/37536 root = FormatResult(@"""a"" //""b", value); Assert.Equal(@"(""a"" //""b).F", GetChildren(root).Single().FullName); } [Fact] public void RootFormatSpecifiers() { var source = @" class C { public int F; } "; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate()); var root = FormatResult("a, raw", value); // simple Assert.Equal("a, raw", root.FullName); Assert.Equal("a.F", GetChildren(root).Single().FullName); root = FormatResult("a, raw, ac, h", value); // multiple specifiers Assert.Equal("a, raw, ac, h", root.FullName); Assert.Equal("a.F", GetChildren(root).Single().FullName); root = FormatResult("M(a, b), raw", value); // non-specifier comma Assert.Equal("M(a, b), raw", root.FullName); Assert.Equal("M(a, b).F", GetChildren(root).Single().FullName); root = FormatResult("a, raw1", value); // alpha-numeric Assert.Equal("a, raw1", root.FullName); Assert.Equal("a.F", GetChildren(root).Single().FullName); root = FormatResult("a, $raw", value); // other punctuation Assert.Equal("a, $raw", root.FullName); Assert.Equal("(a, $raw).F", GetChildren(root).Single().FullName); // not ideal } [Fact] public void RootParentheses() { var source = @" class C { public int F; } "; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate()); var root = FormatResult("a + b", value); Assert.Equal("(a + b).F", GetChildren(root).Single().FullName); // required root = FormatResult("new C()", value); Assert.Equal("(new C()).F", GetChildren(root).Single().FullName); // documentation root = FormatResult("A.B", value); Assert.Equal("A.B.F", GetChildren(root).Single().FullName); // desirable root = FormatResult("A::B", value); Assert.Equal("(A::B).F", GetChildren(root).Single().FullName); // documentation } [Fact] public void RootTrailingSemicolons() { var source = @" class C { public int F; } "; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate()); var root = FormatResult("a;", value); Assert.Equal("a.F", GetChildren(root).Single().FullName); root = FormatResult("a + b;;", value); Assert.Equal("(a + b).F", GetChildren(root).Single().FullName); root = FormatResult(" M( ) ; ;", value); Assert.Equal("M( ).F", GetChildren(root).Single().FullName); } [Fact] public void RootMixedExtras() { var source = @" class C { public int F; } "; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate()); // Semicolon, then comment. var root = FormatResult("a; //", value); Assert.Equal("a", root.FullName); // Comment, then semicolon. root = FormatResult("a // ;", value); Assert.Equal("a", root.FullName); // Semicolon, then format specifier. root = FormatResult("a;, ac", value); Assert.Equal("a, ac", root.FullName); // Format specifier, then semicolon. root = FormatResult("a, ac;", value); Assert.Equal("a, ac", root.FullName); // Comment, then format specifier. root = FormatResult("a//, ac", value); Assert.Equal("a", root.FullName); // Format specifier, then comment. root = FormatResult("a, ac //", value); Assert.Equal("a, ac", root.FullName); // Everything. root = FormatResult("/*A*/ a /*B*/ + /*C*/ b /*D*/ ; ; , ac /*E*/, raw // ;, hidden", value); Assert.Equal("a + b, ac, raw", root.FullName); } [Fact, WorkItem(1022165, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1022165")] public void Keywords_Root() { var source = @" class C { void M() { int @namespace = 3; } } "; var assembly = GetAssembly(source); var value = CreateDkmClrValue(3); var root = FormatResult("@namespace", value); Verify(root, EvalResult("@namespace", "3", "int", "@namespace")); value = CreateDkmClrValue(assembly.GetType("C").Instantiate()); root = FormatResult("this", value); Verify(root, EvalResult("this", "{C}", "C", "this")); // Verify that keywords aren't escaped by the ResultProvider at the // root level (we would never expect to see "namespace" passed as a // resultName, but this check verifies that we leave them "as is"). root = FormatResult("namespace", CreateDkmClrValue(new object())); Verify(root, EvalResult("namespace", "{object}", "object", "namespace")); } [Fact] public void Keywords_RuntimeType() { var source = @" public class @struct { } public class @namespace : @struct { @struct m = new @if(); } public class @if : @struct { } "; var assembly = GetAssembly(source); var type = assembly.GetType("namespace"); var declaredType = assembly.GetType("struct"); var value = CreateDkmClrValue(type.Instantiate(), type); var root = FormatResult("o", value, new DkmClrType((TypeImpl)declaredType)); Verify(GetChildren(root), EvalResult("m", "{if}", "struct {if}", "((@namespace)o).m", DkmEvaluationResultFlags.CanFavorite)); } [Fact] public void Keywords_ProxyType() { var source = @" using System.Diagnostics; [DebuggerTypeProxy(typeof(@class))] public class @struct { public bool @true = false; } public class @class { public bool @false = true; public @class(@struct s) { } } "; var assembly = GetAssembly(source); var value = CreateDkmClrValue(assembly.GetType("struct").Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("@false", "true", "bool", "new @class(o).@false", DkmEvaluationResultFlags.Boolean | DkmEvaluationResultFlags.BooleanTrue), EvalResult("Raw View", null, "", "o, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); var grandChildren = GetChildren(children.Last()); Verify(grandChildren, EvalResult("@true", "false", "bool", "o.@true", DkmEvaluationResultFlags.Boolean)); } [Fact] public void Keywords_MemberAccess() { var source = @" public class @struct { public int @true; } "; var assembly = GetAssembly(source); var value = CreateDkmClrValue(assembly.GetType("struct").Instantiate()); var root = FormatResult("o", value); Verify(GetChildren(root), EvalResult("@true", "0", "int", "o.@true", DkmEvaluationResultFlags.CanFavorite)); } [Fact] public void Keywords_StaticMembers() { var source = @" public class @struct { public static int @true; } "; var assembly = GetAssembly(source); var value = CreateDkmClrValue(assembly.GetType("struct").Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", "@struct", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("@true", "0", "int", "@struct.@true", DkmEvaluationResultFlags.None, DkmEvaluationResultCategory.Data, DkmEvaluationResultAccessType.Public)); } [Fact] public void Keywords_ExplicitInterfaceImplementation() { var source = @" namespace @namespace { public interface @interface<T> { int @return { get; set; } } public class @class : @interface<@class> { int @interface<@class>.@return { get; set; } } } "; var assembly = GetAssembly(source); var value = CreateDkmClrValue(assembly.GetType("namespace.class").Instantiate()); var root = FormatResult("instance", value); Verify(GetChildren(root), EvalResult("@namespace.@interface<@namespace.@class>.@return", "0", "int", "((@namespace.@interface<@namespace.@class>)instance).@return")); } [Fact] public void MangledNames_CastRequired() { var il = @" .class public auto ansi beforefieldinit '<>Mangled' extends [mscorlib]System.Object { .field public int32 x .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public auto ansi beforefieldinit 'NotMangled' extends '<>Mangled' { .field public int32 x .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void '<>Mangled'::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("NotMangled").Instantiate()); var root = FormatResult("o", value); Verify(GetChildren(root), EvalResult("x (<>Mangled)", "0", "int", null), EvalResult("x", "0", "int", "o.x", DkmEvaluationResultFlags.CanFavorite)); } [Fact] public void MangledNames_StaticMembers() { var il = @" .class public auto ansi beforefieldinit '<>Mangled' extends [mscorlib]System.Object { .field public static int32 x .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public auto ansi beforefieldinit 'NotMangled' extends '<>Mangled' { .field public static int32 y .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void '<>Mangled'::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var baseValue = CreateDkmClrValue(assembly.GetType("<>Mangled").Instantiate()); var root = FormatResult("o", baseValue); var children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("x", "0", "int", null)); var derivedValue = CreateDkmClrValue(assembly.GetType("NotMangled").Instantiate()); root = FormatResult("o", derivedValue); children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", "NotMangled", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("x", "0", "int", null, DkmEvaluationResultFlags.None, DkmEvaluationResultCategory.Data, DkmEvaluationResultAccessType.Public), EvalResult("y", "0", "int", "NotMangled.y", DkmEvaluationResultFlags.None, DkmEvaluationResultCategory.Data, DkmEvaluationResultAccessType.Public)); } [Fact] public void MangledNames_ExplicitInterfaceImplementation() { var il = @" .class interface public abstract auto ansi 'abstract.I<>Mangled' { .method public hidebysig newslot specialname abstract virtual instance int32 get_P() cil managed { } .property instance int32 P() { .get instance int32 'abstract.I<>Mangled'::get_P() } } // end of class 'abstract.I<>Mangled' .class public auto ansi beforefieldinit C extends [mscorlib]System.Object implements 'abstract.I<>Mangled' { .method private hidebysig newslot specialname virtual final instance int32 'abstract.I<>Mangled.get_P'() cil managed { .override 'abstract.I<>Mangled'::get_P ldc.i4.1 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 'abstract.I<>Mangled.P'() { .get instance int32 C::'abstract.I<>Mangled.get_P'() } .property instance int32 P() { .get instance int32 C::'abstract.I<>Mangled.get_P'() } } // end of class C "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("C").Instantiate()); var root = FormatResult("instance", value); Verify(GetChildren(root), EvalResult("P", "1", "int", "instance.P", DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Private), EvalResult("abstract.I<>Mangled.P", "1", "int", null, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Private)); } [Fact] public void MangledNames_ArrayElement() { var il = @" .class public auto ansi beforefieldinit '<>Mangled' extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public auto ansi beforefieldinit NotMangled extends [mscorlib]System.Object { .field public class [mscorlib]System.Collections.Generic.IEnumerable`1<class '<>Mangled'> 'array' .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 ldc.i4.1 newarr '<>Mangled' stfld class [mscorlib]System.Collections.Generic.IEnumerable`1<class '<>Mangled'> NotMangled::'array' ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("NotMangled").Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("array", "{<>Mangled[1]}", "System.Collections.Generic.IEnumerable<<>Mangled> {<>Mangled[]}", "o.array", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite)); Verify(GetChildren(children.Single()), EvalResult("[0]", "null", "<>Mangled", null)); } [Fact] public void MangledNames_Namespace() { var il = @" .class public auto ansi beforefieldinit '<>Mangled.C' extends [mscorlib]System.Object { .field public static int32 x .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var baseValue = CreateDkmClrValue(assembly.GetType("<>Mangled.C").Instantiate()); var root = FormatResult("o", baseValue); var children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("x", "0", "int", null)); } [Fact] public void MangledNames_PointerDereference() { var il = @" .class public auto ansi beforefieldinit '<>Mangled' extends [mscorlib]System.Object { .field private static int32* p .method assembly hidebysig specialname rtspecialname instance void .ctor(int64 arg) cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0008: ldarg.1 IL_0009: conv.u IL_000a: stsfld int32* '<>Mangled'::p IL_0010: ret } } // end of class '<>Mangled' "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); unsafe { int i = 4; long p = (long)&i; var type = assembly.GetType("<>Mangled"); var rootExpr = "m"; var value = CreateDkmClrValue(type.Instantiate(p)); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{<>Mangled}", "<>Mangled", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); children = GetChildren(children.Single()); Verify(children, EvalResult("p", PointerToString(new IntPtr(p)), "int*", null, DkmEvaluationResultFlags.Expandable)); children = GetChildren(children.Single()); Verify(children, EvalResult("*p", "4", "int", null)); } } [Fact] public void MangledNames_DebuggerTypeProxy() { var il = @" .class public auto ansi beforefieldinit Type extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [mscorlib]System.Type) = {type('<>Mangled')} .field public bool x .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 ldc.i4.0 stfld bool Type::x ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } // end of method Type::.ctor } // end of class Type .class public auto ansi beforefieldinit '<>Mangled' extends [mscorlib]System.Object { .field public bool y .method public hidebysig specialname rtspecialname instance void .ctor(class Type s) cil managed { ldarg.0 ldc.i4.1 stfld bool '<>Mangled'::y ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } // end of method '<>Mangled'::.ctor } // end of class '<>Mangled' "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("Type").Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("y", "true", "bool", null, DkmEvaluationResultFlags.Boolean | DkmEvaluationResultFlags.BooleanTrue), EvalResult("Raw View", null, "", "o, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); var grandChildren = GetChildren(children.Last()); Verify(grandChildren, EvalResult("x", "false", "bool", "o.x", DkmEvaluationResultFlags.Boolean)); } [Fact] public void GenericTypeWithoutBacktick() { var il = @" .class public auto ansi beforefieldinit C<T> extends [mscorlib]System.Object { .field public static int32 'x' .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("C").MakeGenericType(typeof(int)).Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", "C<int>", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("x", "0", "int", "C<int>.x")); } [Fact] public void BackTick_NonGenericType() { var il = @" .class public auto ansi beforefieldinit 'C`1' extends [mscorlib]System.Object { .field public static int32 'x' .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("C`1").Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("x", "0", "int", null)); } [Fact] public void BackTick_GenericType() { var il = @" .class public auto ansi beforefieldinit 'C`1'<T> extends [mscorlib]System.Object { .field public static int32 'x' .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("C`1").MakeGenericType(typeof(int)).Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", "C<int>", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("x", "0", "int", "C<int>.x")); } [Fact] public void BackTick_Member() { // IL doesn't support using generic methods as property accessors so // there's no way to test a "legitimate" backtick in a member name. var il = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .field public static int32 'x`1' .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("C").Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", "C", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("x`1", "0", "int", fullName: null)); } [Fact] public void BackTick_FirstCharacter() { var il = @" .class public auto ansi beforefieldinit '`1'<T> extends [mscorlib]System.Object { .field public static int32 'x' .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("`1").MakeGenericType(typeof(int)).Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("x", "0", "int", fullName: null)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class FullNameTests : CSharpResultProviderTestBase { [Fact] public void Null() { IDkmClrFullNameProvider fullNameProvider = new CSharpFormatter(); var inspectionContext = CreateDkmInspectionContext(); Assert.Equal("null", fullNameProvider.GetClrExpressionForNull(inspectionContext)); } [Fact] public void This() { IDkmClrFullNameProvider fullNameProvider = new CSharpFormatter(); var inspectionContext = CreateDkmInspectionContext(); Assert.Equal("this", fullNameProvider.GetClrExpressionForThis(inspectionContext)); } [Fact] public void ArrayIndex() { IDkmClrFullNameProvider fullNameProvider = new CSharpFormatter(); var inspectionContext = CreateDkmInspectionContext(); Assert.Equal("[]", fullNameProvider.GetClrArrayIndexExpression(inspectionContext, new string[0])); Assert.Equal("[]", fullNameProvider.GetClrArrayIndexExpression(inspectionContext, new[] { "" })); Assert.Equal("[ ]", fullNameProvider.GetClrArrayIndexExpression(inspectionContext, new[] { " " })); Assert.Equal("[1]", fullNameProvider.GetClrArrayIndexExpression(inspectionContext, new[] { "1" })); Assert.Equal("[[], 2, 3]", fullNameProvider.GetClrArrayIndexExpression(inspectionContext, new[] { "[]", "2", "3" })); Assert.Equal("[, , ]", fullNameProvider.GetClrArrayIndexExpression(inspectionContext, new[] { "", "", "" })); } [Fact] public void Cast() { var source = @"class C { }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source))); using (runtime.Load()) { IDkmClrFullNameProvider fullNameProvider = new CSharpFormatter(); var inspectionContext = CreateDkmInspectionContext(); var type = runtime.GetType("C"); Assert.Equal("(C)o", fullNameProvider.GetClrCastExpression(inspectionContext, "o", type, null, DkmClrCastExpressionOptions.None)); Assert.Equal("o as C", fullNameProvider.GetClrCastExpression(inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ConditionalCast)); Assert.Equal("(C)(o)", fullNameProvider.GetClrCastExpression(inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ParenthesizeArgument)); Assert.Equal("(o) as C", fullNameProvider.GetClrCastExpression(inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ParenthesizeArgument | DkmClrCastExpressionOptions.ConditionalCast)); Assert.Equal("((C)o)", fullNameProvider.GetClrCastExpression(inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ParenthesizeEntireExpression)); Assert.Equal("(o as C)", fullNameProvider.GetClrCastExpression(inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ParenthesizeEntireExpression | DkmClrCastExpressionOptions.ConditionalCast)); Assert.Equal("((C)(o))", fullNameProvider.GetClrCastExpression(inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ParenthesizeEntireExpression | DkmClrCastExpressionOptions.ParenthesizeArgument)); Assert.Equal("((o) as C)", fullNameProvider.GetClrCastExpression(inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ParenthesizeEntireExpression | DkmClrCastExpressionOptions.ParenthesizeArgument | DkmClrCastExpressionOptions.ConditionalCast)); // Some of the same tests with "..." as the expression ("..." is used // by the debugger when the expression cannot be determined). Assert.Equal("(C)...", fullNameProvider.GetClrCastExpression(inspectionContext, "...", type, null, DkmClrCastExpressionOptions.None)); Assert.Equal("... as C", fullNameProvider.GetClrCastExpression(inspectionContext, "...", type, null, DkmClrCastExpressionOptions.ConditionalCast)); Assert.Equal("(... as C)", fullNameProvider.GetClrCastExpression(inspectionContext, "...", type, null, DkmClrCastExpressionOptions.ParenthesizeEntireExpression | DkmClrCastExpressionOptions.ConditionalCast)); } } [Fact] public void RootComment() { var source = @" class C { public int F; } "; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate()); var root = FormatResult("a // Comment", value); Assert.Equal("a.F", GetChildren(root).Single().FullName); root = FormatResult(" a // Comment", value); Assert.Equal("a.F", GetChildren(root).Single().FullName); root = FormatResult("a// Comment", value); Assert.Equal("a.F", GetChildren(root).Single().FullName); root = FormatResult("a /*b*/ +c /*d*/// Comment", value); Assert.Equal("(a +c).F", GetChildren(root).Single().FullName); root = FormatResult("a /*//*/+ c// Comment", value); Assert.Equal("(a + c).F", GetChildren(root).Single().FullName); root = FormatResult("a /*/**/+ c// Comment", value); Assert.Equal("(a + c).F", GetChildren(root).Single().FullName); root = FormatResult("/**/a// Comment", value); Assert.Equal("a.F", GetChildren(root).Single().FullName); // See https://dev.azure.com/devdiv/DevDiv/_workitems/edit/847849 root = FormatResult(@"""a//b/*"" // c", value); Assert.Equal(@"(""a//b/*"").F", GetChildren(root).Single().FullName); // incorrect - see https://github.com/dotnet/roslyn/issues/37536 root = FormatResult(@"""a"" //""b", value); Assert.Equal(@"(""a"" //""b).F", GetChildren(root).Single().FullName); } [Fact] public void RootFormatSpecifiers() { var source = @" class C { public int F; } "; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate()); var root = FormatResult("a, raw", value); // simple Assert.Equal("a, raw", root.FullName); Assert.Equal("a.F", GetChildren(root).Single().FullName); root = FormatResult("a, raw, ac, h", value); // multiple specifiers Assert.Equal("a, raw, ac, h", root.FullName); Assert.Equal("a.F", GetChildren(root).Single().FullName); root = FormatResult("M(a, b), raw", value); // non-specifier comma Assert.Equal("M(a, b), raw", root.FullName); Assert.Equal("M(a, b).F", GetChildren(root).Single().FullName); root = FormatResult("a, raw1", value); // alpha-numeric Assert.Equal("a, raw1", root.FullName); Assert.Equal("a.F", GetChildren(root).Single().FullName); root = FormatResult("a, $raw", value); // other punctuation Assert.Equal("a, $raw", root.FullName); Assert.Equal("(a, $raw).F", GetChildren(root).Single().FullName); // not ideal } [Fact] public void RootParentheses() { var source = @" class C { public int F; } "; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate()); var root = FormatResult("a + b", value); Assert.Equal("(a + b).F", GetChildren(root).Single().FullName); // required root = FormatResult("new C()", value); Assert.Equal("(new C()).F", GetChildren(root).Single().FullName); // documentation root = FormatResult("A.B", value); Assert.Equal("A.B.F", GetChildren(root).Single().FullName); // desirable root = FormatResult("A::B", value); Assert.Equal("(A::B).F", GetChildren(root).Single().FullName); // documentation } [Fact] public void RootTrailingSemicolons() { var source = @" class C { public int F; } "; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate()); var root = FormatResult("a;", value); Assert.Equal("a.F", GetChildren(root).Single().FullName); root = FormatResult("a + b;;", value); Assert.Equal("(a + b).F", GetChildren(root).Single().FullName); root = FormatResult(" M( ) ; ;", value); Assert.Equal("M( ).F", GetChildren(root).Single().FullName); } [Fact] public void RootMixedExtras() { var source = @" class C { public int F; } "; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate()); // Semicolon, then comment. var root = FormatResult("a; //", value); Assert.Equal("a", root.FullName); // Comment, then semicolon. root = FormatResult("a // ;", value); Assert.Equal("a", root.FullName); // Semicolon, then format specifier. root = FormatResult("a;, ac", value); Assert.Equal("a, ac", root.FullName); // Format specifier, then semicolon. root = FormatResult("a, ac;", value); Assert.Equal("a, ac", root.FullName); // Comment, then format specifier. root = FormatResult("a//, ac", value); Assert.Equal("a", root.FullName); // Format specifier, then comment. root = FormatResult("a, ac //", value); Assert.Equal("a, ac", root.FullName); // Everything. root = FormatResult("/*A*/ a /*B*/ + /*C*/ b /*D*/ ; ; , ac /*E*/, raw // ;, hidden", value); Assert.Equal("a + b, ac, raw", root.FullName); } [Fact, WorkItem(1022165, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1022165")] public void Keywords_Root() { var source = @" class C { void M() { int @namespace = 3; } } "; var assembly = GetAssembly(source); var value = CreateDkmClrValue(3); var root = FormatResult("@namespace", value); Verify(root, EvalResult("@namespace", "3", "int", "@namespace")); value = CreateDkmClrValue(assembly.GetType("C").Instantiate()); root = FormatResult("this", value); Verify(root, EvalResult("this", "{C}", "C", "this")); // Verify that keywords aren't escaped by the ResultProvider at the // root level (we would never expect to see "namespace" passed as a // resultName, but this check verifies that we leave them "as is"). root = FormatResult("namespace", CreateDkmClrValue(new object())); Verify(root, EvalResult("namespace", "{object}", "object", "namespace")); } [Fact] public void Keywords_RuntimeType() { var source = @" public class @struct { } public class @namespace : @struct { @struct m = new @if(); } public class @if : @struct { } "; var assembly = GetAssembly(source); var type = assembly.GetType("namespace"); var declaredType = assembly.GetType("struct"); var value = CreateDkmClrValue(type.Instantiate(), type); var root = FormatResult("o", value, new DkmClrType((TypeImpl)declaredType)); Verify(GetChildren(root), EvalResult("m", "{if}", "struct {if}", "((@namespace)o).m", DkmEvaluationResultFlags.CanFavorite)); } [Fact] public void Keywords_ProxyType() { var source = @" using System.Diagnostics; [DebuggerTypeProxy(typeof(@class))] public class @struct { public bool @true = false; } public class @class { public bool @false = true; public @class(@struct s) { } } "; var assembly = GetAssembly(source); var value = CreateDkmClrValue(assembly.GetType("struct").Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("@false", "true", "bool", "new @class(o).@false", DkmEvaluationResultFlags.Boolean | DkmEvaluationResultFlags.BooleanTrue), EvalResult("Raw View", null, "", "o, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); var grandChildren = GetChildren(children.Last()); Verify(grandChildren, EvalResult("@true", "false", "bool", "o.@true", DkmEvaluationResultFlags.Boolean)); } [Fact] public void Keywords_MemberAccess() { var source = @" public class @struct { public int @true; } "; var assembly = GetAssembly(source); var value = CreateDkmClrValue(assembly.GetType("struct").Instantiate()); var root = FormatResult("o", value); Verify(GetChildren(root), EvalResult("@true", "0", "int", "o.@true", DkmEvaluationResultFlags.CanFavorite)); } [Fact] public void Keywords_StaticMembers() { var source = @" public class @struct { public static int @true; } "; var assembly = GetAssembly(source); var value = CreateDkmClrValue(assembly.GetType("struct").Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", "@struct", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("@true", "0", "int", "@struct.@true", DkmEvaluationResultFlags.None, DkmEvaluationResultCategory.Data, DkmEvaluationResultAccessType.Public)); } [Fact] public void Keywords_ExplicitInterfaceImplementation() { var source = @" namespace @namespace { public interface @interface<T> { int @return { get; set; } } public class @class : @interface<@class> { int @interface<@class>.@return { get; set; } } } "; var assembly = GetAssembly(source); var value = CreateDkmClrValue(assembly.GetType("namespace.class").Instantiate()); var root = FormatResult("instance", value); Verify(GetChildren(root), EvalResult("@namespace.@interface<@namespace.@class>.@return", "0", "int", "((@namespace.@interface<@namespace.@class>)instance).@return")); } [Fact] public void MangledNames_CastRequired() { var il = @" .class public auto ansi beforefieldinit '<>Mangled' extends [mscorlib]System.Object { .field public int32 x .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public auto ansi beforefieldinit 'NotMangled' extends '<>Mangled' { .field public int32 x .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void '<>Mangled'::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("NotMangled").Instantiate()); var root = FormatResult("o", value); Verify(GetChildren(root), EvalResult("x (<>Mangled)", "0", "int", null), EvalResult("x", "0", "int", "o.x", DkmEvaluationResultFlags.CanFavorite)); } [Fact] public void MangledNames_StaticMembers() { var il = @" .class public auto ansi beforefieldinit '<>Mangled' extends [mscorlib]System.Object { .field public static int32 x .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public auto ansi beforefieldinit 'NotMangled' extends '<>Mangled' { .field public static int32 y .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void '<>Mangled'::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var baseValue = CreateDkmClrValue(assembly.GetType("<>Mangled").Instantiate()); var root = FormatResult("o", baseValue); var children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("x", "0", "int", null)); var derivedValue = CreateDkmClrValue(assembly.GetType("NotMangled").Instantiate()); root = FormatResult("o", derivedValue); children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", "NotMangled", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("x", "0", "int", null, DkmEvaluationResultFlags.None, DkmEvaluationResultCategory.Data, DkmEvaluationResultAccessType.Public), EvalResult("y", "0", "int", "NotMangled.y", DkmEvaluationResultFlags.None, DkmEvaluationResultCategory.Data, DkmEvaluationResultAccessType.Public)); } [Fact] public void MangledNames_ExplicitInterfaceImplementation() { var il = @" .class interface public abstract auto ansi 'abstract.I<>Mangled' { .method public hidebysig newslot specialname abstract virtual instance int32 get_P() cil managed { } .property instance int32 P() { .get instance int32 'abstract.I<>Mangled'::get_P() } } // end of class 'abstract.I<>Mangled' .class public auto ansi beforefieldinit C extends [mscorlib]System.Object implements 'abstract.I<>Mangled' { .method private hidebysig newslot specialname virtual final instance int32 'abstract.I<>Mangled.get_P'() cil managed { .override 'abstract.I<>Mangled'::get_P ldc.i4.1 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 'abstract.I<>Mangled.P'() { .get instance int32 C::'abstract.I<>Mangled.get_P'() } .property instance int32 P() { .get instance int32 C::'abstract.I<>Mangled.get_P'() } } // end of class C "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("C").Instantiate()); var root = FormatResult("instance", value); Verify(GetChildren(root), EvalResult("P", "1", "int", "instance.P", DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Private), EvalResult("abstract.I<>Mangled.P", "1", "int", null, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Private)); } [Fact] public void MangledNames_ArrayElement() { var il = @" .class public auto ansi beforefieldinit '<>Mangled' extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public auto ansi beforefieldinit NotMangled extends [mscorlib]System.Object { .field public class [mscorlib]System.Collections.Generic.IEnumerable`1<class '<>Mangled'> 'array' .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 ldc.i4.1 newarr '<>Mangled' stfld class [mscorlib]System.Collections.Generic.IEnumerable`1<class '<>Mangled'> NotMangled::'array' ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("NotMangled").Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("array", "{<>Mangled[1]}", "System.Collections.Generic.IEnumerable<<>Mangled> {<>Mangled[]}", "o.array", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite)); Verify(GetChildren(children.Single()), EvalResult("[0]", "null", "<>Mangled", null)); } [Fact] public void MangledNames_Namespace() { var il = @" .class public auto ansi beforefieldinit '<>Mangled.C' extends [mscorlib]System.Object { .field public static int32 x .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var baseValue = CreateDkmClrValue(assembly.GetType("<>Mangled.C").Instantiate()); var root = FormatResult("o", baseValue); var children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("x", "0", "int", null)); } [Fact] public void MangledNames_PointerDereference() { var il = @" .class public auto ansi beforefieldinit '<>Mangled' extends [mscorlib]System.Object { .field private static int32* p .method assembly hidebysig specialname rtspecialname instance void .ctor(int64 arg) cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0008: ldarg.1 IL_0009: conv.u IL_000a: stsfld int32* '<>Mangled'::p IL_0010: ret } } // end of class '<>Mangled' "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); unsafe { int i = 4; long p = (long)&i; var type = assembly.GetType("<>Mangled"); var rootExpr = "m"; var value = CreateDkmClrValue(type.Instantiate(p)); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{<>Mangled}", "<>Mangled", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); children = GetChildren(children.Single()); Verify(children, EvalResult("p", PointerToString(new IntPtr(p)), "int*", null, DkmEvaluationResultFlags.Expandable)); children = GetChildren(children.Single()); Verify(children, EvalResult("*p", "4", "int", null)); } } [Fact] public void MangledNames_DebuggerTypeProxy() { var il = @" .class public auto ansi beforefieldinit Type extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [mscorlib]System.Type) = {type('<>Mangled')} .field public bool x .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 ldc.i4.0 stfld bool Type::x ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } // end of method Type::.ctor } // end of class Type .class public auto ansi beforefieldinit '<>Mangled' extends [mscorlib]System.Object { .field public bool y .method public hidebysig specialname rtspecialname instance void .ctor(class Type s) cil managed { ldarg.0 ldc.i4.1 stfld bool '<>Mangled'::y ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } // end of method '<>Mangled'::.ctor } // end of class '<>Mangled' "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("Type").Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("y", "true", "bool", null, DkmEvaluationResultFlags.Boolean | DkmEvaluationResultFlags.BooleanTrue), EvalResult("Raw View", null, "", "o, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); var grandChildren = GetChildren(children.Last()); Verify(grandChildren, EvalResult("x", "false", "bool", "o.x", DkmEvaluationResultFlags.Boolean)); } [Fact] public void GenericTypeWithoutBacktick() { var il = @" .class public auto ansi beforefieldinit C<T> extends [mscorlib]System.Object { .field public static int32 'x' .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("C").MakeGenericType(typeof(int)).Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", "C<int>", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("x", "0", "int", "C<int>.x")); } [Fact] public void BackTick_NonGenericType() { var il = @" .class public auto ansi beforefieldinit 'C`1' extends [mscorlib]System.Object { .field public static int32 'x' .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("C`1").Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("x", "0", "int", null)); } [Fact] public void BackTick_GenericType() { var il = @" .class public auto ansi beforefieldinit 'C`1'<T> extends [mscorlib]System.Object { .field public static int32 'x' .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("C`1").MakeGenericType(typeof(int)).Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", "C<int>", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("x", "0", "int", "C<int>.x")); } [Fact] public void BackTick_Member() { // IL doesn't support using generic methods as property accessors so // there's no way to test a "legitimate" backtick in a member name. var il = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .field public static int32 'x`1' .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("C").Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", "C", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("x`1", "0", "int", fullName: null)); } [Fact] public void BackTick_FirstCharacter() { var il = @" .class public auto ansi beforefieldinit '`1'<T> extends [mscorlib]System.Object { .field public static int32 'x' .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("`1").MakeGenericType(typeof(int)).Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("x", "0", "int", fullName: null)); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Analyzers/VisualBasic/Tests/VisualBasicAnalyzers.UnitTests.shproj
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup Label="Globals"> <ProjectGuid>{7B7F4153-AE93-4908-B8F0-430871589F83}</ProjectGuid> <MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion> </PropertyGroup> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" /> <PropertyGroup /> <Import Project="VisualBasicAnalyzers.UnitTests.projitems" Label="Shared" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.VisualBasic.targets" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup Label="Globals"> <ProjectGuid>{7B7F4153-AE93-4908-B8F0-430871589F83}</ProjectGuid> <MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion> </PropertyGroup> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" /> <PropertyGroup /> <Import Project="VisualBasicAnalyzers.UnitTests.projitems" Label="Shared" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.VisualBasic.targets" /> </Project>
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Compilers/CSharp/Test/Syntax/Parsing/DeconstructionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing { // Some examples of parsing subtleties: // `(T id, ...) = ...` is a deconstruction-assignment into a tuple expression with declaration expressions // `var (id, ...) = ...` is a deconstruction-assignment // `(T id, ...) id;` starts with a tuple type // `(T, ...) id;` starts with tuple type // `(T, ...)[] id;` starts with a tuple type array // `(E, ...) = ...;` is a deconstruction-assignment // `(E, ...).Goo();` starts with a tuple literal/expression // `(E, ...) + ...` also starts with a tuple literal/expression // `(T, ...)? id;` starts with a tuple type [CompilerTrait(CompilerFeature.Tuples)] public class DeconstructionTests : ParsingTests { public DeconstructionTests(ITestOutputHelper output) : base(output) { } protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { return SyntaxFactory.ParseSyntaxTree(text, options: options); } [Fact] public void ParenExpression() { // `(id) .` starts with a parenthesized expression var tree = UsingTree(@" class C { void Goo() { (x).ToString(); } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TupleTypeWithElementNames() { // `(T id, ...) id` starts with a tuple type var tree = UsingTree(@" class C { void Goo() { (Int32 a, Int64 b) x; } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TupleType() { // `(T, ...) id` starts with a type var tree = UsingTree(@" class C { void Goo() { (Int32, Int64) x; } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TupleTypeArray() { // (T, ...) [] is a type var tree = UsingTree(@" class C { void Goo() { (Int32, Int64)[] x; } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TupleLiteral() { // (E, ...) followed by ., +, -, etc. starts with a tuple literal/expression var tree = UsingTree(@" class C { void Goo() { (Int32, Int64).Goo(); } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DeconstructionAssignment() { // (E, ...) = is a deconstruction-assignment var tree = UsingTree(@" class C { void Goo() { (x, y) = goo; } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void SimpleDeclaration() { var tree = UsingTree(@" class C { void Goo() { for(Int32 x = goo; ; ) { } } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ForStatement); { N(SyntaxKind.ForKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int32"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "goo"); } } } } N(SyntaxKind.SemicolonToken); N(SyntaxKind.SemicolonToken); N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void NestedDeconstructionAssignment() { // (E, ...) = is a deconstruction-assignment var tree = UsingTree(@" class C { void Goo() { (x, (y, z)) = goo; } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DeconstructionDeclaration() { // `(T id, ...) = ...` is a deconstruction-declaration var tree = UsingTree(@" class C { void Goo() { (Int32 a, Int64 b) = goo; } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int32"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "a"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int64"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "goo"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void NestedDeconstructionDeclaration() { // `(T id, (...)) = ...` is a deconstruction-declaration var tree = UsingTree(@" class C { void Goo() { ((Int32 a, Int64 b), Int32 c) = goo; } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int32"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "a"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int64"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int32"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "c"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "goo"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void VarDeconstructionDeclaration() { // `var (id, ...) = ...` is a deconstruction-declaration var tree = UsingTree(@" class C { void Goo() { var (a, b) = goo; } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "goo"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void VarNestedDeconstructionDeclaration() { // `var ((id, ...), ...) = ...` is a deconstruction-declaration var tree = UsingTree(@" class C { void Goo() { var ((a, b), c) = goo; } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "goo"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void VarMethodCall() { // `var(...);` is a method call var tree = UsingTree(@" class C { void Goo() { var(a, b); } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void MixedDeconstructionVariables() { var tree = UsingTree(@" class C { void Goo() { (Int32 x, var (y, z)) = goo; } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int32"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CommaToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "z"); } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "goo"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DeconstructionFor() { var tree = UsingTree(@" class C { void Goo() { for ((Int32 x, Int64 y) = goo; ; ) { } } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ForStatement); { N(SyntaxKind.ForKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int32"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int64"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "goo"); } } N(SyntaxKind.SemicolonToken); N(SyntaxKind.SemicolonToken); N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void VarDeconstructionFor() { var tree = UsingTree(@" class C { void Goo() { for (var (x, y) = goo; ; ) { } } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ForStatement); { N(SyntaxKind.ForKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "goo"); } } N(SyntaxKind.SemicolonToken); N(SyntaxKind.SemicolonToken); N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DeconstructionForeach() { var tree = UsingTree(@" class C { void Goo() { foreach ((int x, var y) in goo) { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "goo"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void VarDeconstructionForeach() { var tree = UsingTree(@" class C { void Goo() { foreach (var (x, y) in goo) { } } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "goo"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DeconstructionInScript() { var tree = UsingTree(@" (int x, int y) = (1, 2); ", options: TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DeconstructionForEachInScript() { var tree = UsingTree(@" foreach ((int x, int y) in new[] { (1, 2) }) { }; ", options: TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.InKeyword); N(SyntaxKind.ImplicitArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.OpenBracketToken); N(SyntaxKind.CloseBracketToken); N(SyntaxKind.ArrayInitializerExpression); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DeconstructionDeclarationWithDiscard() { var tree = UsingTree(@" class C { void Goo() { (int _, var _, var (_, _), _) = e; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TupleArray() { var text = "(T, T)[] id;"; var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.False(statement.HasErrors); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); var declaration = ((LocalDeclarationStatementSyntax)statement).Declaration; Assert.Equal("(T, T)[]", declaration.Type.ToString()); Assert.Equal("id", declaration.Variables.ToString()); } [Fact] public void ParenthesizedExpression() { var text = "(x).ToString();"; var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.False(statement.HasErrors); Assert.Equal(SyntaxKind.ExpressionStatement, statement.Kind()); var expression = ((ExpressionStatementSyntax)statement).Expression; Assert.Equal(SyntaxKind.InvocationExpression, expression.Kind()); } [Fact] public void TupleLiteralStatement() { var text = "(x, x).ToString();"; var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.False(statement.HasErrors); Assert.Equal(SyntaxKind.ExpressionStatement, statement.Kind()); var expression = ((ExpressionStatementSyntax)statement).Expression; Assert.Equal(SyntaxKind.InvocationExpression, expression.Kind()); } [Fact] public void Statement4() { var text = "((x)).ToString();"; var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.False(statement.HasErrors); Assert.Equal(SyntaxKind.ExpressionStatement, statement.Kind()); var expression = ((ExpressionStatementSyntax)statement).Expression; Assert.Equal(SyntaxKind.InvocationExpression, expression.Kind()); } [Fact] public void Statement5() { var text = "((x, y) = M()).ToString();"; var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.False(statement.HasErrors); Assert.Equal(SyntaxKind.ExpressionStatement, statement.Kind()); var expression = ((ExpressionStatementSyntax)statement).Expression; Assert.Equal(SyntaxKind.InvocationExpression, expression.Kind()); var invocation = (InvocationExpressionSyntax)expression; var lhs = (MemberAccessExpressionSyntax)invocation.Expression; var lhsContent = (ParenthesizedExpressionSyntax)lhs.Expression; Assert.Equal(SyntaxKind.SimpleAssignmentExpression, lhsContent.Expression.Kind()); } [Fact] public void CastWithTupleType() { var text = "(((x, y))z).Goo();"; var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.False(statement.HasErrors); Assert.Equal(SyntaxKind.ExpressionStatement, statement.Kind()); var expression = ((ExpressionStatementSyntax)statement).Expression; Assert.Equal(SyntaxKind.InvocationExpression, expression.Kind()); var invocation = (InvocationExpressionSyntax)expression; var lhs = (MemberAccessExpressionSyntax)invocation.Expression; var lhsContent = (ParenthesizedExpressionSyntax)lhs.Expression; Assert.Equal(SyntaxKind.CastExpression, lhsContent.Expression.Kind()); } [Fact] public void NotACast() { var text = "((Int32.MaxValue, Int32.MaxValue)).ToString();"; var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.False(statement.HasErrors); var expression = ((ExpressionStatementSyntax)statement).Expression; var invocation = (InvocationExpressionSyntax)expression; var lhs = (MemberAccessExpressionSyntax)invocation.Expression; var paren = (ParenthesizedExpressionSyntax)lhs.Expression; Assert.Equal(SyntaxKind.TupleExpression, paren.Expression.Kind()); } [Fact] public void AlsoNotACast() { var text = "((x, y)).ToString();"; var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.False(statement.HasErrors); var expression = ((ExpressionStatementSyntax)statement).Expression; var invocation = (InvocationExpressionSyntax)expression; var lhs = (MemberAccessExpressionSyntax)invocation.Expression; var paren = (ParenthesizedExpressionSyntax)lhs.Expression; Assert.Equal(SyntaxKind.TupleExpression, paren.Expression.Kind()); } [Fact] public void StillNotACast() { var text = "((((x, y)))).ToString();"; var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.False(statement.HasErrors); var expression = ((ExpressionStatementSyntax)statement).Expression; var invocation = (InvocationExpressionSyntax)expression; var lhs = (MemberAccessExpressionSyntax)invocation.Expression; var paren1 = (ParenthesizedExpressionSyntax)lhs.Expression; var paren2 = (ParenthesizedExpressionSyntax)paren1.Expression; var paren3 = (ParenthesizedExpressionSyntax)paren2.Expression; Assert.Equal(SyntaxKind.TupleExpression, paren3.Expression.Kind()); } [Fact] public void LambdaInExpressionStatement() { var text = "(a) => a;"; // syntax ok var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.False(statement.HasErrors); var expression = ((ExpressionStatementSyntax)statement).Expression; Assert.Equal(SyntaxKind.ParenthesizedLambdaExpression, expression.Kind()); } [Fact] public void LambdaWithBodyInExpressionStatement() { var text = "(a, b) => { };"; // syntax ok var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.False(statement.HasErrors); var expression = ((ExpressionStatementSyntax)statement).Expression; Assert.Equal(SyntaxKind.ParenthesizedLambdaExpression, expression.Kind()); } [Fact] public void InvalidStatement() { var text = "(x, y)? = M();"; // error var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.True(statement.HasErrors); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/12402")] [WorkItem(12402, "https://github.com/dotnet/roslyn/issues/12402")] public void ConfusedForWithDeconstruction() { var text = "for ((int x, var (y, z)) in goo) { }"; var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); // This expectation is wrong. We should expect a foreach statement (because the 'in' keyword is there) Assert.True(statement.Kind() == SyntaxKind.ForStatement); } [Fact] public void NullableTuple() { var text = "(x, y)? z = M();"; var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.False(statement.HasErrors); var declaration = ((LocalDeclarationStatementSyntax)statement).Declaration; var nullable = (NullableTypeSyntax)declaration.Type; Assert.Equal(SyntaxKind.TupleType, nullable.ElementType.Kind()); } [Fact, WorkItem(12803, "https://github.com/dotnet/roslyn/issues/12803")] public void BadTupleElementTypeInDeconstruction01() { var source = @" class C { void M() { int (x1, x2) = (1, 2); } } namespace System { struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } }"; CreateCompilation(source).VerifyDiagnostics( // (6,18): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'. // int (x1, x2) = (1, 2); Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x1, x2)").WithLocation(6, 13) ); } [Fact, WorkItem(12803, "https://github.com/dotnet/roslyn/issues/12803")] public void MixedDeclarationAndAssignmentInTupleDeconstruct() { var source = @" class C { int x2, x3; void M() { (int x1, x2) = (1, 2); (x3, int x4) = (1, 2); } } namespace System { struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } }"; CreateCompilation(source, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics(); } [Fact, WorkItem(12803, "https://github.com/dotnet/roslyn/issues/12803")] public void MixedDeclarationAndAssignmentInTupleDeconstructCSharp9() { var source = @" class C { int x2, x3; void M() { (int x1, x2) = (1, 2); (x3, int x4) = (1, 2); } } namespace System { struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } }"; CreateCompilation(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (7,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (int x1, x2) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(int x1, x2) = (1, 2)").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(7, 9), // (8,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (x3, int x4) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(x3, int x4) = (1, 2)").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(8, 9)); } [Fact, WorkItem(12803, "https://github.com/dotnet/roslyn/issues/12803")] public void SwapAssignmentShouldNotBeParsedAsDeconstructionDeclaration() { var source = @" class C { void M(ref int x, ref int y) { (x, y) = (y, x); } } namespace System { struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } }"; CreateCompilation(source).VerifyDiagnostics( ); } [Fact] public void NoDeconstructionAsLvalue() { var source = @" class C { void M() { var (x, y) = e; // ok, deconstruction declaration var(x, y); // ok, invocation int x = var(x, y); // ok, invocation } }"; ParseAndValidate(source); } [Fact] public void NoDeconstructionAsLvalue_1() { var source = @" class C { void M(string e) { var(x, y) += e; // error 1 } }"; CreateCompilation(source).VerifyDiagnostics( // (6,9): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // var(x, y) += e; // error 1 Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var(x, y)").WithLocation(6, 9), // (6,9): error CS0103: The name 'var' does not exist in the current context // var(x, y) += e; // error 1 Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 9), // (6,13): error CS0103: The name 'x' does not exist in the current context // var(x, y) += e; // error 1 Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(6, 13), // (6,16): error CS0103: The name 'y' does not exist in the current context // var(x, y) += e; // error 1 Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(6, 16)); } [Fact] public void NoDeconstructionAsLvalue_2() { var source = @" class C { void M(string e) { var(x, y)++; // error 2 } }"; CreateCompilation(source).VerifyDiagnostics( // (6,9): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // var(x, y)++; // error 2 Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var(x, y)").WithLocation(6, 9), // (6,9): error CS0103: The name 'var' does not exist in the current context // var(x, y)++; // error 2 Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 9), // (6,13): error CS0103: The name 'x' does not exist in the current context // var(x, y)++; // error 2 Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(6, 13), // (6,16): error CS0103: The name 'y' does not exist in the current context // var(x, y)++; // error 2 Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(6, 16)); } [Fact] public void NoDeconstructionAsLvalue_3() { var source = @" class C { void M(string e) { ++var(x, y); // error 3 } }"; CreateCompilation(source).VerifyDiagnostics( // (6,11): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // ++var(x, y); // error 3 Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var(x, y)").WithLocation(6, 11), // (6,11): error CS0103: The name 'var' does not exist in the current context // ++var(x, y); // error 3 Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 11), // (6,15): error CS0103: The name 'x' does not exist in the current context // ++var(x, y); // error 3 Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(6, 15), // (6,18): error CS0103: The name 'y' does not exist in the current context // ++var(x, y); // error 3 Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(6, 18)); } [Fact] public void NoDeconstructionAsLvalue_4() { var source = @" class C { void M(string e) { X(out var(x, y)); // error 4 } void X(out object x) { x = null; } }"; CreateCompilation(source).VerifyDiagnostics( // (6,15): error CS0103: The name 'var' does not exist in the current context // X(out var(x, y)); // error 4 Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 15), // (6,19): error CS0103: The name 'x' does not exist in the current context // X(out var(x, y)); // error 4 Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(6, 19), // (6,22): error CS0103: The name 'y' does not exist in the current context // X(out var(x, y)); // error 4 Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(6, 22), // (6,15): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // X(out var(x, y)); // error 4 Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var(x, y)").WithLocation(6, 15)); } [Fact] public void NoDeconstructionAsLvalue_5() { var source = @" class C { void M(string e) { X(ref var(x, y)); // error 5 } void X(ref object x) { x = null; } }"; CreateCompilation(source).VerifyDiagnostics( // (6,15): error CS0103: The name 'var' does not exist in the current context // X(ref var(x, y)); // error 5 Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 15), // (6,19): error CS0103: The name 'x' does not exist in the current context // X(ref var(x, y)); // error 5 Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(6, 19), // (6,22): error CS0103: The name 'y' does not exist in the current context // X(ref var(x, y)); // error 5 Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(6, 22), // (6,15): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // X(ref var(x, y)); // error 5 Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var(x, y)").WithLocation(6, 15)); } [Fact] public void NoDeconstructionAsLvalue_6() { var source = @" class C { ref object M(string e) { return ref var(x, y); // error 6 } }"; CreateCompilation(source).VerifyDiagnostics( // (6,20): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // return ref var(x, y); // error 6 Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var(x, y)").WithLocation(6, 20), // (6,20): error CS0103: The name 'var' does not exist in the current context // return ref var(x, y); // error 6 Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 20), // (6,24): error CS0103: The name 'x' does not exist in the current context // return ref var(x, y); // error 6 Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(6, 24), // (6,27): error CS0103: The name 'y' does not exist in the current context // return ref var(x, y); // error 6 Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(6, 27)); } [Fact] public void NoDeconstructionAsLvalue_7() { var source = @" class C { void M(string e) { ref int x = ref var(x, y); // error 7 } }"; CreateCompilation(source).VerifyDiagnostics( // (6,25): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // ref int x = ref var(x, y); // error 7 Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var(x, y)").WithLocation(6, 25), // (6,25): error CS0103: The name 'var' does not exist in the current context // ref int x = ref var(x, y); // error 7 Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 25), // (6,32): error CS0103: The name 'y' does not exist in the current context // ref int x = ref var(x, y); // error 7 Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(6, 32), // (6,29): error CS0165: Use of unassigned local variable 'x' // ref int x = ref var(x, y); // error 7 Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(6, 29)); } [Fact] public void NoDeconstructionAsLvalue_8() { var source = @" class C { void object M(string e) { var (x, 1) = e; // error 8 } }"; CreateCompilation(source).VerifyDiagnostics( // (4,10): error CS1519: Invalid token 'object' in class, record, struct, or interface member declaration // void object M(string e) Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "object").WithArguments("object").WithLocation(4, 10), // (6,9): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // var (x, 1) = e; // error 8 Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x, 1)").WithLocation(6, 9), // (6,9): error CS0103: The name 'var' does not exist in the current context // var (x, 1) = e; // error 8 Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 9), // (6,14): error CS0103: The name 'x' does not exist in the current context // var (x, 1) = e; // error 8 Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(6, 14), // (4,17): error CS0161: 'C.M(string)': not all code paths return a value // void object M(string e) Diagnostic(ErrorCode.ERR_ReturnExpected, "M").WithArguments("C.M(string)").WithLocation(4, 17)); } [Fact] public void DiscardsInDeconstruction_01() { var tree = UsingTree(@"void M() { var (x, _) = e; }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DiscardsInDeconstruction_02() { var tree = UsingTree(@"void M() { (var x, var _) = e; }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DiscardsInOut_01() { var tree = UsingTree(@"void M() { M(out var _); }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DiscardsInOut_02() { var tree = UsingTree(@"void M() { M(out int _); }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DiscardsInPattern_01() { var tree = UsingTree(@"void M() { if (e is int _) {} }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DiscardsInPattern_02() { var tree = UsingTree(@"void M() { if (e is var _) {} }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword, "var"); N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DiscardsInPattern_03() { var tree = UsingTree(@"void M() { switch (e) { case int _: break; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DiscardsInPattern_04() { var tree = UsingTree(@"void M() { switch (e) { case var _: break; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword, "var"); N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void BadTypeForDeconstruct_00() { UsingStatement(@"var (x, y) = e;"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void BadTypeForDeconstruct_01() { UsingStatement(@"var::var (x, y) = e;"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void BadTypeForDeconstruct_02() { UsingStatement(@"var.var (x, y) = e;"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void BadTypeForDeconstruct_03() { UsingStatement(@"var<var> (x, y) = e;"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "var"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void BadTypeForDeconstruct_04() { UsingStatement(@"var[] (x, y) = e;", // (1,5): error CS0443: Syntax error; value expected // var[] (x, y) = e; Diagnostic(ErrorCode.ERR_ValueExpected, "]").WithLocation(1, 5) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); M(SyntaxKind.Argument); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void BadTypeForDeconstruct_05() { UsingStatement(@"var* (x, y) = e;"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void BadTypeForDeconstruct_06() { UsingStatement(@"var? (x, y) = e;", // (1,16): error CS1003: Syntax error, ':' expected // var? (x, y) = e; Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";").WithLocation(1, 16), // (1,16): error CS1525: Invalid expression term ';' // var? (x, y) = e; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(1, 16) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void BadTypeForDeconstruct_07() { UsingStatement(@"var?.var (x, y) = e;"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.ConditionalAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.MemberBindingExpression); { N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(15934, "https://github.com/dotnet/roslyn/issues/15934")] public void PointerTypeInDeconstruction() { string source = @" class C { void M() { // syntax error: pointer types only permitted as an array element type in a tuple (int* x1, int y1) = e; // These are OK, because an array is a valid type in a tuple. (int*[] x2, int y2) = e; (var*[] x3, int y3) = e; // Multiplication in a tuple element is also OK (var* x4, int y4) = e; (var* x5, var* y5) = e; e = (var* x6, var* y6); } } "; UsingTree(source).GetDiagnostics().Verify( // (7,10): error CS1525: Invalid expression term 'int' // (int* x1, int y1) = e; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(7, 10) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x1"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x2"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y2"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y3"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x4"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x5"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y5"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x6"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y6"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing { // Some examples of parsing subtleties: // `(T id, ...) = ...` is a deconstruction-assignment into a tuple expression with declaration expressions // `var (id, ...) = ...` is a deconstruction-assignment // `(T id, ...) id;` starts with a tuple type // `(T, ...) id;` starts with tuple type // `(T, ...)[] id;` starts with a tuple type array // `(E, ...) = ...;` is a deconstruction-assignment // `(E, ...).Goo();` starts with a tuple literal/expression // `(E, ...) + ...` also starts with a tuple literal/expression // `(T, ...)? id;` starts with a tuple type [CompilerTrait(CompilerFeature.Tuples)] public class DeconstructionTests : ParsingTests { public DeconstructionTests(ITestOutputHelper output) : base(output) { } protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { return SyntaxFactory.ParseSyntaxTree(text, options: options); } [Fact] public void ParenExpression() { // `(id) .` starts with a parenthesized expression var tree = UsingTree(@" class C { void Goo() { (x).ToString(); } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TupleTypeWithElementNames() { // `(T id, ...) id` starts with a tuple type var tree = UsingTree(@" class C { void Goo() { (Int32 a, Int64 b) x; } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TupleType() { // `(T, ...) id` starts with a type var tree = UsingTree(@" class C { void Goo() { (Int32, Int64) x; } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TupleTypeArray() { // (T, ...) [] is a type var tree = UsingTree(@" class C { void Goo() { (Int32, Int64)[] x; } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TupleLiteral() { // (E, ...) followed by ., +, -, etc. starts with a tuple literal/expression var tree = UsingTree(@" class C { void Goo() { (Int32, Int64).Goo(); } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DeconstructionAssignment() { // (E, ...) = is a deconstruction-assignment var tree = UsingTree(@" class C { void Goo() { (x, y) = goo; } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void SimpleDeclaration() { var tree = UsingTree(@" class C { void Goo() { for(Int32 x = goo; ; ) { } } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ForStatement); { N(SyntaxKind.ForKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int32"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "goo"); } } } } N(SyntaxKind.SemicolonToken); N(SyntaxKind.SemicolonToken); N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void NestedDeconstructionAssignment() { // (E, ...) = is a deconstruction-assignment var tree = UsingTree(@" class C { void Goo() { (x, (y, z)) = goo; } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DeconstructionDeclaration() { // `(T id, ...) = ...` is a deconstruction-declaration var tree = UsingTree(@" class C { void Goo() { (Int32 a, Int64 b) = goo; } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int32"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "a"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int64"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "goo"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void NestedDeconstructionDeclaration() { // `(T id, (...)) = ...` is a deconstruction-declaration var tree = UsingTree(@" class C { void Goo() { ((Int32 a, Int64 b), Int32 c) = goo; } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int32"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "a"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int64"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int32"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "c"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "goo"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void VarDeconstructionDeclaration() { // `var (id, ...) = ...` is a deconstruction-declaration var tree = UsingTree(@" class C { void Goo() { var (a, b) = goo; } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "goo"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void VarNestedDeconstructionDeclaration() { // `var ((id, ...), ...) = ...` is a deconstruction-declaration var tree = UsingTree(@" class C { void Goo() { var ((a, b), c) = goo; } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "goo"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void VarMethodCall() { // `var(...);` is a method call var tree = UsingTree(@" class C { void Goo() { var(a, b); } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void MixedDeconstructionVariables() { var tree = UsingTree(@" class C { void Goo() { (Int32 x, var (y, z)) = goo; } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int32"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CommaToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "z"); } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "goo"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DeconstructionFor() { var tree = UsingTree(@" class C { void Goo() { for ((Int32 x, Int64 y) = goo; ; ) { } } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ForStatement); { N(SyntaxKind.ForKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int32"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int64"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "goo"); } } N(SyntaxKind.SemicolonToken); N(SyntaxKind.SemicolonToken); N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void VarDeconstructionFor() { var tree = UsingTree(@" class C { void Goo() { for (var (x, y) = goo; ; ) { } } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ForStatement); { N(SyntaxKind.ForKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "goo"); } } N(SyntaxKind.SemicolonToken); N(SyntaxKind.SemicolonToken); N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DeconstructionForeach() { var tree = UsingTree(@" class C { void Goo() { foreach ((int x, var y) in goo) { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "goo"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void VarDeconstructionForeach() { var tree = UsingTree(@" class C { void Goo() { foreach (var (x, y) in goo) { } } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "goo"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DeconstructionInScript() { var tree = UsingTree(@" (int x, int y) = (1, 2); ", options: TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DeconstructionForEachInScript() { var tree = UsingTree(@" foreach ((int x, int y) in new[] { (1, 2) }) { }; ", options: TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.InKeyword); N(SyntaxKind.ImplicitArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.OpenBracketToken); N(SyntaxKind.CloseBracketToken); N(SyntaxKind.ArrayInitializerExpression); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DeconstructionDeclarationWithDiscard() { var tree = UsingTree(@" class C { void Goo() { (int _, var _, var (_, _), _) = e; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TupleArray() { var text = "(T, T)[] id;"; var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.False(statement.HasErrors); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); var declaration = ((LocalDeclarationStatementSyntax)statement).Declaration; Assert.Equal("(T, T)[]", declaration.Type.ToString()); Assert.Equal("id", declaration.Variables.ToString()); } [Fact] public void ParenthesizedExpression() { var text = "(x).ToString();"; var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.False(statement.HasErrors); Assert.Equal(SyntaxKind.ExpressionStatement, statement.Kind()); var expression = ((ExpressionStatementSyntax)statement).Expression; Assert.Equal(SyntaxKind.InvocationExpression, expression.Kind()); } [Fact] public void TupleLiteralStatement() { var text = "(x, x).ToString();"; var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.False(statement.HasErrors); Assert.Equal(SyntaxKind.ExpressionStatement, statement.Kind()); var expression = ((ExpressionStatementSyntax)statement).Expression; Assert.Equal(SyntaxKind.InvocationExpression, expression.Kind()); } [Fact] public void Statement4() { var text = "((x)).ToString();"; var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.False(statement.HasErrors); Assert.Equal(SyntaxKind.ExpressionStatement, statement.Kind()); var expression = ((ExpressionStatementSyntax)statement).Expression; Assert.Equal(SyntaxKind.InvocationExpression, expression.Kind()); } [Fact] public void Statement5() { var text = "((x, y) = M()).ToString();"; var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.False(statement.HasErrors); Assert.Equal(SyntaxKind.ExpressionStatement, statement.Kind()); var expression = ((ExpressionStatementSyntax)statement).Expression; Assert.Equal(SyntaxKind.InvocationExpression, expression.Kind()); var invocation = (InvocationExpressionSyntax)expression; var lhs = (MemberAccessExpressionSyntax)invocation.Expression; var lhsContent = (ParenthesizedExpressionSyntax)lhs.Expression; Assert.Equal(SyntaxKind.SimpleAssignmentExpression, lhsContent.Expression.Kind()); } [Fact] public void CastWithTupleType() { var text = "(((x, y))z).Goo();"; var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.False(statement.HasErrors); Assert.Equal(SyntaxKind.ExpressionStatement, statement.Kind()); var expression = ((ExpressionStatementSyntax)statement).Expression; Assert.Equal(SyntaxKind.InvocationExpression, expression.Kind()); var invocation = (InvocationExpressionSyntax)expression; var lhs = (MemberAccessExpressionSyntax)invocation.Expression; var lhsContent = (ParenthesizedExpressionSyntax)lhs.Expression; Assert.Equal(SyntaxKind.CastExpression, lhsContent.Expression.Kind()); } [Fact] public void NotACast() { var text = "((Int32.MaxValue, Int32.MaxValue)).ToString();"; var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.False(statement.HasErrors); var expression = ((ExpressionStatementSyntax)statement).Expression; var invocation = (InvocationExpressionSyntax)expression; var lhs = (MemberAccessExpressionSyntax)invocation.Expression; var paren = (ParenthesizedExpressionSyntax)lhs.Expression; Assert.Equal(SyntaxKind.TupleExpression, paren.Expression.Kind()); } [Fact] public void AlsoNotACast() { var text = "((x, y)).ToString();"; var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.False(statement.HasErrors); var expression = ((ExpressionStatementSyntax)statement).Expression; var invocation = (InvocationExpressionSyntax)expression; var lhs = (MemberAccessExpressionSyntax)invocation.Expression; var paren = (ParenthesizedExpressionSyntax)lhs.Expression; Assert.Equal(SyntaxKind.TupleExpression, paren.Expression.Kind()); } [Fact] public void StillNotACast() { var text = "((((x, y)))).ToString();"; var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.False(statement.HasErrors); var expression = ((ExpressionStatementSyntax)statement).Expression; var invocation = (InvocationExpressionSyntax)expression; var lhs = (MemberAccessExpressionSyntax)invocation.Expression; var paren1 = (ParenthesizedExpressionSyntax)lhs.Expression; var paren2 = (ParenthesizedExpressionSyntax)paren1.Expression; var paren3 = (ParenthesizedExpressionSyntax)paren2.Expression; Assert.Equal(SyntaxKind.TupleExpression, paren3.Expression.Kind()); } [Fact] public void LambdaInExpressionStatement() { var text = "(a) => a;"; // syntax ok var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.False(statement.HasErrors); var expression = ((ExpressionStatementSyntax)statement).Expression; Assert.Equal(SyntaxKind.ParenthesizedLambdaExpression, expression.Kind()); } [Fact] public void LambdaWithBodyInExpressionStatement() { var text = "(a, b) => { };"; // syntax ok var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.False(statement.HasErrors); var expression = ((ExpressionStatementSyntax)statement).Expression; Assert.Equal(SyntaxKind.ParenthesizedLambdaExpression, expression.Kind()); } [Fact] public void InvalidStatement() { var text = "(x, y)? = M();"; // error var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.True(statement.HasErrors); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/12402")] [WorkItem(12402, "https://github.com/dotnet/roslyn/issues/12402")] public void ConfusedForWithDeconstruction() { var text = "for ((int x, var (y, z)) in goo) { }"; var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); // This expectation is wrong. We should expect a foreach statement (because the 'in' keyword is there) Assert.True(statement.Kind() == SyntaxKind.ForStatement); } [Fact] public void NullableTuple() { var text = "(x, y)? z = M();"; var statement = SyntaxFactory.ParseStatement(text, offset: 0, options: TestOptions.Regular.WithTuplesFeature()); Assert.False(statement.HasErrors); var declaration = ((LocalDeclarationStatementSyntax)statement).Declaration; var nullable = (NullableTypeSyntax)declaration.Type; Assert.Equal(SyntaxKind.TupleType, nullable.ElementType.Kind()); } [Fact, WorkItem(12803, "https://github.com/dotnet/roslyn/issues/12803")] public void BadTupleElementTypeInDeconstruction01() { var source = @" class C { void M() { int (x1, x2) = (1, 2); } } namespace System { struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } }"; CreateCompilation(source).VerifyDiagnostics( // (6,18): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'. // int (x1, x2) = (1, 2); Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x1, x2)").WithLocation(6, 13) ); } [Fact, WorkItem(12803, "https://github.com/dotnet/roslyn/issues/12803")] public void MixedDeclarationAndAssignmentInTupleDeconstruct() { var source = @" class C { int x2, x3; void M() { (int x1, x2) = (1, 2); (x3, int x4) = (1, 2); } } namespace System { struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } }"; CreateCompilation(source, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics(); } [Fact, WorkItem(12803, "https://github.com/dotnet/roslyn/issues/12803")] public void MixedDeclarationAndAssignmentInTupleDeconstructCSharp9() { var source = @" class C { int x2, x3; void M() { (int x1, x2) = (1, 2); (x3, int x4) = (1, 2); } } namespace System { struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } }"; CreateCompilation(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (7,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (int x1, x2) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(int x1, x2) = (1, 2)").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(7, 9), // (8,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (x3, int x4) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(x3, int x4) = (1, 2)").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(8, 9)); } [Fact, WorkItem(12803, "https://github.com/dotnet/roslyn/issues/12803")] public void SwapAssignmentShouldNotBeParsedAsDeconstructionDeclaration() { var source = @" class C { void M(ref int x, ref int y) { (x, y) = (y, x); } } namespace System { struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } }"; CreateCompilation(source).VerifyDiagnostics( ); } [Fact] public void NoDeconstructionAsLvalue() { var source = @" class C { void M() { var (x, y) = e; // ok, deconstruction declaration var(x, y); // ok, invocation int x = var(x, y); // ok, invocation } }"; ParseAndValidate(source); } [Fact] public void NoDeconstructionAsLvalue_1() { var source = @" class C { void M(string e) { var(x, y) += e; // error 1 } }"; CreateCompilation(source).VerifyDiagnostics( // (6,9): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // var(x, y) += e; // error 1 Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var(x, y)").WithLocation(6, 9), // (6,9): error CS0103: The name 'var' does not exist in the current context // var(x, y) += e; // error 1 Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 9), // (6,13): error CS0103: The name 'x' does not exist in the current context // var(x, y) += e; // error 1 Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(6, 13), // (6,16): error CS0103: The name 'y' does not exist in the current context // var(x, y) += e; // error 1 Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(6, 16)); } [Fact] public void NoDeconstructionAsLvalue_2() { var source = @" class C { void M(string e) { var(x, y)++; // error 2 } }"; CreateCompilation(source).VerifyDiagnostics( // (6,9): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // var(x, y)++; // error 2 Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var(x, y)").WithLocation(6, 9), // (6,9): error CS0103: The name 'var' does not exist in the current context // var(x, y)++; // error 2 Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 9), // (6,13): error CS0103: The name 'x' does not exist in the current context // var(x, y)++; // error 2 Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(6, 13), // (6,16): error CS0103: The name 'y' does not exist in the current context // var(x, y)++; // error 2 Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(6, 16)); } [Fact] public void NoDeconstructionAsLvalue_3() { var source = @" class C { void M(string e) { ++var(x, y); // error 3 } }"; CreateCompilation(source).VerifyDiagnostics( // (6,11): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // ++var(x, y); // error 3 Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var(x, y)").WithLocation(6, 11), // (6,11): error CS0103: The name 'var' does not exist in the current context // ++var(x, y); // error 3 Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 11), // (6,15): error CS0103: The name 'x' does not exist in the current context // ++var(x, y); // error 3 Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(6, 15), // (6,18): error CS0103: The name 'y' does not exist in the current context // ++var(x, y); // error 3 Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(6, 18)); } [Fact] public void NoDeconstructionAsLvalue_4() { var source = @" class C { void M(string e) { X(out var(x, y)); // error 4 } void X(out object x) { x = null; } }"; CreateCompilation(source).VerifyDiagnostics( // (6,15): error CS0103: The name 'var' does not exist in the current context // X(out var(x, y)); // error 4 Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 15), // (6,19): error CS0103: The name 'x' does not exist in the current context // X(out var(x, y)); // error 4 Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(6, 19), // (6,22): error CS0103: The name 'y' does not exist in the current context // X(out var(x, y)); // error 4 Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(6, 22), // (6,15): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // X(out var(x, y)); // error 4 Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var(x, y)").WithLocation(6, 15)); } [Fact] public void NoDeconstructionAsLvalue_5() { var source = @" class C { void M(string e) { X(ref var(x, y)); // error 5 } void X(ref object x) { x = null; } }"; CreateCompilation(source).VerifyDiagnostics( // (6,15): error CS0103: The name 'var' does not exist in the current context // X(ref var(x, y)); // error 5 Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 15), // (6,19): error CS0103: The name 'x' does not exist in the current context // X(ref var(x, y)); // error 5 Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(6, 19), // (6,22): error CS0103: The name 'y' does not exist in the current context // X(ref var(x, y)); // error 5 Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(6, 22), // (6,15): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // X(ref var(x, y)); // error 5 Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var(x, y)").WithLocation(6, 15)); } [Fact] public void NoDeconstructionAsLvalue_6() { var source = @" class C { ref object M(string e) { return ref var(x, y); // error 6 } }"; CreateCompilation(source).VerifyDiagnostics( // (6,20): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // return ref var(x, y); // error 6 Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var(x, y)").WithLocation(6, 20), // (6,20): error CS0103: The name 'var' does not exist in the current context // return ref var(x, y); // error 6 Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 20), // (6,24): error CS0103: The name 'x' does not exist in the current context // return ref var(x, y); // error 6 Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(6, 24), // (6,27): error CS0103: The name 'y' does not exist in the current context // return ref var(x, y); // error 6 Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(6, 27)); } [Fact] public void NoDeconstructionAsLvalue_7() { var source = @" class C { void M(string e) { ref int x = ref var(x, y); // error 7 } }"; CreateCompilation(source).VerifyDiagnostics( // (6,25): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // ref int x = ref var(x, y); // error 7 Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var(x, y)").WithLocation(6, 25), // (6,25): error CS0103: The name 'var' does not exist in the current context // ref int x = ref var(x, y); // error 7 Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 25), // (6,32): error CS0103: The name 'y' does not exist in the current context // ref int x = ref var(x, y); // error 7 Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(6, 32), // (6,29): error CS0165: Use of unassigned local variable 'x' // ref int x = ref var(x, y); // error 7 Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(6, 29)); } [Fact] public void NoDeconstructionAsLvalue_8() { var source = @" class C { void object M(string e) { var (x, 1) = e; // error 8 } }"; CreateCompilation(source).VerifyDiagnostics( // (4,10): error CS1519: Invalid token 'object' in class, record, struct, or interface member declaration // void object M(string e) Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "object").WithArguments("object").WithLocation(4, 10), // (6,9): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // var (x, 1) = e; // error 8 Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x, 1)").WithLocation(6, 9), // (6,9): error CS0103: The name 'var' does not exist in the current context // var (x, 1) = e; // error 8 Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 9), // (6,14): error CS0103: The name 'x' does not exist in the current context // var (x, 1) = e; // error 8 Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(6, 14), // (4,17): error CS0161: 'C.M(string)': not all code paths return a value // void object M(string e) Diagnostic(ErrorCode.ERR_ReturnExpected, "M").WithArguments("C.M(string)").WithLocation(4, 17)); } [Fact] public void DiscardsInDeconstruction_01() { var tree = UsingTree(@"void M() { var (x, _) = e; }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DiscardsInDeconstruction_02() { var tree = UsingTree(@"void M() { (var x, var _) = e; }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DiscardsInOut_01() { var tree = UsingTree(@"void M() { M(out var _); }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DiscardsInOut_02() { var tree = UsingTree(@"void M() { M(out int _); }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DiscardsInPattern_01() { var tree = UsingTree(@"void M() { if (e is int _) {} }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DiscardsInPattern_02() { var tree = UsingTree(@"void M() { if (e is var _) {} }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword, "var"); N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DiscardsInPattern_03() { var tree = UsingTree(@"void M() { switch (e) { case int _: break; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DiscardsInPattern_04() { var tree = UsingTree(@"void M() { switch (e) { case var _: break; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword, "var"); N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void BadTypeForDeconstruct_00() { UsingStatement(@"var (x, y) = e;"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void BadTypeForDeconstruct_01() { UsingStatement(@"var::var (x, y) = e;"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void BadTypeForDeconstruct_02() { UsingStatement(@"var.var (x, y) = e;"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void BadTypeForDeconstruct_03() { UsingStatement(@"var<var> (x, y) = e;"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "var"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void BadTypeForDeconstruct_04() { UsingStatement(@"var[] (x, y) = e;", // (1,5): error CS0443: Syntax error; value expected // var[] (x, y) = e; Diagnostic(ErrorCode.ERR_ValueExpected, "]").WithLocation(1, 5) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); M(SyntaxKind.Argument); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void BadTypeForDeconstruct_05() { UsingStatement(@"var* (x, y) = e;"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void BadTypeForDeconstruct_06() { UsingStatement(@"var? (x, y) = e;", // (1,16): error CS1003: Syntax error, ':' expected // var? (x, y) = e; Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";").WithLocation(1, 16), // (1,16): error CS1525: Invalid expression term ';' // var? (x, y) = e; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(1, 16) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void BadTypeForDeconstruct_07() { UsingStatement(@"var?.var (x, y) = e;"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.ConditionalAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.MemberBindingExpression); { N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(15934, "https://github.com/dotnet/roslyn/issues/15934")] public void PointerTypeInDeconstruction() { string source = @" class C { void M() { // syntax error: pointer types only permitted as an array element type in a tuple (int* x1, int y1) = e; // These are OK, because an array is a valid type in a tuple. (int*[] x2, int y2) = e; (var*[] x3, int y3) = e; // Multiplication in a tuple element is also OK (var* x4, int y4) = e; (var* x5, var* y5) = e; e = (var* x6, var* y6); } } "; UsingTree(source).GetDiagnostics().Verify( // (7,10): error CS1525: Invalid expression term 'int' // (int* x1, int y1) = e; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(7, 10) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x1"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x2"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y2"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y3"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x4"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x5"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y5"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x6"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y6"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Compilers/CSharp/Test/Emit/Emit/CovariantReturnTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Emit { public class CovariantReturnTests : EmitMetadataTestBase { private static MetadataReference _corelibraryWithCovariantReturnSupport; private static MetadataReference CorelibraryWithCovariantReturnSupport { get { if (_corelibraryWithCovariantReturnSupport == null) { _corelibraryWithCovariantReturnSupport = MakeCorelibraryWithCovariantReturnSupport(); } return _corelibraryWithCovariantReturnSupport; } } private static MetadataReference MakeCorelibraryWithCovariantReturnSupport() { const string corLibraryCore = @" namespace System { public class Array { public static T[] Empty<T>() => throw null; } public class Console { public static void WriteLine(string message) => throw null; } public class Attribute { } [Flags] public enum AttributeTargets { Assembly = 0x1, Module = 0x2, Class = 0x4, Struct = 0x8, Enum = 0x10, Constructor = 0x20, Method = 0x40, Property = 0x80, Field = 0x100, Event = 0x200, Interface = 0x400, Parameter = 0x800, Delegate = 0x1000, ReturnValue = 0x2000, GenericParameter = 0x4000, All = 0x7FFF } [AttributeUsage(AttributeTargets.Class, Inherited = true)] public sealed class AttributeUsageAttribute : Attribute { public AttributeUsageAttribute(AttributeTargets validOn) { } public bool AllowMultiple { get => throw null; set { } } public bool Inherited { get => throw null; set { } } public AttributeTargets ValidOn => throw null; } public struct Boolean { } public struct Byte { } public class Delegate { public static Delegate CreateDelegate(Type type, object firstArgument, Reflection.MethodInfo method) => null; } public abstract class Enum : IComparable { } public class Exception { public Exception(string message) => throw null; } public class FlagsAttribute : Attribute { } public delegate T Func<out T>(); public delegate U Func<in T, out U>(T arg); public interface IComparable { } public interface IDisposable { void Dispose(); } public struct Int16 { } public struct Int32 { } public struct IntPtr { } public class MulticastDelegate : Delegate { } public struct Nullable<T> { } public class Object { public virtual string ToString() => throw null; public virtual int GetHashCode() => throw null; public virtual bool Equals(object other) => throw null; } public sealed class ParamArrayAttribute : Attribute { } public struct RuntimeMethodHandle { } public struct RuntimeTypeHandle { } public class String : IComparable { public static String Empty = null; public override string ToString() => throw null; public static bool operator ==(string a, string b) => throw null; public static bool operator !=(string a, string b) => throw null; public override bool Equals(object other) => throw null; public override int GetHashCode() => throw null; } public class Type { public Reflection.FieldInfo GetField(string name) => null; public static Type GetType(string name) => null; public static Type GetTypeFromHandle(RuntimeTypeHandle handle) => null; } public class ValueType { } public struct Void { } namespace Collections { public interface IEnumerable { IEnumerator GetEnumerator(); } public interface IEnumerator { object Current { get; } bool MoveNext(); void Reset(); } } namespace Collections.Generic { public interface IEnumerable<out T> : IEnumerable { new IEnumerator<T> GetEnumerator(); } public interface IEnumerator<out T> : IEnumerator, IDisposable { new T Current { get; } } } namespace Linq.Expressions { public class Expression { public static ParameterExpression Parameter(Type type) => throw null; public static ParameterExpression Parameter(Type type, string name) => throw null; public static MethodCallExpression Call(Expression instance, Reflection.MethodInfo method, params Expression[] arguments) => throw null; public static Expression<TDelegate> Lambda<TDelegate>(Expression body, params ParameterExpression[] parameters) => throw null; public static MemberExpression Property(Expression expression, Reflection.MethodInfo propertyAccessor) => throw null; public static ConstantExpression Constant(object value, Type type) => throw null; public static UnaryExpression Convert(Expression expression, Type type) => throw null; } public class ParameterExpression : Expression { } public class MethodCallExpression : Expression { } public abstract class LambdaExpression : Expression { } public class Expression<T> : LambdaExpression { } public class MemberExpression : Expression { } public class ConstantExpression : Expression { } public sealed class UnaryExpression : Expression { } } namespace Reflection { public class AssemblyVersionAttribute : Attribute { public AssemblyVersionAttribute(string version) { } } public class DefaultMemberAttribute : Attribute { public DefaultMemberAttribute(string name) { } } public abstract class MemberInfo { } public abstract class MethodBase : MemberInfo { public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle) => throw null; } public abstract class MethodInfo : MethodBase { public virtual Delegate CreateDelegate(Type delegateType, object target) => throw null; } public abstract class FieldInfo : MemberInfo { public abstract object GetValue(object obj); } } namespace Runtime.CompilerServices { public static class RuntimeHelpers { public static object GetObjectValue(object obj) => null; } } } "; const string corlibWithCovariantSupport = corLibraryCore + @" namespace System.Runtime.CompilerServices { public static class RuntimeFeature { public const string CovariantReturnsOfClasses = nameof(CovariantReturnsOfClasses); public const string DefaultImplementationsOfInterfaces = nameof(DefaultImplementationsOfInterfaces); } public sealed class PreserveBaseOverridesAttribute : Attribute { } } "; var compilation = CreateEmptyCompilation(new string[] { corlibWithCovariantSupport, @"[assembly: System.Reflection.AssemblyVersion(""4.0.0.0"")]" }, assemblyName: "mscorlib"); compilation.VerifyDiagnostics(); return compilation.EmitToImageReference(options: new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "v5.1")); } private static CSharpCompilation CreateCovariantCompilation( string source, CSharpCompilationOptions options = null, IEnumerable<MetadataReference> references = null, string assemblyName = null) { Assert.NotNull(CorelibraryWithCovariantReturnSupport); references = (references == null) ? new[] { CorelibraryWithCovariantReturnSupport } : references.ToArray().Prepend(CorelibraryWithCovariantReturnSupport); return CreateEmptyCompilation( source, options: options, parseOptions: TestOptions.WithCovariantReturns, references: references, assemblyName: assemblyName); } [ConditionalFact(typeof(CovariantReturnRuntimeOnly))] public void SimpleCovariantReturnEndToEndTest() { var source = @" using System; class Base { public virtual object M() => ""Base.M""; } class Derived : Base { public override string M() => ""Derived.M""; } class Program { static void Main() { Derived d = new Derived(); Base b = d; string s = d.M(); object o = b.M(); Console.WriteLine(s.ToString()); Console.WriteLine(o.ToString()); } } "; var compilation = CreateCovariantCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @"Derived.M Derived.M"; CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: Verification.Skipped); } [ConditionalFact(typeof(CovariantReturnRuntimeOnly))] public void CovariantRuntimeHasRequiredMembers() { var source = @" using System; class Base { public virtual object M() => ""Base.M""; } class Derived : Base { public override string M() => ""Derived.M""; } class Program { static void Main() { var value = (string)Type.GetType(""System.Runtime.CompilerServices.RuntimeFeature"").GetField(""CovariantReturnsOfClasses"").GetValue(null); if (value != ""CovariantReturnsOfClasses"") throw new Exception(value.ToString()); var attr = Type.GetType(""System.Runtime.CompilerServices.PreserveBaseOverridesAttribute""); if (attr == null) throw new Exception(""missing System.Runtime.CompilerServices.PreserveBaseOverridesAttribute""); } } "; var compilation = CreateCovariantCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @""; CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: Verification.Skipped); } [Fact] public void VbOverrideOfCSharpCovariantReturn_01() { var cSharpSource = @" public class Base { public virtual object M() => null; public virtual object P => null; public virtual object this[int i] => null; } public abstract class Derived : Base { public override string M() => null; public override string P => null; public override string this[int i] => null; } "; var csharpCompilation = CreateCovariantCompilation(cSharpSource).VerifyDiagnostics(); var csharpReference = csharpCompilation.EmitToImageReference(); var vbSource = @" Public Class Derived2 : Inherits Derived Public Overrides Function M() As Object Return Nothing End Function Public Overrides ReadOnly Property P As Object Get Return Nothing End Get End Property Public Overrides Default ReadOnly Property Item(i As Integer) As Object Get Return Nothing End Get End Property End Class "; var ERR_InvalidOverrideDueToReturn2 = typeof(VisualBasic.VisualBasicCompilation).Assembly.GetType("Microsoft.CodeAnalysis.VisualBasic.ERRID").GetField("ERR_InvalidOverrideDueToReturn2").GetValue(null); CreateVisualBasicCompilation(vbSource, referencedAssemblies: new[] { CorelibraryWithCovariantReturnSupport, csharpReference }) .VerifyDiagnostics( //BC30437: 'Public Overrides Function M() As Object' cannot override 'Public Overridable Overloads Function M() As String' because they differ by their return types. //Public Overrides Function M() As Object // ~ Diagnostic(ERR_InvalidOverrideDueToReturn2, "M").WithArguments("Public Overrides Function M() As Object", "Public Overridable Overloads Function M() As String").WithLocation(3, 31), //BC30437: 'Public Overrides ReadOnly Property P As Object' cannot override 'Public Overridable Overloads ReadOnly Property P As String' because they differ by their return types. //Public Overrides ReadOnly Property P As Object // ~ Diagnostic(ERR_InvalidOverrideDueToReturn2, "P").WithArguments("Public Overrides ReadOnly Property P As Object", "Public Overridable Overloads ReadOnly Property P As String").WithLocation(6, 40), //BC30437: 'Public Overrides ReadOnly Default Property Item(i As Integer) As Object' cannot override 'Public Overridable Overloads ReadOnly Default Property Item(i As Integer) As String' because they differ by their return types. //Public Overrides Default ReadOnly Property Item(i As Integer) As Object // ~~~~ Diagnostic(ERR_InvalidOverrideDueToReturn2, "Item").WithArguments("Public Overrides ReadOnly Default Property Item(i As Integer) As Object", "Public Overridable Overloads ReadOnly Default Property Item(i As Integer) As String").WithLocation(11, 48) ); } [Fact] public void VbOverrideOfCSharpCovariantReturn_02() { var cSharpSource = @" public class Base { public virtual object M() => ""Base.M""; public virtual object P => ""Base.P""; public virtual object this[int i] => ""Base[]""; } public abstract class Derived : Base { public override string M() => ""Derived.M""; public override string P => ""Derived.P""; public override string this[int i] => ""Derived[]""; } "; var csharpCompilation = CreateCovariantCompilation(cSharpSource).VerifyDiagnostics(); var csharpReference = csharpCompilation.EmitToImageReference(); var vbSource = @" Imports System Public Class Derived2 : Inherits Derived Public Overrides Function M() As String Return ""Derived2.M"" End Function Public Overrides ReadOnly Property P As String Get Return ""Derived2.P"" End Get End Property Public Overrides Default ReadOnly Property Item(i As Integer) As String Get Return ""Derived2[]"" End Get End Property Public Shared Sub Test(b As Base, d As Derived, d2 As Derived2) Console.WriteLine(b.M().ToString()) Console.WriteLine(b.P.ToString()) Console.WriteLine(b(0).ToString()) Console.WriteLine(d.M()) Console.WriteLine(d.P) Console.WriteLine(d(0)) Console.WriteLine(d2.M()) Console.WriteLine(d2.P) Console.WriteLine(d2(0)) End Sub public Shared Sub Main() Dim d2 = new Derived2 Test(d2, d2, d2) End Sub End Class "; var compilationOptions = new VisualBasic.VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptimizationLevel(OptimizationLevel.Release); var vbCompilation = CreateVisualBasicCompilation(vbSource, compilationOptions: compilationOptions, referencedAssemblies: new[] { CorelibraryWithCovariantReturnSupport, csharpReference }) .VerifyDiagnostics( ); var expectedOutput = !ExecutionConditionUtil.RuntimeSupportsCovariantReturnsOfClasses ? null : @" Derived2.M Derived2.P Derived2[] Derived2.M Derived2.P Derived2[] Derived2.M Derived2.P Derived2[]"; CompileAndVerify(vbCompilation, verify: Verification.Skipped, expectedOutput: expectedOutput) .VerifyIL("Derived2.Test", @" { // Code size 118 (0x76) .maxstack 2 IL_0000: ldarg.0 IL_0001: callvirt ""Function Base.M() As Object"" IL_0006: callvirt ""Function Object.ToString() As String"" IL_000b: call ""Sub System.Console.WriteLine(String)"" IL_0010: ldarg.0 IL_0011: callvirt ""Function Base.get_P() As Object"" IL_0016: callvirt ""Function Object.ToString() As String"" IL_001b: call ""Sub System.Console.WriteLine(String)"" IL_0020: ldarg.0 IL_0021: ldc.i4.0 IL_0022: callvirt ""Function Base.get_Item(Integer) As Object"" IL_0027: callvirt ""Function Object.ToString() As String"" IL_002c: call ""Sub System.Console.WriteLine(String)"" IL_0031: ldarg.1 IL_0032: callvirt ""Function Derived.M() As String"" IL_0037: call ""Sub System.Console.WriteLine(String)"" IL_003c: ldarg.1 IL_003d: callvirt ""Function Derived.get_P() As String"" IL_0042: call ""Sub System.Console.WriteLine(String)"" IL_0047: ldarg.1 IL_0048: ldc.i4.0 IL_0049: callvirt ""Function Derived.get_Item(Integer) As String"" IL_004e: call ""Sub System.Console.WriteLine(String)"" IL_0053: ldarg.2 IL_0054: callvirt ""Function Derived2.M() As String"" IL_0059: call ""Sub System.Console.WriteLine(String)"" IL_005e: ldarg.2 IL_005f: callvirt ""Function Derived2.get_P() As String"" IL_0064: call ""Sub System.Console.WriteLine(String)"" IL_0069: ldarg.2 IL_006a: ldc.i4.0 IL_006b: callvirt ""Function Derived2.get_Item(Integer) As String"" IL_0070: call ""Sub System.Console.WriteLine(String)"" IL_0075: ret } "); } [ConditionalFact(typeof(CovariantReturnRuntimeOnly))] public void CheckPreserveBaseOverride_01() { var s0 = @" public class Base { public virtual object M() => ""Base.M""; } "; var ref0 = CreateCovariantCompilation( s0, assemblyName: "ref0").VerifyEmitDiagnostics().EmitToImageReference(); var s1a = @" public class Mid : Base { } "; var ref1a = CreateCovariantCompilation( s1a, references: new[] { ref0 }, assemblyName: "ref1").VerifyEmitDiagnostics().EmitToImageReference(); var s1b = @" public class Mid : Base { public override string M() => ""Mid.M""; } "; var ref1b = CreateCovariantCompilation( s1b, references: new[] { ref0 }, assemblyName: "ref1").VerifyEmitDiagnostics().EmitToImageReference(); var s2 = @" public class Derived : Mid { public override string M() => ""Derived.M""; } "; var ref2 = CreateCovariantCompilation( s2, references: new[] { ref0, ref1a }, assemblyName: "ref2").VerifyEmitDiagnostics().EmitToImageReference(); var program = @" using System; public class Program { static void Main() { Derived d = new Derived(); Mid m = d; Base b = m; Console.WriteLine(b.M().ToString()); Console.WriteLine(m.M().ToString()); Console.WriteLine(d.M().ToString()); } } "; var compilation = CreateCovariantCompilation(program, options: TestOptions.DebugExe, references: new[] { ref0, ref1b, ref2 }); compilation.VerifyDiagnostics(); var expectedOutput = @"Derived.M Derived.M Derived.M"; CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: Verification.Skipped); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Emit { public class CovariantReturnTests : EmitMetadataTestBase { private static MetadataReference _corelibraryWithCovariantReturnSupport; private static MetadataReference CorelibraryWithCovariantReturnSupport { get { if (_corelibraryWithCovariantReturnSupport == null) { _corelibraryWithCovariantReturnSupport = MakeCorelibraryWithCovariantReturnSupport(); } return _corelibraryWithCovariantReturnSupport; } } private static MetadataReference MakeCorelibraryWithCovariantReturnSupport() { const string corLibraryCore = @" namespace System { public class Array { public static T[] Empty<T>() => throw null; } public class Console { public static void WriteLine(string message) => throw null; } public class Attribute { } [Flags] public enum AttributeTargets { Assembly = 0x1, Module = 0x2, Class = 0x4, Struct = 0x8, Enum = 0x10, Constructor = 0x20, Method = 0x40, Property = 0x80, Field = 0x100, Event = 0x200, Interface = 0x400, Parameter = 0x800, Delegate = 0x1000, ReturnValue = 0x2000, GenericParameter = 0x4000, All = 0x7FFF } [AttributeUsage(AttributeTargets.Class, Inherited = true)] public sealed class AttributeUsageAttribute : Attribute { public AttributeUsageAttribute(AttributeTargets validOn) { } public bool AllowMultiple { get => throw null; set { } } public bool Inherited { get => throw null; set { } } public AttributeTargets ValidOn => throw null; } public struct Boolean { } public struct Byte { } public class Delegate { public static Delegate CreateDelegate(Type type, object firstArgument, Reflection.MethodInfo method) => null; } public abstract class Enum : IComparable { } public class Exception { public Exception(string message) => throw null; } public class FlagsAttribute : Attribute { } public delegate T Func<out T>(); public delegate U Func<in T, out U>(T arg); public interface IComparable { } public interface IDisposable { void Dispose(); } public struct Int16 { } public struct Int32 { } public struct IntPtr { } public class MulticastDelegate : Delegate { } public struct Nullable<T> { } public class Object { public virtual string ToString() => throw null; public virtual int GetHashCode() => throw null; public virtual bool Equals(object other) => throw null; } public sealed class ParamArrayAttribute : Attribute { } public struct RuntimeMethodHandle { } public struct RuntimeTypeHandle { } public class String : IComparable { public static String Empty = null; public override string ToString() => throw null; public static bool operator ==(string a, string b) => throw null; public static bool operator !=(string a, string b) => throw null; public override bool Equals(object other) => throw null; public override int GetHashCode() => throw null; } public class Type { public Reflection.FieldInfo GetField(string name) => null; public static Type GetType(string name) => null; public static Type GetTypeFromHandle(RuntimeTypeHandle handle) => null; } public class ValueType { } public struct Void { } namespace Collections { public interface IEnumerable { IEnumerator GetEnumerator(); } public interface IEnumerator { object Current { get; } bool MoveNext(); void Reset(); } } namespace Collections.Generic { public interface IEnumerable<out T> : IEnumerable { new IEnumerator<T> GetEnumerator(); } public interface IEnumerator<out T> : IEnumerator, IDisposable { new T Current { get; } } } namespace Linq.Expressions { public class Expression { public static ParameterExpression Parameter(Type type) => throw null; public static ParameterExpression Parameter(Type type, string name) => throw null; public static MethodCallExpression Call(Expression instance, Reflection.MethodInfo method, params Expression[] arguments) => throw null; public static Expression<TDelegate> Lambda<TDelegate>(Expression body, params ParameterExpression[] parameters) => throw null; public static MemberExpression Property(Expression expression, Reflection.MethodInfo propertyAccessor) => throw null; public static ConstantExpression Constant(object value, Type type) => throw null; public static UnaryExpression Convert(Expression expression, Type type) => throw null; } public class ParameterExpression : Expression { } public class MethodCallExpression : Expression { } public abstract class LambdaExpression : Expression { } public class Expression<T> : LambdaExpression { } public class MemberExpression : Expression { } public class ConstantExpression : Expression { } public sealed class UnaryExpression : Expression { } } namespace Reflection { public class AssemblyVersionAttribute : Attribute { public AssemblyVersionAttribute(string version) { } } public class DefaultMemberAttribute : Attribute { public DefaultMemberAttribute(string name) { } } public abstract class MemberInfo { } public abstract class MethodBase : MemberInfo { public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle) => throw null; } public abstract class MethodInfo : MethodBase { public virtual Delegate CreateDelegate(Type delegateType, object target) => throw null; } public abstract class FieldInfo : MemberInfo { public abstract object GetValue(object obj); } } namespace Runtime.CompilerServices { public static class RuntimeHelpers { public static object GetObjectValue(object obj) => null; } } } "; const string corlibWithCovariantSupport = corLibraryCore + @" namespace System.Runtime.CompilerServices { public static class RuntimeFeature { public const string CovariantReturnsOfClasses = nameof(CovariantReturnsOfClasses); public const string DefaultImplementationsOfInterfaces = nameof(DefaultImplementationsOfInterfaces); } public sealed class PreserveBaseOverridesAttribute : Attribute { } } "; var compilation = CreateEmptyCompilation(new string[] { corlibWithCovariantSupport, @"[assembly: System.Reflection.AssemblyVersion(""4.0.0.0"")]" }, assemblyName: "mscorlib"); compilation.VerifyDiagnostics(); return compilation.EmitToImageReference(options: new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "v5.1")); } private static CSharpCompilation CreateCovariantCompilation( string source, CSharpCompilationOptions options = null, IEnumerable<MetadataReference> references = null, string assemblyName = null) { Assert.NotNull(CorelibraryWithCovariantReturnSupport); references = (references == null) ? new[] { CorelibraryWithCovariantReturnSupport } : references.ToArray().Prepend(CorelibraryWithCovariantReturnSupport); return CreateEmptyCompilation( source, options: options, parseOptions: TestOptions.WithCovariantReturns, references: references, assemblyName: assemblyName); } [ConditionalFact(typeof(CovariantReturnRuntimeOnly))] public void SimpleCovariantReturnEndToEndTest() { var source = @" using System; class Base { public virtual object M() => ""Base.M""; } class Derived : Base { public override string M() => ""Derived.M""; } class Program { static void Main() { Derived d = new Derived(); Base b = d; string s = d.M(); object o = b.M(); Console.WriteLine(s.ToString()); Console.WriteLine(o.ToString()); } } "; var compilation = CreateCovariantCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @"Derived.M Derived.M"; CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: Verification.Skipped); } [ConditionalFact(typeof(CovariantReturnRuntimeOnly))] public void CovariantRuntimeHasRequiredMembers() { var source = @" using System; class Base { public virtual object M() => ""Base.M""; } class Derived : Base { public override string M() => ""Derived.M""; } class Program { static void Main() { var value = (string)Type.GetType(""System.Runtime.CompilerServices.RuntimeFeature"").GetField(""CovariantReturnsOfClasses"").GetValue(null); if (value != ""CovariantReturnsOfClasses"") throw new Exception(value.ToString()); var attr = Type.GetType(""System.Runtime.CompilerServices.PreserveBaseOverridesAttribute""); if (attr == null) throw new Exception(""missing System.Runtime.CompilerServices.PreserveBaseOverridesAttribute""); } } "; var compilation = CreateCovariantCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @""; CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: Verification.Skipped); } [Fact] public void VbOverrideOfCSharpCovariantReturn_01() { var cSharpSource = @" public class Base { public virtual object M() => null; public virtual object P => null; public virtual object this[int i] => null; } public abstract class Derived : Base { public override string M() => null; public override string P => null; public override string this[int i] => null; } "; var csharpCompilation = CreateCovariantCompilation(cSharpSource).VerifyDiagnostics(); var csharpReference = csharpCompilation.EmitToImageReference(); var vbSource = @" Public Class Derived2 : Inherits Derived Public Overrides Function M() As Object Return Nothing End Function Public Overrides ReadOnly Property P As Object Get Return Nothing End Get End Property Public Overrides Default ReadOnly Property Item(i As Integer) As Object Get Return Nothing End Get End Property End Class "; var ERR_InvalidOverrideDueToReturn2 = typeof(VisualBasic.VisualBasicCompilation).Assembly.GetType("Microsoft.CodeAnalysis.VisualBasic.ERRID").GetField("ERR_InvalidOverrideDueToReturn2").GetValue(null); CreateVisualBasicCompilation(vbSource, referencedAssemblies: new[] { CorelibraryWithCovariantReturnSupport, csharpReference }) .VerifyDiagnostics( //BC30437: 'Public Overrides Function M() As Object' cannot override 'Public Overridable Overloads Function M() As String' because they differ by their return types. //Public Overrides Function M() As Object // ~ Diagnostic(ERR_InvalidOverrideDueToReturn2, "M").WithArguments("Public Overrides Function M() As Object", "Public Overridable Overloads Function M() As String").WithLocation(3, 31), //BC30437: 'Public Overrides ReadOnly Property P As Object' cannot override 'Public Overridable Overloads ReadOnly Property P As String' because they differ by their return types. //Public Overrides ReadOnly Property P As Object // ~ Diagnostic(ERR_InvalidOverrideDueToReturn2, "P").WithArguments("Public Overrides ReadOnly Property P As Object", "Public Overridable Overloads ReadOnly Property P As String").WithLocation(6, 40), //BC30437: 'Public Overrides ReadOnly Default Property Item(i As Integer) As Object' cannot override 'Public Overridable Overloads ReadOnly Default Property Item(i As Integer) As String' because they differ by their return types. //Public Overrides Default ReadOnly Property Item(i As Integer) As Object // ~~~~ Diagnostic(ERR_InvalidOverrideDueToReturn2, "Item").WithArguments("Public Overrides ReadOnly Default Property Item(i As Integer) As Object", "Public Overridable Overloads ReadOnly Default Property Item(i As Integer) As String").WithLocation(11, 48) ); } [Fact] public void VbOverrideOfCSharpCovariantReturn_02() { var cSharpSource = @" public class Base { public virtual object M() => ""Base.M""; public virtual object P => ""Base.P""; public virtual object this[int i] => ""Base[]""; } public abstract class Derived : Base { public override string M() => ""Derived.M""; public override string P => ""Derived.P""; public override string this[int i] => ""Derived[]""; } "; var csharpCompilation = CreateCovariantCompilation(cSharpSource).VerifyDiagnostics(); var csharpReference = csharpCompilation.EmitToImageReference(); var vbSource = @" Imports System Public Class Derived2 : Inherits Derived Public Overrides Function M() As String Return ""Derived2.M"" End Function Public Overrides ReadOnly Property P As String Get Return ""Derived2.P"" End Get End Property Public Overrides Default ReadOnly Property Item(i As Integer) As String Get Return ""Derived2[]"" End Get End Property Public Shared Sub Test(b As Base, d As Derived, d2 As Derived2) Console.WriteLine(b.M().ToString()) Console.WriteLine(b.P.ToString()) Console.WriteLine(b(0).ToString()) Console.WriteLine(d.M()) Console.WriteLine(d.P) Console.WriteLine(d(0)) Console.WriteLine(d2.M()) Console.WriteLine(d2.P) Console.WriteLine(d2(0)) End Sub public Shared Sub Main() Dim d2 = new Derived2 Test(d2, d2, d2) End Sub End Class "; var compilationOptions = new VisualBasic.VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptimizationLevel(OptimizationLevel.Release); var vbCompilation = CreateVisualBasicCompilation(vbSource, compilationOptions: compilationOptions, referencedAssemblies: new[] { CorelibraryWithCovariantReturnSupport, csharpReference }) .VerifyDiagnostics( ); var expectedOutput = !ExecutionConditionUtil.RuntimeSupportsCovariantReturnsOfClasses ? null : @" Derived2.M Derived2.P Derived2[] Derived2.M Derived2.P Derived2[] Derived2.M Derived2.P Derived2[]"; CompileAndVerify(vbCompilation, verify: Verification.Skipped, expectedOutput: expectedOutput) .VerifyIL("Derived2.Test", @" { // Code size 118 (0x76) .maxstack 2 IL_0000: ldarg.0 IL_0001: callvirt ""Function Base.M() As Object"" IL_0006: callvirt ""Function Object.ToString() As String"" IL_000b: call ""Sub System.Console.WriteLine(String)"" IL_0010: ldarg.0 IL_0011: callvirt ""Function Base.get_P() As Object"" IL_0016: callvirt ""Function Object.ToString() As String"" IL_001b: call ""Sub System.Console.WriteLine(String)"" IL_0020: ldarg.0 IL_0021: ldc.i4.0 IL_0022: callvirt ""Function Base.get_Item(Integer) As Object"" IL_0027: callvirt ""Function Object.ToString() As String"" IL_002c: call ""Sub System.Console.WriteLine(String)"" IL_0031: ldarg.1 IL_0032: callvirt ""Function Derived.M() As String"" IL_0037: call ""Sub System.Console.WriteLine(String)"" IL_003c: ldarg.1 IL_003d: callvirt ""Function Derived.get_P() As String"" IL_0042: call ""Sub System.Console.WriteLine(String)"" IL_0047: ldarg.1 IL_0048: ldc.i4.0 IL_0049: callvirt ""Function Derived.get_Item(Integer) As String"" IL_004e: call ""Sub System.Console.WriteLine(String)"" IL_0053: ldarg.2 IL_0054: callvirt ""Function Derived2.M() As String"" IL_0059: call ""Sub System.Console.WriteLine(String)"" IL_005e: ldarg.2 IL_005f: callvirt ""Function Derived2.get_P() As String"" IL_0064: call ""Sub System.Console.WriteLine(String)"" IL_0069: ldarg.2 IL_006a: ldc.i4.0 IL_006b: callvirt ""Function Derived2.get_Item(Integer) As String"" IL_0070: call ""Sub System.Console.WriteLine(String)"" IL_0075: ret } "); } [ConditionalFact(typeof(CovariantReturnRuntimeOnly))] public void CheckPreserveBaseOverride_01() { var s0 = @" public class Base { public virtual object M() => ""Base.M""; } "; var ref0 = CreateCovariantCompilation( s0, assemblyName: "ref0").VerifyEmitDiagnostics().EmitToImageReference(); var s1a = @" public class Mid : Base { } "; var ref1a = CreateCovariantCompilation( s1a, references: new[] { ref0 }, assemblyName: "ref1").VerifyEmitDiagnostics().EmitToImageReference(); var s1b = @" public class Mid : Base { public override string M() => ""Mid.M""; } "; var ref1b = CreateCovariantCompilation( s1b, references: new[] { ref0 }, assemblyName: "ref1").VerifyEmitDiagnostics().EmitToImageReference(); var s2 = @" public class Derived : Mid { public override string M() => ""Derived.M""; } "; var ref2 = CreateCovariantCompilation( s2, references: new[] { ref0, ref1a }, assemblyName: "ref2").VerifyEmitDiagnostics().EmitToImageReference(); var program = @" using System; public class Program { static void Main() { Derived d = new Derived(); Mid m = d; Base b = m; Console.WriteLine(b.M().ToString()); Console.WriteLine(m.M().ToString()); Console.WriteLine(d.M().ToString()); } } "; var compilation = CreateCovariantCompilation(program, options: TestOptions.DebugExe, references: new[] { ref0, ref1b, ref2 }); compilation.VerifyDiagnostics(); var expectedOutput = @"Derived.M Derived.M Derived.M"; CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: Verification.Skipped); } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Features/CSharp/Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue { internal sealed class CSharpEditAndContinueAnalyzer : AbstractEditAndContinueAnalyzer { [ExportLanguageServiceFactory(typeof(IEditAndContinueAnalyzer), LanguageNames.CSharp), Shared] internal sealed class Factory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } public ILanguageService CreateLanguageService(HostLanguageServices languageServices) { return new CSharpEditAndContinueAnalyzer(testFaultInjector: null); } } // Public for testing purposes public CSharpEditAndContinueAnalyzer(Action<SyntaxNode>? testFaultInjector = null) : base(testFaultInjector) { } #region Syntax Analysis private enum BlockPart { OpenBrace = DefaultStatementPart, CloseBrace = 1, } private enum ForEachPart { ForEach = DefaultStatementPart, VariableDeclaration = 1, In = 2, Expression = 3, } private enum SwitchExpressionPart { WholeExpression = DefaultStatementPart, // An active statement that covers IL generated for the decision tree: // <governing-expression> [|switch { <arm>, ..., <arm> }|] // This active statement is never a leaf active statement (does not correspond to a breakpoint span). SwitchBody = 1, } /// <returns> /// <see cref="BaseMethodDeclarationSyntax"/> for methods, operators, constructors, destructors and accessors. /// <see cref="VariableDeclaratorSyntax"/> for field initializers. /// <see cref="PropertyDeclarationSyntax"/> for property initializers and expression bodies. /// <see cref="IndexerDeclarationSyntax"/> for indexer expression bodies. /// <see cref="ArrowExpressionClauseSyntax"/> for getter of an expression-bodied property/indexer. /// </returns> internal override bool TryFindMemberDeclaration(SyntaxNode? root, SyntaxNode node, out OneOrMany<SyntaxNode> declarations) { var current = node; while (current != null && current != root) { switch (current.Kind()) { case SyntaxKind.MethodDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: declarations = new(current); return true; case SyntaxKind.PropertyDeclaration: // int P { get; } = [|initializer|]; RoslynDebug.Assert(((PropertyDeclarationSyntax)current).Initializer != null); declarations = new(current); return true; case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: // Active statements encompassing modifiers or type correspond to the first initialized field. // [|public static int F = 1|], G = 2; declarations = new(((BaseFieldDeclarationSyntax)current).Declaration.Variables.First()); return true; case SyntaxKind.VariableDeclarator: // public static int F = 1, [|G = 2|]; RoslynDebug.Assert(current.Parent.IsKind(SyntaxKind.VariableDeclaration)); switch (current.Parent.Parent!.Kind()) { case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: declarations = new(current); return true; } current = current.Parent; break; case SyntaxKind.ArrowExpressionClause: // represents getter symbol declaration node of a property/indexer with expression body if (current.Parent.IsKind(SyntaxKind.PropertyDeclaration, SyntaxKind.IndexerDeclaration)) { declarations = new(current); return true; } break; } current = current.Parent; } declarations = default; return false; } /// <returns> /// Given a node representing a declaration or a top-level match node returns: /// - <see cref="BlockSyntax"/> for method-like member declarations with block bodies (methods, operators, constructors, destructors, accessors). /// - <see cref="ExpressionSyntax"/> for variable declarators of fields, properties with an initializer expression, or /// for method-like member declarations with expression bodies (methods, properties, indexers, operators) /// - <see cref="CompilationUnitSyntax"/> for top level statements /// /// A null reference otherwise. /// </returns> internal override SyntaxNode? TryGetDeclarationBody(SyntaxNode node) { if (node.IsKind(SyntaxKind.VariableDeclarator, out VariableDeclaratorSyntax? variableDeclarator)) { return variableDeclarator.Initializer?.Value; } if (node is CompilationUnitSyntax unit && unit.ContainsTopLevelStatements()) { // For top level statements, where there is no syntax node to represent the entire body of the synthesized // main method we just use the compilation unit itself return node; } return SyntaxUtilities.TryGetMethodDeclarationBody(node); } internal override bool IsDeclarationWithSharedBody(SyntaxNode declaration) => false; protected override ImmutableArray<ISymbol> GetCapturedVariables(SemanticModel model, SyntaxNode memberBody) { if (memberBody is CompilationUnitSyntax unit && unit.ContainsTopLevelStatements()) { return model.AnalyzeDataFlow(((GlobalStatementSyntax)unit.Members[0]).Statement, unit.Members.OfType<GlobalStatementSyntax>().Last().Statement)!.Captured; } Debug.Assert(memberBody.IsKind(SyntaxKind.Block) || memberBody is ExpressionSyntax); return model.AnalyzeDataFlow(memberBody).Captured; } protected override bool AreHandledEventsEqual(IMethodSymbol oldMethod, IMethodSymbol newMethod) => true; internal override bool HasParameterClosureScope(ISymbol member) { // in instance constructor parameters are lifted to a closure different from method body return (member as IMethodSymbol)?.MethodKind == MethodKind.Constructor; } protected override IEnumerable<SyntaxNode> GetVariableUseSites(IEnumerable<SyntaxNode> roots, ISymbol localOrParameter, SemanticModel model, CancellationToken cancellationToken) { Debug.Assert(localOrParameter is IParameterSymbol || localOrParameter is ILocalSymbol || localOrParameter is IRangeVariableSymbol); // not supported (it's non trivial to find all places where "this" is used): Debug.Assert(!localOrParameter.IsThisParameter()); return from root in roots from node in root.DescendantNodesAndSelf() where node.IsKind(SyntaxKind.IdentifierName) let nameSyntax = (IdentifierNameSyntax)node where (string?)nameSyntax.Identifier.Value == localOrParameter.Name && (model.GetSymbolInfo(nameSyntax, cancellationToken).Symbol?.Equals(localOrParameter) ?? false) select node; } /// <returns> /// If <paramref name="node"/> is a method, accessor, operator, destructor, or constructor without an initializer, /// tokens of its block body, or tokens of the expression body. /// /// If <paramref name="node"/> is an indexer declaration the tokens of its expression body. /// /// If <paramref name="node"/> is a property declaration the tokens of its expression body or initializer. /// /// If <paramref name="node"/> is a constructor with an initializer, /// tokens of the initializer concatenated with tokens of the constructor body. /// /// If <paramref name="node"/> is a variable declarator of a field with an initializer, /// subset of the tokens of the field declaration depending on which variable declarator it is. /// /// Null reference otherwise. /// </returns> internal override IEnumerable<SyntaxToken>? TryGetActiveTokens(SyntaxNode node) { if (node.IsKind(SyntaxKind.VariableDeclarator)) { // TODO: The logic is similar to BreakpointSpans.TryCreateSpanForVariableDeclaration. Can we abstract it? var declarator = node; var fieldDeclaration = (BaseFieldDeclarationSyntax)declarator.Parent!.Parent!; var variableDeclaration = fieldDeclaration.Declaration; if (fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword)) { return null; } if (variableDeclaration.Variables.Count == 1) { if (variableDeclaration.Variables[0].Initializer == null) { return null; } return fieldDeclaration.Modifiers.Concat(variableDeclaration.DescendantTokens()).Concat(fieldDeclaration.SemicolonToken); } if (declarator == variableDeclaration.Variables[0]) { return fieldDeclaration.Modifiers.Concat(variableDeclaration.Type.DescendantTokens()).Concat(node.DescendantTokens()); } return declarator.DescendantTokens(); } if (node is PropertyDeclarationSyntax { ExpressionBody: var propertyExpressionBody and not null }) { return propertyExpressionBody.Expression.DescendantTokens(); } if (node is IndexerDeclarationSyntax { ExpressionBody: var indexerExpressionBody and not null }) { return indexerExpressionBody.Expression.DescendantTokens(); } var bodyTokens = SyntaxUtilities.TryGetMethodDeclarationBody(node)?.DescendantTokens(); if (node.IsKind(SyntaxKind.ConstructorDeclaration, out ConstructorDeclarationSyntax? ctor)) { if (ctor.Initializer != null) { bodyTokens = ctor.Initializer.DescendantTokens().Concat(bodyTokens ?? Enumerable.Empty<SyntaxToken>()); } } return bodyTokens; } internal override (TextSpan envelope, TextSpan hole) GetActiveSpanEnvelope(SyntaxNode declaration) => (BreakpointSpans.GetEnvelope(declaration), default); protected override SyntaxNode GetEncompassingAncestorImpl(SyntaxNode bodyOrMatchRoot) { // Constructor may contain active nodes outside of its body (constructor initializer), // but within the body of the member declaration (the parent). if (bodyOrMatchRoot.Parent.IsKind(SyntaxKind.ConstructorDeclaration)) { return bodyOrMatchRoot.Parent; } // Field initializer match root -- an active statement may include the modifiers // and type specification of the field declaration. if (bodyOrMatchRoot.IsKind(SyntaxKind.EqualsValueClause) && bodyOrMatchRoot.Parent.IsKind(SyntaxKind.VariableDeclarator) && bodyOrMatchRoot.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration)) { return bodyOrMatchRoot.Parent.Parent; } // Field initializer body -- an active statement may include the modifiers // and type specification of the field declaration. if (bodyOrMatchRoot.Parent.IsKind(SyntaxKind.EqualsValueClause) && bodyOrMatchRoot.Parent.Parent.IsKind(SyntaxKind.VariableDeclarator) && bodyOrMatchRoot.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration)) { return bodyOrMatchRoot.Parent.Parent.Parent; } // otherwise all active statements are covered by the body/match root itself: return bodyOrMatchRoot; } protected override SyntaxNode FindStatementAndPartner(SyntaxNode declarationBody, TextSpan span, SyntaxNode? partnerDeclarationBody, out SyntaxNode? partner, out int statementPart) { var position = span.Start; SyntaxUtilities.AssertIsBody(declarationBody, allowLambda: false); if (position < declarationBody.SpanStart) { // Only constructors and the field initializers may have an [|active statement|] starting outside of the <<body>>. // Constructor: [|public C()|] <<{ }>> // Constructor initializer: public C() : [|base(expr)|] <<{ }>> // Constructor initializer with lambda: public C() : base(() => { [|...|] }) <<{ }>> // Field initializers: [|public int a = <<expr>>|], [|b = <<expr>>|]; // No need to special case property initializers here, the active statement always spans the initializer expression. if (declarationBody.Parent.IsKind(SyntaxKind.ConstructorDeclaration)) { var constructor = (ConstructorDeclarationSyntax)declarationBody.Parent; var partnerConstructor = (ConstructorDeclarationSyntax?)partnerDeclarationBody?.Parent; if (constructor.Initializer == null || position < constructor.Initializer.ColonToken.SpanStart) { statementPart = DefaultStatementPart; partner = partnerConstructor; return constructor; } declarationBody = constructor.Initializer; partnerDeclarationBody = partnerConstructor?.Initializer; } } if (!declarationBody.FullSpan.Contains(position)) { // invalid position, let's find a labeled node that encompasses the body: position = declarationBody.SpanStart; } SyntaxNode node; if (partnerDeclarationBody != null) { SyntaxUtilities.FindLeafNodeAndPartner(declarationBody, position, partnerDeclarationBody, out node, out partner); } else { node = declarationBody.FindToken(position).Parent!; partner = null; } while (true) { var isBody = node == declarationBody || LambdaUtilities.IsLambdaBodyStatementOrExpression(node); if (isBody || SyntaxComparer.Statement.HasLabel(node)) { switch (node.Kind()) { case SyntaxKind.Block: statementPart = (int)GetStatementPart((BlockSyntax)node, position); return node; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: Debug.Assert(!isBody); statementPart = (int)GetStatementPart((CommonForEachStatementSyntax)node, position); return node; case SyntaxKind.DoStatement: // The active statement of DoStatement node is the while condition, // which is lexically not the closest breakpoint span (the body is). // do { ... } [|while (condition);|] Debug.Assert(position == ((DoStatementSyntax)node).WhileKeyword.SpanStart); Debug.Assert(!isBody); goto default; case SyntaxKind.PropertyDeclaration: // The active span corresponding to a property declaration is the span corresponding to its initializer (if any), // not the span corresponding to the accessor. // int P { [|get;|] } = [|<initializer>|]; Debug.Assert(position == ((PropertyDeclarationSyntax)node).Initializer!.SpanStart); goto default; case SyntaxKind.VariableDeclaration: // VariableDeclaration ::= TypeSyntax CommaSeparatedList(VariableDeclarator) // // The compiler places sequence points after each local variable initialization. // The TypeSyntax is considered to be part of the first sequence span. Debug.Assert(!isBody); node = ((VariableDeclarationSyntax)node).Variables.First(); if (partner != null) { partner = ((VariableDeclarationSyntax)partner).Variables.First(); } statementPart = DefaultStatementPart; return node; case SyntaxKind.SwitchExpression: // An active statement that covers IL generated for the decision tree: // <governing-expression> [|switch { <arm>, ..., <arm> }|] // This active statement is never a leaf active statement (does not correspond to a breakpoint span). var switchExpression = (SwitchExpressionSyntax)node; if (position == switchExpression.SwitchKeyword.SpanStart) { Debug.Assert(span.End == switchExpression.CloseBraceToken.Span.End); statementPart = (int)SwitchExpressionPart.SwitchBody; return node; } // The switch expression itself can be (a part of) an active statement associated with the containing node // For example, when it is used as a switch arm expression like so: // <expr> switch { <pattern> [|when <expr> switch { ... }|] ... } Debug.Assert(position == switchExpression.Span.Start); if (isBody) { goto default; } // ascend to parent node: break; case SyntaxKind.SwitchExpressionArm: // An active statement may occur in the when clause and in the arm expression: // <constant-pattern> [|when <condition>|] => [|<expression>|] // The former is covered by when-clause node - it's a labeled node. // The latter isn't enclosed in a distinct labeled syntax node and thus needs to be covered // by the arm node itself. Debug.Assert(position == ((SwitchExpressionArmSyntax)node).Expression.SpanStart); Debug.Assert(!isBody); goto default; default: statementPart = DefaultStatementPart; return node; } } node = node.Parent!; if (partner != null) { partner = partner.Parent; } } } private static BlockPart GetStatementPart(BlockSyntax node, int position) => position < node.OpenBraceToken.Span.End ? BlockPart.OpenBrace : BlockPart.CloseBrace; private static TextSpan GetActiveSpan(BlockSyntax node, BlockPart part) => part switch { BlockPart.OpenBrace => node.OpenBraceToken.Span, BlockPart.CloseBrace => node.CloseBraceToken.Span, _ => throw ExceptionUtilities.UnexpectedValue(part), }; private static ForEachPart GetStatementPart(CommonForEachStatementSyntax node, int position) => position < node.OpenParenToken.SpanStart ? ForEachPart.ForEach : position < node.InKeyword.SpanStart ? ForEachPart.VariableDeclaration : position < node.Expression.SpanStart ? ForEachPart.In : ForEachPart.Expression; private static TextSpan GetActiveSpan(ForEachStatementSyntax node, ForEachPart part) => part switch { ForEachPart.ForEach => node.ForEachKeyword.Span, ForEachPart.VariableDeclaration => TextSpan.FromBounds(node.Type.SpanStart, node.Identifier.Span.End), ForEachPart.In => node.InKeyword.Span, ForEachPart.Expression => node.Expression.Span, _ => throw ExceptionUtilities.UnexpectedValue(part), }; private static TextSpan GetActiveSpan(ForEachVariableStatementSyntax node, ForEachPart part) => part switch { ForEachPart.ForEach => node.ForEachKeyword.Span, ForEachPart.VariableDeclaration => TextSpan.FromBounds(node.Variable.SpanStart, node.Variable.Span.End), ForEachPart.In => node.InKeyword.Span, ForEachPart.Expression => node.Expression.Span, _ => throw ExceptionUtilities.UnexpectedValue(part), }; private static TextSpan GetActiveSpan(SwitchExpressionSyntax node, SwitchExpressionPart part) => part switch { SwitchExpressionPart.WholeExpression => node.Span, SwitchExpressionPart.SwitchBody => TextSpan.FromBounds(node.SwitchKeyword.SpanStart, node.CloseBraceToken.Span.End), _ => throw ExceptionUtilities.UnexpectedValue(part), }; protected override bool AreEquivalent(SyntaxNode left, SyntaxNode right) => SyntaxFactory.AreEquivalent(left, right); private static bool AreEquivalentIgnoringLambdaBodies(SyntaxNode left, SyntaxNode right) { // usual case: if (SyntaxFactory.AreEquivalent(left, right)) { return true; } return LambdaUtilities.AreEquivalentIgnoringLambdaBodies(left, right); } internal override SyntaxNode FindDeclarationBodyPartner(SyntaxNode leftRoot, SyntaxNode rightRoot, SyntaxNode leftNode) => SyntaxUtilities.FindPartner(leftRoot, rightRoot, leftNode); internal override bool IsClosureScope(SyntaxNode node) => LambdaUtilities.IsClosureScope(node); protected override SyntaxNode? FindEnclosingLambdaBody(SyntaxNode? container, SyntaxNode node) { var root = GetEncompassingAncestor(container); var current = node; while (current != root && current != null) { if (LambdaUtilities.IsLambdaBodyStatementOrExpression(current, out var body)) { return body; } current = current.Parent; } return null; } protected override IEnumerable<SyntaxNode> GetLambdaBodyExpressionsAndStatements(SyntaxNode lambdaBody) => SpecializedCollections.SingletonEnumerable(lambdaBody); protected override SyntaxNode? TryGetPartnerLambdaBody(SyntaxNode oldBody, SyntaxNode newLambda) => LambdaUtilities.TryGetCorrespondingLambdaBody(oldBody, newLambda); protected override Match<SyntaxNode> ComputeTopLevelMatch(SyntaxNode oldCompilationUnit, SyntaxNode newCompilationUnit) => SyntaxComparer.TopLevel.ComputeMatch(oldCompilationUnit, newCompilationUnit); protected override Match<SyntaxNode> ComputeTopLevelDeclarationMatch(SyntaxNode oldDeclaration, SyntaxNode newDeclaration) { Contract.ThrowIfNull(oldDeclaration.Parent); Contract.ThrowIfNull(newDeclaration.Parent); var comparer = new SyntaxComparer(oldDeclaration.Parent, newDeclaration.Parent, new[] { oldDeclaration }, new[] { newDeclaration }, compareStatementSyntax: false); return comparer.ComputeMatch(oldDeclaration.Parent, newDeclaration.Parent); } protected override Match<SyntaxNode> ComputeBodyMatch(SyntaxNode oldBody, SyntaxNode newBody, IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>>? knownMatches) { SyntaxUtilities.AssertIsBody(oldBody, allowLambda: true); SyntaxUtilities.AssertIsBody(newBody, allowLambda: true); if (oldBody is ExpressionSyntax || newBody is ExpressionSyntax || (oldBody.Parent.IsKind(SyntaxKind.LocalFunctionStatement) && newBody.Parent.IsKind(SyntaxKind.LocalFunctionStatement))) { Debug.Assert(oldBody is ExpressionSyntax || oldBody is BlockSyntax); Debug.Assert(newBody is ExpressionSyntax || newBody is BlockSyntax); // The matching algorithm requires the roots to match each other. // Lambda bodies, field/property initializers, and method/property/indexer/operator expression-bodies may also be lambda expressions. // Say we have oldBody 'x => x' and newBody 'F(x => x + 1)', then // the algorithm would match 'x => x' to 'F(x => x + 1)' instead of // matching 'x => x' to 'x => x + 1'. // We use the parent node as a root: // - for field/property initializers the root is EqualsValueClause. // - for member expression-bodies the root is ArrowExpressionClauseSyntax. // - for block bodies the root is a method/operator/accessor declaration (only happens when matching expression body with a block body) // - for lambdas the root is a LambdaExpression. // - for query lambdas the root is the query clause containing the lambda (e.g. where). // - for local functions the root is LocalFunctionStatement. static SyntaxNode GetMatchingRoot(SyntaxNode body) { var parent = body.Parent!; // We could apply this change across all ArrowExpressionClause consistently not just for ones with LocalFunctionStatement parents // but it would require an essential refactoring. return parent.IsKind(SyntaxKind.ArrowExpressionClause) && parent.Parent.IsKind(SyntaxKind.LocalFunctionStatement) ? parent.Parent : parent; } var oldRoot = GetMatchingRoot(oldBody); var newRoot = GetMatchingRoot(newBody); return new SyntaxComparer(oldRoot, newRoot, GetChildNodes(oldRoot, oldBody), GetChildNodes(newRoot, newBody), compareStatementSyntax: true).ComputeMatch(oldRoot, newRoot, knownMatches); } if (oldBody.Parent.IsKind(SyntaxKind.ConstructorDeclaration)) { // We need to include constructor initializer in the match, since it may contain lambdas. // Use the constructor declaration as a root. RoslynDebug.Assert(oldBody.IsKind(SyntaxKind.Block)); RoslynDebug.Assert(newBody.IsKind(SyntaxKind.Block)); RoslynDebug.Assert(newBody.Parent.IsKind(SyntaxKind.ConstructorDeclaration)); RoslynDebug.Assert(newBody.Parent is object); return SyntaxComparer.Statement.ComputeMatch(oldBody.Parent, newBody.Parent, knownMatches); } return SyntaxComparer.Statement.ComputeMatch(oldBody, newBody, knownMatches); } private static IEnumerable<SyntaxNode> GetChildNodes(SyntaxNode root, SyntaxNode body) { if (root is LocalFunctionStatementSyntax localFunc) { // local functions have multiple children we need to process for matches, but we won't automatically // descend into them, assuming they're nested, so we override the default behaviour and return // multiple children foreach (var attributeList in localFunc.AttributeLists) { yield return attributeList; } yield return localFunc.ReturnType; if (localFunc.TypeParameterList is not null) { yield return localFunc.TypeParameterList; } yield return localFunc.ParameterList; if (localFunc.Body is not null) { yield return localFunc.Body; } else if (localFunc.ExpressionBody is not null) { // Skip the ArrowExpressionClause that is ExressionBody and just return the expression itself yield return localFunc.ExpressionBody.Expression; } } else { yield return body; } } internal override void ReportDeclarationInsertDeleteRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode, ISymbol oldSymbol, ISymbol newSymbol, EditAndContinueCapabilities capabilities, CancellationToken cancellationToken) { // Global statements have a declaring syntax reference to the compilation unit itself, which we can just ignore // for the purposes of declaration rude edits if (oldNode.IsKind(SyntaxKind.CompilationUnit) || newNode.IsKind(SyntaxKind.CompilationUnit)) { return; } // Compiler generated methods of records have a declaring syntax reference to the record declaration itself // but their explicitly implemented counterparts reference the actual member. Compiler generated properties // of records reference the parameter that names them. // // Since there is no useful "old" syntax node for these members, we can't compute declaration or body edits // using the standard tree comparison code. // // Based on this, we can detect a new explicit implementation of a record member by checking if the // declaration kind has changed. If it hasn't changed, then our standard code will handle it. if (oldNode.RawKind == newNode.RawKind) { base.ReportDeclarationInsertDeleteRudeEdits(diagnostics, oldNode, newNode, oldSymbol, newSymbol, capabilities, cancellationToken); return; } // When explicitly implementing a property that is represented by a positional parameter // what looks like an edit could actually be a rude delete, or something else if (oldNode is ParameterSyntax && newNode is PropertyDeclarationSyntax property) { if (property.AccessorList!.Accessors.Count == 1) { // Explicitly implementing a property with only one accessor is a delete of the init accessor, so a rude edit. // Not implementing the get accessor would be a compile error diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ImplementRecordParameterAsReadOnly, GetDiagnosticSpan(newNode, EditKind.Delete), oldNode, new[] { property.Identifier.ToString() })); } else if (property.AccessorList.Accessors.Any(a => a.IsKind(SyntaxKind.SetAccessorDeclaration))) { // The compiler implements the properties with an init accessor so explicitly implementing // it with a set accessor is a rude accessor change edit diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ImplementRecordParameterWithSet, GetDiagnosticSpan(newNode, EditKind.Delete), oldNode, new[] { property.Identifier.ToString() })); } } else if (oldNode is RecordDeclarationSyntax && newNode is MethodDeclarationSyntax && !capabilities.HasFlag(EditAndContinueCapabilities.UpdateParameters) && !oldSymbol.GetParameters().Select(p => p.Name).SequenceEqual(newSymbol.GetParameters().Select(p => p.Name))) { // Explicitly implemented methods must have parameter names that match the compiler generated versions // exactly if the runtime doesn't support updating parameters, otherwise the debugger would show incorrect // parameter names. // We don't need to worry about parameter types, because if they were different then we wouldn't get here // as this wouldn't be the explicit implementation of a known method. // We don't need to worry about access modifiers because the symbol matching still works, and most of the // time changing access modifiers for these known methods is a compile error anyway. diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, GetDiagnosticSpan(newNode, EditKind.Update), oldNode, new[] { oldSymbol.ToDisplayString(SymbolDisplayFormats.NameFormat) })); } } protected override void ReportLocalFunctionsDeclarationRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> bodyMatch) { var bodyEditsForLambda = bodyMatch.GetTreeEdits(); var editMap = BuildEditMap(bodyEditsForLambda); foreach (var edit in bodyEditsForLambda.Edits) { if (HasParentEdit(editMap, edit)) { return; } var classifier = new EditClassifier(this, diagnostics, edit.OldNode, edit.NewNode, edit.Kind, bodyMatch); classifier.ClassifyEdit(); } } protected override bool TryMatchActiveStatement( SyntaxNode oldStatement, int statementPart, SyntaxNode oldBody, SyntaxNode newBody, [NotNullWhen(true)] out SyntaxNode? newStatement) { SyntaxUtilities.AssertIsBody(oldBody, allowLambda: true); SyntaxUtilities.AssertIsBody(newBody, allowLambda: true); switch (oldStatement.Kind()) { case SyntaxKind.ThisConstructorInitializer: case SyntaxKind.BaseConstructorInitializer: case SyntaxKind.ConstructorDeclaration: var newConstructor = (ConstructorDeclarationSyntax)(newBody.Parent.IsKind(SyntaxKind.ArrowExpressionClause) ? newBody.Parent.Parent : newBody.Parent)!; newStatement = (SyntaxNode?)newConstructor.Initializer ?? newConstructor; return true; default: // TODO: Consider mapping an expression body to an equivalent statement expression or return statement and vice versa. // It would benefit transformations of expression bodies to block bodies of lambdas, methods, operators and properties. // See https://github.com/dotnet/roslyn/issues/22696 // field initializer, lambda and query expressions: if (oldStatement == oldBody && !newBody.IsKind(SyntaxKind.Block)) { newStatement = newBody; return true; } newStatement = null; return false; } } #endregion #region Syntax and Semantic Utils protected override TextSpan GetGlobalStatementDiagnosticSpan(SyntaxNode node) { if (node is CompilationUnitSyntax unit) { // When deleting something from a compilation unit we just report diagnostics for the last global statement return unit.Members.OfType<GlobalStatementSyntax>().LastOrDefault()?.Span ?? default; } return GetDiagnosticSpan(node, EditKind.Delete); } protected override string LineDirectiveKeyword => "line"; protected override ushort LineDirectiveSyntaxKind => (ushort)SyntaxKind.LineDirectiveTrivia; protected override IEnumerable<SequenceEdit> GetSyntaxSequenceEdits(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes) => SyntaxComparer.GetSequenceEdits(oldNodes, newNodes); internal override SyntaxNode EmptyCompilationUnit => SyntaxFactory.CompilationUnit(); // there are no experimental features at this time. internal override bool ExperimentalFeaturesEnabled(SyntaxTree tree) => false; protected override bool StateMachineSuspensionPointKindEquals(SyntaxNode suspensionPoint1, SyntaxNode suspensionPoint2) => (suspensionPoint1 is CommonForEachStatementSyntax) ? suspensionPoint2 is CommonForEachStatementSyntax : suspensionPoint1.RawKind == suspensionPoint2.RawKind; protected override bool StatementLabelEquals(SyntaxNode node1, SyntaxNode node2) => SyntaxComparer.Statement.GetLabel(node1) == SyntaxComparer.Statement.GetLabel(node2); protected override bool TryGetEnclosingBreakpointSpan(SyntaxNode root, int position, out TextSpan span) => BreakpointSpans.TryGetClosestBreakpointSpan(root, position, out span); protected override bool TryGetActiveSpan(SyntaxNode node, int statementPart, int minLength, out TextSpan span) { switch (node.Kind()) { case SyntaxKind.Block: span = GetActiveSpan((BlockSyntax)node, (BlockPart)statementPart); return true; case SyntaxKind.ForEachStatement: span = GetActiveSpan((ForEachStatementSyntax)node, (ForEachPart)statementPart); return true; case SyntaxKind.ForEachVariableStatement: span = GetActiveSpan((ForEachVariableStatementSyntax)node, (ForEachPart)statementPart); return true; case SyntaxKind.DoStatement: // The active statement of DoStatement node is the while condition, // which is lexically not the closest breakpoint span (the body is). // do { ... } [|while (condition);|] Debug.Assert(statementPart == DefaultStatementPart); var doStatement = (DoStatementSyntax)node; return BreakpointSpans.TryGetClosestBreakpointSpan(node, doStatement.WhileKeyword.SpanStart, out span); case SyntaxKind.PropertyDeclaration: // The active span corresponding to a property declaration is the span corresponding to its initializer (if any), // not the span corresponding to the accessor. // int P { [|get;|] } = [|<initializer>|]; Debug.Assert(statementPart == DefaultStatementPart); var propertyDeclaration = (PropertyDeclarationSyntax)node; if (propertyDeclaration.Initializer != null && BreakpointSpans.TryGetClosestBreakpointSpan(node, propertyDeclaration.Initializer.SpanStart, out span)) { return true; } span = default; return false; case SyntaxKind.SwitchExpression: span = GetActiveSpan((SwitchExpressionSyntax)node, (SwitchExpressionPart)statementPart); return true; case SyntaxKind.SwitchExpressionArm: // An active statement may occur in the when clause and in the arm expression: // <constant-pattern> [|when <condition>|] => [|<expression>|] // The former is covered by when-clause node - it's a labeled node. // The latter isn't enclosed in a distinct labeled syntax node and thus needs to be covered // by the arm node itself. Debug.Assert(statementPart == DefaultStatementPart); span = ((SwitchExpressionArmSyntax)node).Expression.Span; return true; default: // make sure all nodes that use statement parts are handled above: Debug.Assert(statementPart == DefaultStatementPart); return BreakpointSpans.TryGetClosestBreakpointSpan(node, node.SpanStart, out span); } } protected override IEnumerable<(SyntaxNode statement, int statementPart)> EnumerateNearStatements(SyntaxNode statement) { var direction = +1; SyntaxNodeOrToken nodeOrToken = statement; var fieldOrPropertyModifiers = SyntaxUtilities.TryGetFieldOrPropertyModifiers(statement); while (true) { nodeOrToken = (direction < 0) ? nodeOrToken.GetPreviousSibling() : nodeOrToken.GetNextSibling(); if (nodeOrToken.RawKind == 0) { var parent = statement.Parent; if (parent == null) { yield break; } switch (parent.Kind()) { case SyntaxKind.Block: // The next sequence point hit after the last statement of a block is the closing brace: yield return (parent, (int)(direction > 0 ? BlockPart.CloseBrace : BlockPart.OpenBrace)); break; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: // The next sequence point hit after the body is the in keyword: // [|foreach|] ([|variable-declaration|] [|in|] [|expression|]) [|<body>|] yield return (parent, (int)ForEachPart.In); break; } if (direction > 0) { nodeOrToken = statement; direction = -1; continue; } if (fieldOrPropertyModifiers.HasValue) { // We enumerated all members and none of them has an initializer. // We don't have any better place where to place the span than the initial field. // Consider: in non-partial classes we could find a single constructor. // Otherwise, it would be confusing to select one arbitrarily. yield return (statement, -1); } nodeOrToken = statement = parent; fieldOrPropertyModifiers = SyntaxUtilities.TryGetFieldOrPropertyModifiers(statement); direction = +1; yield return (nodeOrToken.AsNode()!, DefaultStatementPart); } else { var node = nodeOrToken.AsNode(); if (node == null) { continue; } if (fieldOrPropertyModifiers.HasValue) { var nodeModifiers = SyntaxUtilities.TryGetFieldOrPropertyModifiers(node); if (!nodeModifiers.HasValue || nodeModifiers.Value.Any(SyntaxKind.StaticKeyword) != fieldOrPropertyModifiers.Value.Any(SyntaxKind.StaticKeyword)) { continue; } } switch (node.Kind()) { case SyntaxKind.Block: yield return (node, (int)(direction > 0 ? BlockPart.OpenBrace : BlockPart.CloseBrace)); break; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: yield return (node, (int)ForEachPart.ForEach); break; } yield return (node, DefaultStatementPart); } } } protected override bool AreEquivalentActiveStatements(SyntaxNode oldStatement, SyntaxNode newStatement, int statementPart) { if (oldStatement.Kind() != newStatement.Kind()) { return false; } switch (oldStatement.Kind()) { case SyntaxKind.Block: // closing brace of a using statement or a block that contains using local declarations: if (statementPart == (int)BlockPart.CloseBrace) { if (oldStatement.Parent.IsKind(SyntaxKind.UsingStatement, out UsingStatementSyntax? oldUsing)) { return newStatement.Parent.IsKind(SyntaxKind.UsingStatement, out UsingStatementSyntax? newUsing) && AreEquivalentActiveStatements(oldUsing, newUsing); } return HasEquivalentUsingDeclarations((BlockSyntax)oldStatement, (BlockSyntax)newStatement); } return true; case SyntaxKind.ConstructorDeclaration: // The call could only change if the base type of the containing class changed. return true; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: // only check the expression, edits in the body and the variable declaration are allowed: return AreEquivalentActiveStatements((CommonForEachStatementSyntax)oldStatement, (CommonForEachStatementSyntax)newStatement); case SyntaxKind.IfStatement: // only check the condition, edits in the body are allowed: return AreEquivalentActiveStatements((IfStatementSyntax)oldStatement, (IfStatementSyntax)newStatement); case SyntaxKind.WhileStatement: // only check the condition, edits in the body are allowed: return AreEquivalentActiveStatements((WhileStatementSyntax)oldStatement, (WhileStatementSyntax)newStatement); case SyntaxKind.DoStatement: // only check the condition, edits in the body are allowed: return AreEquivalentActiveStatements((DoStatementSyntax)oldStatement, (DoStatementSyntax)newStatement); case SyntaxKind.SwitchStatement: return AreEquivalentActiveStatements((SwitchStatementSyntax)oldStatement, (SwitchStatementSyntax)newStatement); case SyntaxKind.LockStatement: return AreEquivalentActiveStatements((LockStatementSyntax)oldStatement, (LockStatementSyntax)newStatement); case SyntaxKind.UsingStatement: return AreEquivalentActiveStatements((UsingStatementSyntax)oldStatement, (UsingStatementSyntax)newStatement); // fixed and for statements don't need special handling since the active statement is a variable declaration default: return AreEquivalentIgnoringLambdaBodies(oldStatement, newStatement); } } private static bool HasEquivalentUsingDeclarations(BlockSyntax oldBlock, BlockSyntax newBlock) { var oldUsingDeclarations = oldBlock.Statements.Where(s => s is LocalDeclarationStatementSyntax l && l.UsingKeyword != default); var newUsingDeclarations = newBlock.Statements.Where(s => s is LocalDeclarationStatementSyntax l && l.UsingKeyword != default); return oldUsingDeclarations.SequenceEqual(newUsingDeclarations, AreEquivalentIgnoringLambdaBodies); } private static bool AreEquivalentActiveStatements(IfStatementSyntax oldNode, IfStatementSyntax newNode) { // only check the condition, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition); } private static bool AreEquivalentActiveStatements(WhileStatementSyntax oldNode, WhileStatementSyntax newNode) { // only check the condition, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition); } private static bool AreEquivalentActiveStatements(DoStatementSyntax oldNode, DoStatementSyntax newNode) { // only check the condition, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition); } private static bool AreEquivalentActiveStatements(SwitchStatementSyntax oldNode, SwitchStatementSyntax newNode) { // only check the expression, edits in the body are allowed, unless the switch expression contains patterns: if (!AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression)) { return false; } // Check that switch statement decision tree has not changed. var hasDecitionTree = oldNode.Sections.Any(s => s.Labels.Any(l => l is CasePatternSwitchLabelSyntax)); return !hasDecitionTree || AreEquivalentSwitchStatementDecisionTrees(oldNode, newNode); } private static bool AreEquivalentActiveStatements(LockStatementSyntax oldNode, LockStatementSyntax newNode) { // only check the expression, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression); } private static bool AreEquivalentActiveStatements(FixedStatementSyntax oldNode, FixedStatementSyntax newNode) => AreEquivalentIgnoringLambdaBodies(oldNode.Declaration, newNode.Declaration); private static bool AreEquivalentActiveStatements(UsingStatementSyntax oldNode, UsingStatementSyntax newNode) { // only check the expression/declaration, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies( (SyntaxNode?)oldNode.Declaration ?? oldNode.Expression!, (SyntaxNode?)newNode.Declaration ?? newNode.Expression!); } private static bool AreEquivalentActiveStatements(CommonForEachStatementSyntax oldNode, CommonForEachStatementSyntax newNode) { if (oldNode.Kind() != newNode.Kind() || !AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression)) { return false; } switch (oldNode.Kind()) { case SyntaxKind.ForEachStatement: return AreEquivalentIgnoringLambdaBodies(((ForEachStatementSyntax)oldNode).Type, ((ForEachStatementSyntax)newNode).Type); case SyntaxKind.ForEachVariableStatement: return AreEquivalentIgnoringLambdaBodies(((ForEachVariableStatementSyntax)oldNode).Variable, ((ForEachVariableStatementSyntax)newNode).Variable); default: throw ExceptionUtilities.UnexpectedValue(oldNode.Kind()); } } private static bool AreSimilarActiveStatements(CommonForEachStatementSyntax oldNode, CommonForEachStatementSyntax newNode) { List<SyntaxToken>? oldTokens = null; List<SyntaxToken>? newTokens = null; SyntaxComparer.GetLocalNames(oldNode, ref oldTokens); SyntaxComparer.GetLocalNames(newNode, ref newTokens); // A valid foreach statement declares at least one variable. RoslynDebug.Assert(oldTokens != null); RoslynDebug.Assert(newTokens != null); return DeclareSameIdentifiers(oldTokens.ToArray(), newTokens.ToArray()); } internal override bool IsInterfaceDeclaration(SyntaxNode node) => node.IsKind(SyntaxKind.InterfaceDeclaration); internal override bool IsRecordDeclaration(SyntaxNode node) => node.IsKind(SyntaxKind.RecordDeclaration, SyntaxKind.RecordStructDeclaration); internal override SyntaxNode? TryGetContainingTypeDeclaration(SyntaxNode node) => node is CompilationUnitSyntax ? null : node.Parent!.FirstAncestorOrSelf<BaseTypeDeclarationSyntax>(); internal override bool HasBackingField(SyntaxNode propertyOrIndexerDeclaration) => propertyOrIndexerDeclaration.IsKind(SyntaxKind.PropertyDeclaration, out PropertyDeclarationSyntax? propertyDecl) && SyntaxUtilities.HasBackingField(propertyDecl); internal override bool TryGetAssociatedMemberDeclaration(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? declaration) { if (node.IsKind(SyntaxKind.Parameter, SyntaxKind.TypeParameter)) { Contract.ThrowIfFalse(node.IsParentKind(SyntaxKind.ParameterList, SyntaxKind.TypeParameterList, SyntaxKind.BracketedParameterList)); declaration = node.Parent!.Parent!; return true; } if (node.Parent.IsParentKind(SyntaxKind.PropertyDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.EventDeclaration)) { declaration = node.Parent.Parent!; return true; } declaration = null; return false; } internal override bool IsDeclarationWithInitializer(SyntaxNode declaration) => declaration is VariableDeclaratorSyntax { Initializer: not null } || declaration is PropertyDeclarationSyntax { Initializer: not null }; internal override bool IsRecordPrimaryConstructorParameter(SyntaxNode declaration) => declaration is ParameterSyntax { Parent: ParameterListSyntax { Parent: RecordDeclarationSyntax } }; private static bool IsPropertyDeclarationMatchingPrimaryConstructorParameter(SyntaxNode declaration, INamedTypeSymbol newContainingType) { if (newContainingType.IsRecord && declaration is PropertyDeclarationSyntax { Identifier: { ValueText: var name } }) { // We need to use symbol information to find the primary constructor, because it could be in another file if the type is partial foreach (var reference in newContainingType.DeclaringSyntaxReferences) { // Since users can define as many constructors as they like, going back to syntax to find the parameter list // in the record declaration is the simplest way to check if there is a matching parameter if (reference.GetSyntax() is RecordDeclarationSyntax record && record.ParameterList is not null && record.ParameterList.Parameters.Any(p => p.Identifier.ValueText.Equals(name))) { return true; } } } return false; } internal override bool IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(SyntaxNode declaration, INamedTypeSymbol newContainingType, out bool isFirstAccessor) { isFirstAccessor = false; if (declaration is AccessorDeclarationSyntax { Parent: AccessorListSyntax { Parent: PropertyDeclarationSyntax property } list } && IsPropertyDeclarationMatchingPrimaryConstructorParameter(property, newContainingType)) { isFirstAccessor = list.Accessors[0] == declaration; return true; } return false; } internal override bool IsConstructorWithMemberInitializers(SyntaxNode constructorDeclaration) => constructorDeclaration is ConstructorDeclarationSyntax ctor && (ctor.Initializer == null || ctor.Initializer.IsKind(SyntaxKind.BaseConstructorInitializer)); internal override bool IsPartial(INamedTypeSymbol type) { var syntaxRefs = type.DeclaringSyntaxReferences; return syntaxRefs.Length > 1 || ((BaseTypeDeclarationSyntax)syntaxRefs.Single().GetSyntax()).Modifiers.Any(SyntaxKind.PartialKeyword); } protected override SyntaxNode GetSymbolDeclarationSyntax(SyntaxReference reference, CancellationToken cancellationToken) => reference.GetSyntax(cancellationToken); protected override OneOrMany<(ISymbol? oldSymbol, ISymbol? newSymbol, EditKind editKind)> GetSymbolEdits( EditKind editKind, SyntaxNode? oldNode, SyntaxNode? newNode, SemanticModel? oldModel, SemanticModel newModel, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, CancellationToken cancellationToken) { var oldSymbol = (oldNode != null) ? GetSymbolForEdit(oldNode, oldModel!, cancellationToken) : null; var newSymbol = (newNode != null) ? GetSymbolForEdit(newNode, newModel, cancellationToken) : null; switch (editKind) { case EditKind.Update: Contract.ThrowIfNull(oldNode); Contract.ThrowIfNull(newNode); Contract.ThrowIfNull(oldModel); // Certain updates of a property/indexer node affects its accessors. // Return all affected symbols for these updates. // 1) Old or new property/indexer has an expression body: // int this[...] => expr; // int this[...] { get => expr; } // int P => expr; // int P { get => expr; } = init if (oldNode is PropertyDeclarationSyntax { ExpressionBody: not null } or IndexerDeclarationSyntax { ExpressionBody: not null } || newNode is PropertyDeclarationSyntax { ExpressionBody: not null } or IndexerDeclarationSyntax { ExpressionBody: not null }) { Debug.Assert(oldSymbol is IPropertySymbol); Debug.Assert(newSymbol is IPropertySymbol); var oldGetterSymbol = ((IPropertySymbol)oldSymbol).GetMethod; var newGetterSymbol = ((IPropertySymbol)newSymbol).GetMethod; return OneOrMany.Create(ImmutableArray.Create((oldSymbol, newSymbol, editKind), (oldGetterSymbol, newGetterSymbol, editKind))); } // 2) Property/indexer declarations differ in readonly keyword. if (oldNode is PropertyDeclarationSyntax oldProperty && newNode is PropertyDeclarationSyntax newProperty && DiffersInReadOnlyModifier(oldProperty.Modifiers, newProperty.Modifiers) || oldNode is IndexerDeclarationSyntax oldIndexer && newNode is IndexerDeclarationSyntax newIndexer && DiffersInReadOnlyModifier(oldIndexer.Modifiers, newIndexer.Modifiers)) { Debug.Assert(oldSymbol is IPropertySymbol); Debug.Assert(newSymbol is IPropertySymbol); var oldPropertySymbol = (IPropertySymbol)oldSymbol; var newPropertySymbol = (IPropertySymbol)newSymbol; using var _ = ArrayBuilder<(ISymbol?, ISymbol?, EditKind)>.GetInstance(out var builder); builder.Add((oldPropertySymbol, newPropertySymbol, editKind)); if (oldPropertySymbol.GetMethod != null && newPropertySymbol.GetMethod != null && oldPropertySymbol.GetMethod.IsReadOnly != newPropertySymbol.GetMethod.IsReadOnly) { builder.Add((oldPropertySymbol.GetMethod, newPropertySymbol.GetMethod, editKind)); } if (oldPropertySymbol.SetMethod != null && newPropertySymbol.SetMethod != null && oldPropertySymbol.SetMethod.IsReadOnly != newPropertySymbol.SetMethod.IsReadOnly) { builder.Add((oldPropertySymbol.SetMethod, newPropertySymbol.SetMethod, editKind)); } return OneOrMany.Create(builder.ToImmutable()); } static bool DiffersInReadOnlyModifier(SyntaxTokenList oldModifiers, SyntaxTokenList newModifiers) => (oldModifiers.IndexOf(SyntaxKind.ReadOnlyKeyword) >= 0) != (newModifiers.IndexOf(SyntaxKind.ReadOnlyKeyword) >= 0); // Change in attributes or modifiers of a field affects all its variable declarations. if (oldNode is BaseFieldDeclarationSyntax oldField && newNode is BaseFieldDeclarationSyntax newField) { return GetFieldSymbolUpdates(oldField.Declaration.Variables, newField.Declaration.Variables); } // Chnage in type of a field affects all its variable declarations. if (oldNode is VariableDeclarationSyntax oldVariableDeclaration && newNode is VariableDeclarationSyntax newVariableDeclaration) { return GetFieldSymbolUpdates(oldVariableDeclaration.Variables, newVariableDeclaration.Variables); } OneOrMany<(ISymbol?, ISymbol?, EditKind)> GetFieldSymbolUpdates(SeparatedSyntaxList<VariableDeclaratorSyntax> oldVariables, SeparatedSyntaxList<VariableDeclaratorSyntax> newVariables) { if (oldVariables.Count == 1 && newVariables.Count == 1) { return OneOrMany.Create((oldModel.GetDeclaredSymbol(oldVariables[0], cancellationToken), newModel.GetDeclaredSymbol(newVariables[0], cancellationToken), EditKind.Update)); } var result = from oldVariable in oldVariables join newVariable in newVariables on oldVariable.Identifier.Text equals newVariable.Identifier.Text select (oldModel.GetDeclaredSymbol(oldVariable, cancellationToken), newModel.GetDeclaredSymbol(newVariable, cancellationToken), EditKind.Update); return OneOrMany.Create(result.ToImmutableArray()); } break; case EditKind.Delete: case EditKind.Insert: var node = oldNode ?? newNode; // If the entire block-bodied property/indexer is deleted/inserted (accessors and the list they are contained in), // ignore this edit. We will have a semantic edit for the property/indexer itself. if (node.IsKind(SyntaxKind.GetAccessorDeclaration)) { Debug.Assert(node.Parent.IsKind(SyntaxKind.AccessorList)); if (HasEdit(editMap, node.Parent, editKind) && !HasEdit(editMap, node.Parent.Parent, editKind)) { return OneOrMany<(ISymbol?, ISymbol?, EditKind)>.Empty; } } // Inserting/deleting an expression-bodied property/indexer affects two symbols: // the property/indexer itself and the getter. // int this[...] => expr; // int P => expr; if (node is PropertyDeclarationSyntax { ExpressionBody: not null } or IndexerDeclarationSyntax { ExpressionBody: not null }) { var oldGetterSymbol = ((IPropertySymbol?)oldSymbol)?.GetMethod; var newGetterSymbol = ((IPropertySymbol?)newSymbol)?.GetMethod; return OneOrMany.Create(ImmutableArray.Create((oldSymbol, newSymbol, editKind), (oldGetterSymbol, newGetterSymbol, editKind))); } // Inserting/deleting a type parameter constraint should result in an update of the corresponding type parameter symbol: if (node.IsKind(SyntaxKind.TypeParameterConstraintClause)) { return OneOrMany.Create(ImmutableArray.Create((oldSymbol, newSymbol, EditKind.Update))); } // Inserting/deleting a global statement should result in an update of the implicit main method: if (node.IsKind(SyntaxKind.GlobalStatement)) { return OneOrMany.Create(ImmutableArray.Create((oldSymbol, newSymbol, EditKind.Update))); } break; } return (editKind == EditKind.Delete ? oldSymbol : newSymbol) is null ? OneOrMany<(ISymbol?, ISymbol?, EditKind)>.Empty : new OneOrMany<(ISymbol?, ISymbol?, EditKind)>((oldSymbol, newSymbol, editKind)); } private static ISymbol? GetSymbolForEdit( SyntaxNode node, SemanticModel model, CancellationToken cancellationToken) { if (node.IsKind(SyntaxKind.UsingDirective, SyntaxKind.NamespaceDeclaration, SyntaxKind.FileScopedNamespaceDeclaration)) { return null; } if (node.IsKind(SyntaxKind.TypeParameterConstraintClause)) { var constraintClause = (TypeParameterConstraintClauseSyntax)node; var symbolInfo = model.GetSymbolInfo(constraintClause.Name, cancellationToken); return symbolInfo.Symbol; } // Top level code always lives in a synthesized Main method if (node.IsKind(SyntaxKind.GlobalStatement)) { return model.GetEnclosingSymbol(node.SpanStart, cancellationToken); } var symbol = model.GetDeclaredSymbol(node, cancellationToken); // TODO: this is incorrect (https://github.com/dotnet/roslyn/issues/54800) // Ignore partial method definition parts. // Partial method that does not have implementation part is not emitted to metadata. // Partial method without a definition part is a compilation error. if (symbol is IMethodSymbol { IsPartialDefinition: true }) { return null; } return symbol; } internal override bool ContainsLambda(SyntaxNode declaration) => declaration.DescendantNodes().Any(LambdaUtilities.IsLambda); internal override bool IsLambda(SyntaxNode node) => LambdaUtilities.IsLambda(node); internal override bool IsLocalFunction(SyntaxNode node) => node.IsKind(SyntaxKind.LocalFunctionStatement); internal override bool IsNestedFunction(SyntaxNode node) => node is AnonymousFunctionExpressionSyntax or LocalFunctionStatementSyntax; internal override bool TryGetLambdaBodies(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? body1, out SyntaxNode? body2) => LambdaUtilities.TryGetLambdaBodies(node, out body1, out body2); internal override SyntaxNode GetLambda(SyntaxNode lambdaBody) => LambdaUtilities.GetLambda(lambdaBody); internal override IMethodSymbol GetLambdaExpressionSymbol(SemanticModel model, SyntaxNode lambdaExpression, CancellationToken cancellationToken) { var bodyExpression = LambdaUtilities.GetNestedFunctionBody(lambdaExpression); return (IMethodSymbol)model.GetRequiredEnclosingSymbol(bodyExpression.SpanStart, cancellationToken); } internal override SyntaxNode? GetContainingQueryExpression(SyntaxNode node) => node.FirstAncestorOrSelf<QueryExpressionSyntax>(); internal override bool QueryClauseLambdasTypeEquivalent(SemanticModel oldModel, SyntaxNode oldNode, SemanticModel newModel, SyntaxNode newNode, CancellationToken cancellationToken) { switch (oldNode.Kind()) { case SyntaxKind.FromClause: case SyntaxKind.LetClause: case SyntaxKind.WhereClause: case SyntaxKind.OrderByClause: case SyntaxKind.JoinClause: var oldQueryClauseInfo = oldModel.GetQueryClauseInfo((QueryClauseSyntax)oldNode, cancellationToken); var newQueryClauseInfo = newModel.GetQueryClauseInfo((QueryClauseSyntax)newNode, cancellationToken); return MemberSignaturesEquivalent(oldQueryClauseInfo.CastInfo.Symbol, newQueryClauseInfo.CastInfo.Symbol) && MemberSignaturesEquivalent(oldQueryClauseInfo.OperationInfo.Symbol, newQueryClauseInfo.OperationInfo.Symbol); case SyntaxKind.AscendingOrdering: case SyntaxKind.DescendingOrdering: var oldOrderingInfo = oldModel.GetSymbolInfo(oldNode, cancellationToken); var newOrderingInfo = newModel.GetSymbolInfo(newNode, cancellationToken); return MemberSignaturesEquivalent(oldOrderingInfo.Symbol, newOrderingInfo.Symbol); case SyntaxKind.SelectClause: var oldSelectInfo = oldModel.GetSymbolInfo(oldNode, cancellationToken); var newSelectInfo = newModel.GetSymbolInfo(newNode, cancellationToken); // Changing reduced select clause to a non-reduced form or vice versa // adds/removes a call to Select method, which is a supported change. return oldSelectInfo.Symbol == null || newSelectInfo.Symbol == null || MemberSignaturesEquivalent(oldSelectInfo.Symbol, newSelectInfo.Symbol); case SyntaxKind.GroupClause: var oldGroupByInfo = oldModel.GetSymbolInfo(oldNode, cancellationToken); var newGroupByInfo = newModel.GetSymbolInfo(newNode, cancellationToken); return MemberSignaturesEquivalent(oldGroupByInfo.Symbol, newGroupByInfo.Symbol, GroupBySignatureComparer); default: return true; } } private static bool GroupBySignatureComparer(ImmutableArray<IParameterSymbol> oldParameters, ITypeSymbol oldReturnType, ImmutableArray<IParameterSymbol> newParameters, ITypeSymbol newReturnType) { // C# spec paragraph 7.16.2.6 "Groupby clauses": // // A query expression of the form // from x in e group v by k // is translated into // (e).GroupBy(x => k, x => v) // except when v is the identifier x, the translation is // (e).GroupBy(x => k) // // Possible signatures: // C<G<K, T>> GroupBy<K>(Func<T, K> keySelector); // C<G<K, E>> GroupBy<K, E>(Func<T, K> keySelector, Func<T, E> elementSelector); if (!TypesEquivalent(oldReturnType, newReturnType, exact: false)) { return false; } Debug.Assert(oldParameters.Length == 1 || oldParameters.Length == 2); Debug.Assert(newParameters.Length == 1 || newParameters.Length == 2); // The types of the lambdas have to be the same if present. // The element selector may be added/removed. if (!ParameterTypesEquivalent(oldParameters[0], newParameters[0], exact: false)) { return false; } if (oldParameters.Length == newParameters.Length && newParameters.Length == 2) { return ParameterTypesEquivalent(oldParameters[1], newParameters[1], exact: false); } return true; } #endregion #region Diagnostic Info protected override SymbolDisplayFormat ErrorDisplayFormat => SymbolDisplayFormat.CSharpErrorMessageFormat; protected override TextSpan? TryGetDiagnosticSpan(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpanImpl(node, editKind); internal static new TextSpan GetDiagnosticSpan(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpanImpl(node, editKind) ?? node.Span; private static TextSpan? TryGetDiagnosticSpanImpl(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpanImpl(node.Kind(), node, editKind); // internal for testing; kind is passed explicitly for testing as well internal static TextSpan? TryGetDiagnosticSpanImpl(SyntaxKind kind, SyntaxNode node, EditKind editKind) { switch (kind) { case SyntaxKind.CompilationUnit: return default(TextSpan); case SyntaxKind.GlobalStatement: return node.Span; case SyntaxKind.ExternAliasDirective: case SyntaxKind.UsingDirective: return node.Span; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: var ns = (BaseNamespaceDeclarationSyntax)node; return TextSpan.FromBounds(ns.NamespaceKeyword.SpanStart, ns.Name.Span.End); case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: var typeDeclaration = (TypeDeclarationSyntax)node; return GetDiagnosticSpan(typeDeclaration.Modifiers, typeDeclaration.Keyword, typeDeclaration.TypeParameterList ?? (SyntaxNodeOrToken)typeDeclaration.Identifier); case SyntaxKind.EnumDeclaration: var enumDeclaration = (EnumDeclarationSyntax)node; return GetDiagnosticSpan(enumDeclaration.Modifiers, enumDeclaration.EnumKeyword, enumDeclaration.Identifier); case SyntaxKind.DelegateDeclaration: var delegateDeclaration = (DelegateDeclarationSyntax)node; return GetDiagnosticSpan(delegateDeclaration.Modifiers, delegateDeclaration.DelegateKeyword, delegateDeclaration.ParameterList); case SyntaxKind.FieldDeclaration: var fieldDeclaration = (BaseFieldDeclarationSyntax)node; return GetDiagnosticSpan(fieldDeclaration.Modifiers, fieldDeclaration.Declaration, fieldDeclaration.Declaration); case SyntaxKind.EventFieldDeclaration: var eventFieldDeclaration = (EventFieldDeclarationSyntax)node; return GetDiagnosticSpan(eventFieldDeclaration.Modifiers, eventFieldDeclaration.EventKeyword, eventFieldDeclaration.Declaration); case SyntaxKind.VariableDeclaration: return TryGetDiagnosticSpanImpl(node.Parent!, editKind); case SyntaxKind.VariableDeclarator: return node.Span; case SyntaxKind.MethodDeclaration: var methodDeclaration = (MethodDeclarationSyntax)node; return GetDiagnosticSpan(methodDeclaration.Modifiers, methodDeclaration.ReturnType, methodDeclaration.ParameterList); case SyntaxKind.ConversionOperatorDeclaration: var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)node; return GetDiagnosticSpan(conversionOperatorDeclaration.Modifiers, conversionOperatorDeclaration.ImplicitOrExplicitKeyword, conversionOperatorDeclaration.ParameterList); case SyntaxKind.OperatorDeclaration: var operatorDeclaration = (OperatorDeclarationSyntax)node; return GetDiagnosticSpan(operatorDeclaration.Modifiers, operatorDeclaration.ReturnType, operatorDeclaration.ParameterList); case SyntaxKind.ConstructorDeclaration: var constructorDeclaration = (ConstructorDeclarationSyntax)node; return GetDiagnosticSpan(constructorDeclaration.Modifiers, constructorDeclaration.Identifier, constructorDeclaration.ParameterList); case SyntaxKind.DestructorDeclaration: var destructorDeclaration = (DestructorDeclarationSyntax)node; return GetDiagnosticSpan(destructorDeclaration.Modifiers, destructorDeclaration.TildeToken, destructorDeclaration.ParameterList); case SyntaxKind.PropertyDeclaration: var propertyDeclaration = (PropertyDeclarationSyntax)node; return GetDiagnosticSpan(propertyDeclaration.Modifiers, propertyDeclaration.Type, propertyDeclaration.Identifier); case SyntaxKind.IndexerDeclaration: var indexerDeclaration = (IndexerDeclarationSyntax)node; return GetDiagnosticSpan(indexerDeclaration.Modifiers, indexerDeclaration.Type, indexerDeclaration.ParameterList); case SyntaxKind.EventDeclaration: var eventDeclaration = (EventDeclarationSyntax)node; return GetDiagnosticSpan(eventDeclaration.Modifiers, eventDeclaration.EventKeyword, eventDeclaration.Identifier); case SyntaxKind.EnumMemberDeclaration: return node.Span; case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.UnknownAccessorDeclaration: var accessorDeclaration = (AccessorDeclarationSyntax)node; return GetDiagnosticSpan(accessorDeclaration.Modifiers, accessorDeclaration.Keyword, accessorDeclaration.Keyword); case SyntaxKind.TypeParameterConstraintClause: var constraint = (TypeParameterConstraintClauseSyntax)node; return TextSpan.FromBounds(constraint.WhereKeyword.SpanStart, constraint.Constraints.Last().Span.End); case SyntaxKind.TypeParameter: var typeParameter = (TypeParameterSyntax)node; return typeParameter.Identifier.Span; case SyntaxKind.AccessorList: case SyntaxKind.TypeParameterList: case SyntaxKind.ParameterList: case SyntaxKind.BracketedParameterList: if (editKind == EditKind.Delete) { return TryGetDiagnosticSpanImpl(node.Parent!, editKind); } else { return node.Span; } case SyntaxKind.Parameter: var parameter = (ParameterSyntax)node; // Lambda parameters don't have types or modifiers, so the parameter is the only node var startNode = parameter.Type ?? (SyntaxNode)parameter; return GetDiagnosticSpan(parameter.Modifiers, startNode, parameter); case SyntaxKind.AttributeList: var attributeList = (AttributeListSyntax)node; return attributeList.Span; case SyntaxKind.Attribute: return node.Span; case SyntaxKind.ArrowExpressionClause: return TryGetDiagnosticSpanImpl(node.Parent!, editKind); // We only need a diagnostic span if reporting an error for a child statement. // The following statements may have child statements. case SyntaxKind.Block: return ((BlockSyntax)node).OpenBraceToken.Span; case SyntaxKind.UsingStatement: var usingStatement = (UsingStatementSyntax)node; return TextSpan.FromBounds(usingStatement.UsingKeyword.SpanStart, usingStatement.CloseParenToken.Span.End); case SyntaxKind.FixedStatement: var fixedStatement = (FixedStatementSyntax)node; return TextSpan.FromBounds(fixedStatement.FixedKeyword.SpanStart, fixedStatement.CloseParenToken.Span.End); case SyntaxKind.LockStatement: var lockStatement = (LockStatementSyntax)node; return TextSpan.FromBounds(lockStatement.LockKeyword.SpanStart, lockStatement.CloseParenToken.Span.End); case SyntaxKind.StackAllocArrayCreationExpression: return ((StackAllocArrayCreationExpressionSyntax)node).StackAllocKeyword.Span; case SyntaxKind.ImplicitStackAllocArrayCreationExpression: return ((ImplicitStackAllocArrayCreationExpressionSyntax)node).StackAllocKeyword.Span; case SyntaxKind.TryStatement: return ((TryStatementSyntax)node).TryKeyword.Span; case SyntaxKind.CatchClause: return ((CatchClauseSyntax)node).CatchKeyword.Span; case SyntaxKind.CatchDeclaration: case SyntaxKind.CatchFilterClause: return node.Span; case SyntaxKind.FinallyClause: return ((FinallyClauseSyntax)node).FinallyKeyword.Span; case SyntaxKind.IfStatement: var ifStatement = (IfStatementSyntax)node; return TextSpan.FromBounds(ifStatement.IfKeyword.SpanStart, ifStatement.CloseParenToken.Span.End); case SyntaxKind.ElseClause: return ((ElseClauseSyntax)node).ElseKeyword.Span; case SyntaxKind.SwitchStatement: var switchStatement = (SwitchStatementSyntax)node; return TextSpan.FromBounds(switchStatement.SwitchKeyword.SpanStart, (switchStatement.CloseParenToken != default) ? switchStatement.CloseParenToken.Span.End : switchStatement.Expression.Span.End); case SyntaxKind.SwitchSection: return ((SwitchSectionSyntax)node).Labels.Last().Span; case SyntaxKind.WhileStatement: var whileStatement = (WhileStatementSyntax)node; return TextSpan.FromBounds(whileStatement.WhileKeyword.SpanStart, whileStatement.CloseParenToken.Span.End); case SyntaxKind.DoStatement: return ((DoStatementSyntax)node).DoKeyword.Span; case SyntaxKind.ForStatement: var forStatement = (ForStatementSyntax)node; return TextSpan.FromBounds(forStatement.ForKeyword.SpanStart, forStatement.CloseParenToken.Span.End); case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: var commonForEachStatement = (CommonForEachStatementSyntax)node; return TextSpan.FromBounds( (commonForEachStatement.AwaitKeyword.Span.Length > 0) ? commonForEachStatement.AwaitKeyword.SpanStart : commonForEachStatement.ForEachKeyword.SpanStart, commonForEachStatement.CloseParenToken.Span.End); case SyntaxKind.LabeledStatement: return ((LabeledStatementSyntax)node).Identifier.Span; case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return ((CheckedStatementSyntax)node).Keyword.Span; case SyntaxKind.UnsafeStatement: return ((UnsafeStatementSyntax)node).UnsafeKeyword.Span; case SyntaxKind.LocalFunctionStatement: var lfd = (LocalFunctionStatementSyntax)node; return lfd.Identifier.Span; case SyntaxKind.YieldBreakStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.ExpressionStatement: case SyntaxKind.EmptyStatement: case SyntaxKind.GotoStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: return node.Span; case SyntaxKind.LocalDeclarationStatement: var localDeclarationStatement = (LocalDeclarationStatementSyntax)node; return CombineSpans(localDeclarationStatement.AwaitKeyword.Span, localDeclarationStatement.UsingKeyword.Span, node.Span); case SyntaxKind.AwaitExpression: return ((AwaitExpressionSyntax)node).AwaitKeyword.Span; case SyntaxKind.AnonymousObjectCreationExpression: return ((AnonymousObjectCreationExpressionSyntax)node).NewKeyword.Span; case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)node).ParameterList.Span; case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)node).Parameter.Span; case SyntaxKind.AnonymousMethodExpression: return ((AnonymousMethodExpressionSyntax)node).DelegateKeyword.Span; case SyntaxKind.QueryExpression: return ((QueryExpressionSyntax)node).FromClause.FromKeyword.Span; case SyntaxKind.QueryBody: var queryBody = (QueryBodySyntax)node; return TryGetDiagnosticSpanImpl(queryBody.Clauses.FirstOrDefault() ?? queryBody.Parent!, editKind); case SyntaxKind.QueryContinuation: return ((QueryContinuationSyntax)node).IntoKeyword.Span; case SyntaxKind.FromClause: return ((FromClauseSyntax)node).FromKeyword.Span; case SyntaxKind.JoinClause: return ((JoinClauseSyntax)node).JoinKeyword.Span; case SyntaxKind.JoinIntoClause: return ((JoinIntoClauseSyntax)node).IntoKeyword.Span; case SyntaxKind.LetClause: return ((LetClauseSyntax)node).LetKeyword.Span; case SyntaxKind.WhereClause: return ((WhereClauseSyntax)node).WhereKeyword.Span; case SyntaxKind.OrderByClause: return ((OrderByClauseSyntax)node).OrderByKeyword.Span; case SyntaxKind.AscendingOrdering: case SyntaxKind.DescendingOrdering: return node.Span; case SyntaxKind.SelectClause: return ((SelectClauseSyntax)node).SelectKeyword.Span; case SyntaxKind.GroupClause: return ((GroupClauseSyntax)node).GroupKeyword.Span; case SyntaxKind.IsPatternExpression: case SyntaxKind.TupleType: case SyntaxKind.TupleExpression: case SyntaxKind.DeclarationExpression: case SyntaxKind.RefType: case SyntaxKind.RefExpression: case SyntaxKind.DeclarationPattern: case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.WhenClause: case SyntaxKind.SingleVariableDesignation: case SyntaxKind.CasePatternSwitchLabel: return node.Span; case SyntaxKind.SwitchExpression: return ((SwitchExpressionSyntax)node).SwitchKeyword.Span; case SyntaxKind.SwitchExpressionArm: return ((SwitchExpressionArmSyntax)node).EqualsGreaterThanToken.Span; default: return null; } } private static TextSpan GetDiagnosticSpan(SyntaxTokenList modifiers, SyntaxNodeOrToken start, SyntaxNodeOrToken end) => TextSpan.FromBounds((modifiers.Count != 0) ? modifiers.First().SpanStart : start.SpanStart, end.Span.End); private static TextSpan CombineSpans(TextSpan first, TextSpan second, TextSpan defaultSpan) => (first.Length > 0 && second.Length > 0) ? TextSpan.FromBounds(first.Start, second.End) : (first.Length > 0) ? first : (second.Length > 0) ? second : defaultSpan; internal override TextSpan GetLambdaParameterDiagnosticSpan(SyntaxNode lambda, int ordinal) { Debug.Assert(ordinal >= 0); switch (lambda.Kind()) { case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)lambda).ParameterList.Parameters[ordinal].Identifier.Span; case SyntaxKind.SimpleLambdaExpression: Debug.Assert(ordinal == 0); return ((SimpleLambdaExpressionSyntax)lambda).Parameter.Identifier.Span; case SyntaxKind.AnonymousMethodExpression: // since we are given a parameter ordinal there has to be a parameter list: return ((AnonymousMethodExpressionSyntax)lambda).ParameterList!.Parameters[ordinal].Identifier.Span; default: return lambda.Span; } } internal override string GetDisplayName(INamedTypeSymbol symbol) => symbol.TypeKind switch { TypeKind.Struct => symbol.IsRecord ? CSharpFeaturesResources.record_struct : CSharpFeaturesResources.struct_, TypeKind.Class => symbol.IsRecord ? CSharpFeaturesResources.record_ : FeaturesResources.class_, _ => base.GetDisplayName(symbol) }; internal override string GetDisplayName(IPropertySymbol symbol) => symbol.IsIndexer ? CSharpFeaturesResources.indexer : base.GetDisplayName(symbol); internal override string GetDisplayName(IMethodSymbol symbol) => symbol.MethodKind switch { MethodKind.PropertyGet => symbol.AssociatedSymbol is IPropertySymbol { IsIndexer: true } ? CSharpFeaturesResources.indexer_getter : CSharpFeaturesResources.property_getter, MethodKind.PropertySet => symbol.AssociatedSymbol is IPropertySymbol { IsIndexer: true } ? CSharpFeaturesResources.indexer_setter : CSharpFeaturesResources.property_setter, MethodKind.StaticConstructor => FeaturesResources.static_constructor, MethodKind.Destructor => CSharpFeaturesResources.destructor, MethodKind.Conversion => CSharpFeaturesResources.conversion_operator, MethodKind.LocalFunction => FeaturesResources.local_function, _ => base.GetDisplayName(symbol) }; protected override string? TryGetDisplayName(SyntaxNode node, EditKind editKind) => TryGetDisplayNameImpl(node, editKind); internal static new string? GetDisplayName(SyntaxNode node, EditKind editKind) => TryGetDisplayNameImpl(node, editKind) ?? throw ExceptionUtilities.UnexpectedValue(node.Kind()); internal static string? TryGetDisplayNameImpl(SyntaxNode node, EditKind editKind) { switch (node.Kind()) { // top-level case SyntaxKind.CompilationUnit: case SyntaxKind.GlobalStatement: return CSharpFeaturesResources.global_statement; case SyntaxKind.ExternAliasDirective: return CSharpFeaturesResources.extern_alias; case SyntaxKind.UsingDirective: // Dev12 distinguishes using alias from using namespace and reports different errors for removing alias. // None of these changes are allowed anyways, so let's keep it simple. return CSharpFeaturesResources.using_directive; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return FeaturesResources.namespace_; case SyntaxKind.ClassDeclaration: return FeaturesResources.class_; case SyntaxKind.StructDeclaration: return CSharpFeaturesResources.struct_; case SyntaxKind.InterfaceDeclaration: return FeaturesResources.interface_; case SyntaxKind.RecordDeclaration: return CSharpFeaturesResources.record_; case SyntaxKind.RecordStructDeclaration: return CSharpFeaturesResources.record_struct; case SyntaxKind.EnumDeclaration: return FeaturesResources.enum_; case SyntaxKind.DelegateDeclaration: return FeaturesResources.delegate_; case SyntaxKind.FieldDeclaration: var declaration = (FieldDeclarationSyntax)node; return declaration.Modifiers.Any(SyntaxKind.ConstKeyword) ? FeaturesResources.const_field : FeaturesResources.field; case SyntaxKind.EventFieldDeclaration: return CSharpFeaturesResources.event_field; case SyntaxKind.VariableDeclaration: case SyntaxKind.VariableDeclarator: return TryGetDisplayNameImpl(node.Parent!, editKind); case SyntaxKind.MethodDeclaration: return FeaturesResources.method; case SyntaxKind.ConversionOperatorDeclaration: return CSharpFeaturesResources.conversion_operator; case SyntaxKind.OperatorDeclaration: return FeaturesResources.operator_; case SyntaxKind.ConstructorDeclaration: var ctor = (ConstructorDeclarationSyntax)node; return ctor.Modifiers.Any(SyntaxKind.StaticKeyword) ? FeaturesResources.static_constructor : FeaturesResources.constructor; case SyntaxKind.DestructorDeclaration: return CSharpFeaturesResources.destructor; case SyntaxKind.PropertyDeclaration: return SyntaxUtilities.HasBackingField((PropertyDeclarationSyntax)node) ? FeaturesResources.auto_property : FeaturesResources.property_; case SyntaxKind.IndexerDeclaration: return CSharpFeaturesResources.indexer; case SyntaxKind.EventDeclaration: return FeaturesResources.event_; case SyntaxKind.EnumMemberDeclaration: return FeaturesResources.enum_value; case SyntaxKind.GetAccessorDeclaration: if (node.Parent!.Parent!.IsKind(SyntaxKind.PropertyDeclaration)) { return CSharpFeaturesResources.property_getter; } else { RoslynDebug.Assert(node.Parent.Parent.IsKind(SyntaxKind.IndexerDeclaration)); return CSharpFeaturesResources.indexer_getter; } case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: if (node.Parent!.Parent!.IsKind(SyntaxKind.PropertyDeclaration)) { return CSharpFeaturesResources.property_setter; } else { RoslynDebug.Assert(node.Parent.Parent.IsKind(SyntaxKind.IndexerDeclaration)); return CSharpFeaturesResources.indexer_setter; } case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return FeaturesResources.event_accessor; case SyntaxKind.ArrowExpressionClause: return node.Parent!.Kind() switch { SyntaxKind.PropertyDeclaration => CSharpFeaturesResources.property_getter, SyntaxKind.IndexerDeclaration => CSharpFeaturesResources.indexer_getter, _ => null }; case SyntaxKind.TypeParameterConstraintClause: return FeaturesResources.type_constraint; case SyntaxKind.TypeParameterList: case SyntaxKind.TypeParameter: return FeaturesResources.type_parameter; case SyntaxKind.Parameter: return FeaturesResources.parameter; case SyntaxKind.AttributeList: return FeaturesResources.attribute; case SyntaxKind.Attribute: return FeaturesResources.attribute; case SyntaxKind.AttributeTargetSpecifier: return CSharpFeaturesResources.attribute_target; // statement: case SyntaxKind.TryStatement: return CSharpFeaturesResources.try_block; case SyntaxKind.CatchClause: case SyntaxKind.CatchDeclaration: return CSharpFeaturesResources.catch_clause; case SyntaxKind.CatchFilterClause: return CSharpFeaturesResources.filter_clause; case SyntaxKind.FinallyClause: return CSharpFeaturesResources.finally_clause; case SyntaxKind.FixedStatement: return CSharpFeaturesResources.fixed_statement; case SyntaxKind.UsingStatement: return CSharpFeaturesResources.using_statement; case SyntaxKind.LockStatement: return CSharpFeaturesResources.lock_statement; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: return CSharpFeaturesResources.foreach_statement; case SyntaxKind.CheckedStatement: return CSharpFeaturesResources.checked_statement; case SyntaxKind.UncheckedStatement: return CSharpFeaturesResources.unchecked_statement; case SyntaxKind.YieldBreakStatement: return CSharpFeaturesResources.yield_break_statement; case SyntaxKind.YieldReturnStatement: return CSharpFeaturesResources.yield_return_statement; case SyntaxKind.AwaitExpression: return CSharpFeaturesResources.await_expression; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: return CSharpFeaturesResources.lambda; case SyntaxKind.AnonymousMethodExpression: return CSharpFeaturesResources.anonymous_method; case SyntaxKind.FromClause: return CSharpFeaturesResources.from_clause; case SyntaxKind.JoinClause: case SyntaxKind.JoinIntoClause: return CSharpFeaturesResources.join_clause; case SyntaxKind.LetClause: return CSharpFeaturesResources.let_clause; case SyntaxKind.WhereClause: return CSharpFeaturesResources.where_clause; case SyntaxKind.OrderByClause: case SyntaxKind.AscendingOrdering: case SyntaxKind.DescendingOrdering: return CSharpFeaturesResources.orderby_clause; case SyntaxKind.SelectClause: return CSharpFeaturesResources.select_clause; case SyntaxKind.GroupClause: return CSharpFeaturesResources.groupby_clause; case SyntaxKind.QueryBody: return CSharpFeaturesResources.query_body; case SyntaxKind.QueryContinuation: return CSharpFeaturesResources.into_clause; case SyntaxKind.IsPatternExpression: return CSharpFeaturesResources.is_pattern; case SyntaxKind.SimpleAssignmentExpression: if (((AssignmentExpressionSyntax)node).IsDeconstruction()) { return CSharpFeaturesResources.deconstruction; } else { throw ExceptionUtilities.UnexpectedValue(node.Kind()); } case SyntaxKind.TupleType: case SyntaxKind.TupleExpression: return CSharpFeaturesResources.tuple; case SyntaxKind.LocalFunctionStatement: return CSharpFeaturesResources.local_function; case SyntaxKind.DeclarationExpression: return CSharpFeaturesResources.out_var; case SyntaxKind.RefType: case SyntaxKind.RefExpression: return CSharpFeaturesResources.ref_local_or_expression; case SyntaxKind.SwitchStatement: return CSharpFeaturesResources.switch_statement; case SyntaxKind.LocalDeclarationStatement: if (((LocalDeclarationStatementSyntax)node).UsingKeyword.IsKind(SyntaxKind.UsingKeyword)) { return CSharpFeaturesResources.using_declaration; } return CSharpFeaturesResources.local_variable_declaration; default: return null; } } protected override string GetSuspensionPointDisplayName(SyntaxNode node, EditKind editKind) { switch (node.Kind()) { case SyntaxKind.ForEachStatement: Debug.Assert(((CommonForEachStatementSyntax)node).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)); return CSharpFeaturesResources.asynchronous_foreach_statement; case SyntaxKind.VariableDeclarator: RoslynDebug.Assert(((LocalDeclarationStatementSyntax)node.Parent!.Parent!).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)); return CSharpFeaturesResources.asynchronous_using_declaration; default: return base.GetSuspensionPointDisplayName(node, editKind); } } #endregion #region Top-Level Syntactic Rude Edits private readonly struct EditClassifier { private readonly CSharpEditAndContinueAnalyzer _analyzer; private readonly ArrayBuilder<RudeEditDiagnostic> _diagnostics; private readonly Match<SyntaxNode>? _match; private readonly SyntaxNode? _oldNode; private readonly SyntaxNode? _newNode; private readonly EditKind _kind; private readonly TextSpan? _span; public EditClassifier( CSharpEditAndContinueAnalyzer analyzer, ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode? oldNode, SyntaxNode? newNode, EditKind kind, Match<SyntaxNode>? match = null, TextSpan? span = null) { RoslynDebug.Assert(oldNode != null || newNode != null); // if the node is deleted we have map that can be used to closest new ancestor RoslynDebug.Assert(newNode != null || match != null); _analyzer = analyzer; _diagnostics = diagnostics; _oldNode = oldNode; _newNode = newNode; _kind = kind; _span = span; _match = match; } private void ReportError(RudeEditKind kind, SyntaxNode? spanNode = null, SyntaxNode? displayNode = null) { var span = (spanNode != null) ? GetDiagnosticSpan(spanNode, _kind) : GetSpan(); var node = displayNode ?? _newNode ?? _oldNode; var displayName = GetDisplayName(node!, _kind); _diagnostics.Add(new RudeEditDiagnostic(kind, span, node, arguments: new[] { displayName })); } private TextSpan GetSpan() { if (_span.HasValue) { return _span.Value; } if (_newNode == null) { return _analyzer.GetDeletedNodeDiagnosticSpan(_match!.Matches, _oldNode!); } return GetDiagnosticSpan(_newNode, _kind); } public void ClassifyEdit() { switch (_kind) { case EditKind.Delete: ClassifyDelete(_oldNode!); return; case EditKind.Update: ClassifyUpdate(_oldNode!, _newNode!); return; case EditKind.Move: ClassifyMove(_newNode!); return; case EditKind.Insert: ClassifyInsert(_newNode!); return; case EditKind.Reorder: ClassifyReorder(_newNode!); return; default: throw ExceptionUtilities.UnexpectedValue(_kind); } } private void ClassifyMove(SyntaxNode newNode) { if (newNode.IsKind(SyntaxKind.LocalFunctionStatement)) { return; } // We could perhaps allow moving a type declaration to a different namespace syntax node // as long as it represents semantically the same namespace as the one of the original type declaration. ReportError(RudeEditKind.Move); } private void ClassifyReorder(SyntaxNode newNode) { if (_newNode.IsKind(SyntaxKind.LocalFunctionStatement)) { return; } switch (newNode.Kind()) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.VariableDeclarator: // Maybe we could allow changing order of field declarations unless the containing type layout is sequential. ReportError(RudeEditKind.Move); return; case SyntaxKind.EnumMemberDeclaration: // To allow this change we would need to check that values of all fields of the enum // are preserved, or make sure we can update all method bodies that accessed those that changed. ReportError(RudeEditKind.Move); return; case SyntaxKind.TypeParameter: case SyntaxKind.Parameter: ReportError(RudeEditKind.Move); return; } } private void ClassifyInsert(SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.ExternAliasDirective: case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: ReportError(RudeEditKind.Insert); return; case SyntaxKind.Attribute: case SyntaxKind.AttributeList: // To allow inserting of attributes we need to check if the inserted attribute // is a pseudo-custom attribute that CLR allows us to change, or if it is a compiler well-know attribute // that affects the generated IL, so we defer those checks until semantic analysis. // Unless the attribute is a module/assembly attribute if (node.IsParentKind(SyntaxKind.CompilationUnit) || node.Parent.IsParentKind(SyntaxKind.CompilationUnit)) { ReportError(RudeEditKind.Insert); } return; } } private void ClassifyDelete(SyntaxNode oldNode) { switch (oldNode.Kind()) { case SyntaxKind.ExternAliasDirective: case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: // To allow removal of declarations we would need to update method bodies that // were previously binding to them but now are binding to another symbol that was previously hidden. ReportError(RudeEditKind.Delete); return; case SyntaxKind.AttributeList: case SyntaxKind.Attribute: // To allow removal of attributes we need to check if the removed attribute // is a pseudo-custom attribute that CLR does not allow us to change, or if it is a compiler well-know attribute // that affects the generated IL, so we defer those checks until semantic analysis. // Unless the attribute is a module/assembly attribute if (oldNode.IsParentKind(SyntaxKind.CompilationUnit) || oldNode.Parent.IsParentKind(SyntaxKind.CompilationUnit)) { ReportError(RudeEditKind.Delete); } return; } } private void ClassifyUpdate(SyntaxNode oldNode, SyntaxNode newNode) { switch (newNode.Kind()) { case SyntaxKind.ExternAliasDirective: ReportError(RudeEditKind.Update); return; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: ClassifyUpdate((BaseNamespaceDeclarationSyntax)oldNode, (BaseNamespaceDeclarationSyntax)newNode); return; case SyntaxKind.Attribute: // To allow update of attributes we need to check if the updated attribute // is a pseudo-custom attribute that CLR allows us to change, or if it is a compiler well-know attribute // that affects the generated IL, so we defer those checks until semantic analysis. // Unless the attribute is a module/assembly attribute if (newNode.IsParentKind(SyntaxKind.CompilationUnit) || newNode.Parent.IsParentKind(SyntaxKind.CompilationUnit)) { ReportError(RudeEditKind.Update); } return; } } private void ClassifyUpdate(BaseNamespaceDeclarationSyntax oldNode, BaseNamespaceDeclarationSyntax newNode) { Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.Name, newNode.Name)); ReportError(RudeEditKind.Renamed); } public void ClassifyDeclarationBodyRudeUpdates(SyntaxNode newDeclarationOrBody) { foreach (var node in newDeclarationOrBody.DescendantNodesAndSelf(LambdaUtilities.IsNotLambda)) { switch (node.Kind()) { case SyntaxKind.StackAllocArrayCreationExpression: case SyntaxKind.ImplicitStackAllocArrayCreationExpression: ReportError(RudeEditKind.StackAllocUpdate, node, _newNode); return; } } } } internal override void ReportTopLevelSyntacticRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, Edit<SyntaxNode> edit, Dictionary<SyntaxNode, EditKind> editMap) { if (HasParentEdit(editMap, edit)) { return; } var classifier = new EditClassifier(this, diagnostics, edit.OldNode, edit.NewNode, edit.Kind, match); classifier.ClassifyEdit(); } internal override void ReportMemberBodyUpdateRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newMember, TextSpan? span) { var classifier = new EditClassifier(this, diagnostics, oldNode: null, newMember, EditKind.Update, span: span); classifier.ClassifyDeclarationBodyRudeUpdates(newMember); } #endregion #region Semantic Rude Edits internal override void ReportInsertedMemberSymbolRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol newSymbol, SyntaxNode newNode, bool insertingIntoExistingContainingType) { var rudeEditKind = newSymbol switch { // Inserting extern member into a new or existing type is not allowed. { IsExtern: true } => RudeEditKind.InsertExtern, // All rude edits below only apply when inserting into an existing type (not when the type itself is inserted): _ when !insertingIntoExistingContainingType => RudeEditKind.None, // Inserting a member into an existing generic type is not allowed. { ContainingType: { Arity: > 0 } } and not INamedTypeSymbol => RudeEditKind.InsertIntoGenericType, // Inserting virtual or interface member into an existing type is not allowed. { IsVirtual: true } or { IsOverride: true } or { IsAbstract: true } and not INamedTypeSymbol => RudeEditKind.InsertVirtual, // Inserting generic method into an existing type is not allowed. IMethodSymbol { Arity: > 0 } => RudeEditKind.InsertGenericMethod, // Inserting destructor to an existing type is not allowed. IMethodSymbol { MethodKind: MethodKind.Destructor } => RudeEditKind.Insert, // Inserting operator to an existing type is not allowed. IMethodSymbol { MethodKind: MethodKind.Conversion or MethodKind.UserDefinedOperator } => RudeEditKind.InsertOperator, // Inserting a method that explictly implements an interface method into an existing type is not allowed. IMethodSymbol { ExplicitInterfaceImplementations: { IsEmpty: false } } => RudeEditKind.InsertMethodWithExplicitInterfaceSpecifier, // TODO: Inserting non-virtual member to an interface (https://github.com/dotnet/roslyn/issues/37128) { ContainingType: { TypeKind: TypeKind.Interface } } and not INamedTypeSymbol => RudeEditKind.InsertIntoInterface, // Inserting a field into an enum: #pragma warning disable format // https://github.com/dotnet/roslyn/issues/54759 IFieldSymbol { ContainingType.TypeKind: TypeKind.Enum } => RudeEditKind.Insert, #pragma warning restore format _ => RudeEditKind.None }; if (rudeEditKind != RudeEditKind.None) { diagnostics.Add(new RudeEditDiagnostic( rudeEditKind, GetDiagnosticSpan(newNode, EditKind.Insert), newNode, arguments: new[] { GetDisplayName(newNode, EditKind.Insert) })); } } #endregion #region Exception Handling Rude Edits /// <summary> /// Return nodes that represent exception handlers encompassing the given active statement node. /// </summary> protected override List<SyntaxNode> GetExceptionHandlingAncestors(SyntaxNode node, bool isNonLeaf) { var result = new List<SyntaxNode>(); var current = node; while (current != null) { var kind = current.Kind(); switch (kind) { case SyntaxKind.TryStatement: if (isNonLeaf) { result.Add(current); } break; case SyntaxKind.CatchClause: case SyntaxKind.FinallyClause: result.Add(current); // skip try: RoslynDebug.Assert(current.Parent is object); RoslynDebug.Assert(current.Parent.Kind() == SyntaxKind.TryStatement); current = current.Parent; break; // stop at type declaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return result; } // stop at lambda: if (LambdaUtilities.IsLambda(current)) { return result; } current = current.Parent; } return result; } internal override void ReportEnclosingExceptionHandlingRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, IEnumerable<Edit<SyntaxNode>> exceptionHandlingEdits, SyntaxNode oldStatement, TextSpan newStatementSpan) { foreach (var edit in exceptionHandlingEdits) { // try/catch/finally have distinct labels so only the nodes of the same kind may match: Debug.Assert(edit.Kind != EditKind.Update || edit.OldNode.RawKind == edit.NewNode.RawKind); if (edit.Kind != EditKind.Update || !AreExceptionClausesEquivalent(edit.OldNode, edit.NewNode)) { AddAroundActiveStatementRudeDiagnostic(diagnostics, edit.OldNode, edit.NewNode, newStatementSpan); } } } private static bool AreExceptionClausesEquivalent(SyntaxNode oldNode, SyntaxNode newNode) { switch (oldNode.Kind()) { case SyntaxKind.TryStatement: var oldTryStatement = (TryStatementSyntax)oldNode; var newTryStatement = (TryStatementSyntax)newNode; return SyntaxFactory.AreEquivalent(oldTryStatement.Finally, newTryStatement.Finally) && SyntaxFactory.AreEquivalent(oldTryStatement.Catches, newTryStatement.Catches); case SyntaxKind.CatchClause: case SyntaxKind.FinallyClause: return SyntaxFactory.AreEquivalent(oldNode, newNode); default: throw ExceptionUtilities.UnexpectedValue(oldNode.Kind()); } } /// <summary> /// An active statement (leaf or not) inside a "catch" makes the catch block read-only. /// An active statement (leaf or not) inside a "finally" makes the whole try/catch/finally block read-only. /// An active statement (non leaf) inside a "try" makes the catch/finally block read-only. /// </summary> /// <remarks> /// Exception handling regions are only needed to be tracked if they contain user code. /// <see cref="UsingStatementSyntax"/> and using <see cref="LocalDeclarationStatementSyntax"/> generate finally blocks, /// but they do not contain non-hidden sequence points. /// </remarks> /// <param name="node">An exception handling ancestor of an active statement node.</param> /// <param name="coversAllChildren"> /// True if all child nodes of the <paramref name="node"/> are contained in the exception region represented by the <paramref name="node"/>. /// </param> protected override TextSpan GetExceptionHandlingRegion(SyntaxNode node, out bool coversAllChildren) { TryStatementSyntax tryStatement; switch (node.Kind()) { case SyntaxKind.TryStatement: tryStatement = (TryStatementSyntax)node; coversAllChildren = false; if (tryStatement.Catches.Count == 0) { RoslynDebug.Assert(tryStatement.Finally != null); return tryStatement.Finally.Span; } return TextSpan.FromBounds( tryStatement.Catches.First().SpanStart, (tryStatement.Finally != null) ? tryStatement.Finally.Span.End : tryStatement.Catches.Last().Span.End); case SyntaxKind.CatchClause: coversAllChildren = true; return node.Span; case SyntaxKind.FinallyClause: coversAllChildren = true; tryStatement = (TryStatementSyntax)node.Parent!; return tryStatement.Span; default: throw ExceptionUtilities.UnexpectedValue(node.Kind()); } } #endregion #region State Machines internal override bool IsStateMachineMethod(SyntaxNode declaration) => SyntaxUtilities.IsAsyncDeclaration(declaration) || SyntaxUtilities.GetSuspensionPoints(declaration).Any(); protected override void GetStateMachineInfo(SyntaxNode body, out ImmutableArray<SyntaxNode> suspensionPoints, out StateMachineKinds kinds) { suspensionPoints = SyntaxUtilities.GetSuspensionPoints(body).ToImmutableArray(); kinds = StateMachineKinds.None; if (suspensionPoints.Any(n => n.IsKind(SyntaxKind.YieldBreakStatement) || n.IsKind(SyntaxKind.YieldReturnStatement))) { kinds |= StateMachineKinds.Iterator; } if (SyntaxUtilities.IsAsyncDeclaration(body.Parent)) { kinds |= StateMachineKinds.Async; } } internal override void ReportStateMachineSuspensionPointRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode) { // TODO: changes around suspension points (foreach, lock, using, etc.) if (newNode.IsKind(SyntaxKind.AwaitExpression)) { var oldContainingStatementPart = FindContainingStatementPart(oldNode); var newContainingStatementPart = FindContainingStatementPart(newNode); // If the old statement has spilled state and the new doesn't the edit is ok. We'll just not use the spilled state. if (!SyntaxFactory.AreEquivalent(oldContainingStatementPart, newContainingStatementPart) && !HasNoSpilledState(newNode, newContainingStatementPart)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.AwaitStatementUpdate, newContainingStatementPart.Span)); } } } internal override void ReportStateMachineSuspensionPointDeletedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode deletedSuspensionPoint) { // Handle deletion of await keyword from await foreach statement. if (deletedSuspensionPoint is CommonForEachStatementSyntax deletedForeachStatement && match.Matches.TryGetValue(deletedSuspensionPoint, out var newForEachStatement) && newForEachStatement is CommonForEachStatementSyntax && deletedForeachStatement.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingFromAsynchronousToSynchronous, GetDiagnosticSpan(newForEachStatement, EditKind.Update), newForEachStatement, new[] { GetDisplayName(newForEachStatement, EditKind.Update) })); return; } // Handle deletion of await keyword from await using declaration. if (deletedSuspensionPoint.IsKind(SyntaxKind.VariableDeclarator) && match.Matches.TryGetValue(deletedSuspensionPoint.Parent!.Parent!, out var newLocalDeclaration) && !((LocalDeclarationStatementSyntax)newLocalDeclaration).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingFromAsynchronousToSynchronous, GetDiagnosticSpan(newLocalDeclaration, EditKind.Update), newLocalDeclaration, new[] { GetDisplayName(newLocalDeclaration, EditKind.Update) })); return; } base.ReportStateMachineSuspensionPointDeletedRudeEdit(diagnostics, match, deletedSuspensionPoint); } internal override void ReportStateMachineSuspensionPointInsertedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode insertedSuspensionPoint, bool aroundActiveStatement) { // Handle addition of await keyword to foreach statement. if (insertedSuspensionPoint is CommonForEachStatementSyntax insertedForEachStatement && match.ReverseMatches.TryGetValue(insertedSuspensionPoint, out var oldNode) && oldNode is CommonForEachStatementSyntax oldForEachStatement && !oldForEachStatement.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Insert, insertedForEachStatement.AwaitKeyword.Span, insertedForEachStatement, new[] { insertedForEachStatement.AwaitKeyword.ToString() })); return; } // Handle addition of using keyword to using declaration. if (insertedSuspensionPoint.IsKind(SyntaxKind.VariableDeclarator) && match.ReverseMatches.TryGetValue(insertedSuspensionPoint.Parent!.Parent!, out var oldLocalDeclaration) && !((LocalDeclarationStatementSyntax)oldLocalDeclaration).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) { var newLocalDeclaration = (LocalDeclarationStatementSyntax)insertedSuspensionPoint!.Parent!.Parent!; diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Insert, newLocalDeclaration.AwaitKeyword.Span, newLocalDeclaration, new[] { newLocalDeclaration.AwaitKeyword.ToString() })); return; } base.ReportStateMachineSuspensionPointInsertedRudeEdit(diagnostics, match, insertedSuspensionPoint, aroundActiveStatement); } private static SyntaxNode FindContainingStatementPart(SyntaxNode node) { while (true) { if (node is StatementSyntax statement) { return statement; } RoslynDebug.Assert(node is object); RoslynDebug.Assert(node.Parent is object); switch (node.Parent.Kind()) { case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.IfStatement: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.LockStatement: case SyntaxKind.UsingStatement: case SyntaxKind.ArrowExpressionClause: return node; } if (LambdaUtilities.IsLambdaBodyStatementOrExpression(node)) { return node; } node = node.Parent; } } private static bool HasNoSpilledState(SyntaxNode awaitExpression, SyntaxNode containingStatementPart) { Debug.Assert(awaitExpression.IsKind(SyntaxKind.AwaitExpression)); // There is nothing within the statement part surrounding the await expression. if (containingStatementPart == awaitExpression) { return true; } switch (containingStatementPart.Kind()) { case SyntaxKind.ExpressionStatement: case SyntaxKind.ReturnStatement: var expression = GetExpressionFromStatementPart(containingStatementPart); // await expr; // return await expr; if (expression == awaitExpression) { return true; } // identifier = await expr; // return identifier = await expr; return IsSimpleAwaitAssignment(expression, awaitExpression); case SyntaxKind.VariableDeclaration: // var idf = await expr in using, for, etc. // EqualsValueClause -> VariableDeclarator -> VariableDeclaration return awaitExpression.Parent!.Parent!.Parent == containingStatementPart; case SyntaxKind.LocalDeclarationStatement: // var idf = await expr; // EqualsValueClause -> VariableDeclarator -> VariableDeclaration -> LocalDeclarationStatement return awaitExpression.Parent!.Parent!.Parent!.Parent == containingStatementPart; } return IsSimpleAwaitAssignment(containingStatementPart, awaitExpression); } private static ExpressionSyntax GetExpressionFromStatementPart(SyntaxNode statement) { switch (statement.Kind()) { case SyntaxKind.ExpressionStatement: return ((ExpressionStatementSyntax)statement).Expression; case SyntaxKind.ReturnStatement: // Must have an expression since we are only inspecting at statements that contain an expression. return ((ReturnStatementSyntax)statement).Expression!; default: throw ExceptionUtilities.UnexpectedValue(statement.Kind()); } } private static bool IsSimpleAwaitAssignment(SyntaxNode node, SyntaxNode awaitExpression) { if (node.IsKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment)) { return assignment.Left.IsKind(SyntaxKind.IdentifierName) && assignment.Right == awaitExpression; } return false; } #endregion #region Rude Edits around Active Statement internal override void ReportOtherRudeEditsAroundActiveStatement( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement, bool isNonLeaf) { ReportRudeEditsForSwitchWhenClauses(diagnostics, oldActiveStatement, newActiveStatement); ReportRudeEditsForAncestorsDeclaringInterStatementTemps(diagnostics, match, oldActiveStatement, newActiveStatement); ReportRudeEditsForCheckedStatements(diagnostics, oldActiveStatement, newActiveStatement, isNonLeaf); } /// <summary> /// Reports rude edits when an active statement is a when clause in a switch statement and any of the switch cases or the switch value changed. /// This is necessary since the switch emits long-lived synthesized variables to store results of pattern evaluations. /// These synthesized variables are mapped to the slots of the new methods via ordinals. The mapping preserves the values of these variables as long as /// exactly the same variables are emitted for the new switch as they were for the old one and their order didn't change either. /// This is guaranteed if none of the case clauses have changed. /// </summary> private void ReportRudeEditsForSwitchWhenClauses(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement) { if (!oldActiveStatement.IsKind(SyntaxKind.WhenClause)) { return; } // switch expression does not have sequence points (active statements): if (oldActiveStatement.Parent!.Parent!.Parent is not SwitchStatementSyntax oldSwitch) { return; } // switch statement does not match switch expression, so it must be part of a switch statement as well. var newSwitch = (SwitchStatementSyntax)newActiveStatement.Parent!.Parent!.Parent!; // when clauses can only match other when clauses: Debug.Assert(newActiveStatement.IsKind(SyntaxKind.WhenClause)); if (!AreEquivalentIgnoringLambdaBodies(oldSwitch.Expression, newSwitch.Expression)) { AddRudeUpdateAroundActiveStatement(diagnostics, newSwitch); } if (!AreEquivalentSwitchStatementDecisionTrees(oldSwitch, newSwitch)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdateAroundActiveStatement, GetDiagnosticSpan(newSwitch, EditKind.Update), newSwitch, new[] { CSharpFeaturesResources.switch_statement_case_clause })); } } private static bool AreEquivalentSwitchStatementDecisionTrees(SwitchStatementSyntax oldSwitch, SwitchStatementSyntax newSwitch) => oldSwitch.Sections.SequenceEqual(newSwitch.Sections, AreSwitchSectionsEquivalent); private static bool AreSwitchSectionsEquivalent(SwitchSectionSyntax oldSection, SwitchSectionSyntax newSection) => oldSection.Labels.SequenceEqual(newSection.Labels, AreLabelsEquivalent); private static bool AreLabelsEquivalent(SwitchLabelSyntax oldLabel, SwitchLabelSyntax newLabel) { if (oldLabel.IsKind(SyntaxKind.CasePatternSwitchLabel, out CasePatternSwitchLabelSyntax? oldCasePatternLabel) && newLabel.IsKind(SyntaxKind.CasePatternSwitchLabel, out CasePatternSwitchLabelSyntax? newCasePatternLabel)) { // ignore the actual when expressions: return SyntaxFactory.AreEquivalent(oldCasePatternLabel.Pattern, newCasePatternLabel.Pattern) && (oldCasePatternLabel.WhenClause != null) == (newCasePatternLabel.WhenClause != null); } else { return SyntaxFactory.AreEquivalent(oldLabel, newLabel); } } private void ReportRudeEditsForCheckedStatements( ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement, bool isNonLeaf) { // checked context can't be changed around non-leaf active statement: if (!isNonLeaf) { return; } // Changing checked context around an internal active statement may change the instructions // executed after method calls in the active statement but before the next sequence point. // Since the debugger remaps the IP at the first sequence point following a call instruction // allowing overflow context to be changed may lead to execution of code with old semantics. var oldCheckedStatement = TryGetCheckedStatementAncestor(oldActiveStatement); var newCheckedStatement = TryGetCheckedStatementAncestor(newActiveStatement); bool isRude; if (oldCheckedStatement == null || newCheckedStatement == null) { isRude = oldCheckedStatement != newCheckedStatement; } else { isRude = oldCheckedStatement.Kind() != newCheckedStatement.Kind(); } if (isRude) { AddAroundActiveStatementRudeDiagnostic(diagnostics, oldCheckedStatement, newCheckedStatement, newActiveStatement.Span); } } private static CheckedStatementSyntax? TryGetCheckedStatementAncestor(SyntaxNode? node) { // Ignoring lambda boundaries since checked context flows through. while (node != null) { switch (node.Kind()) { case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return (CheckedStatementSyntax)node; } node = node.Parent; } return null; } private void ReportRudeEditsForAncestorsDeclaringInterStatementTemps( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement) { // Rude Edits for fixed/using/lock/foreach statements that are added/updated around an active statement. // Although such changes are technically possible, they might lead to confusion since // the temporary variables these statements generate won't be properly initialized. // // We use a simple algorithm to match each new node with its old counterpart. // If all nodes match this algorithm is linear, otherwise it's quadratic. // // Unlike exception regions matching where we use LCS, we allow reordering of the statements. ReportUnmatchedStatements<LockStatementSyntax>(diagnostics, match, n => n.IsKind(SyntaxKind.LockStatement), oldActiveStatement, newActiveStatement, areEquivalent: AreEquivalentActiveStatements, areSimilar: null); ReportUnmatchedStatements<FixedStatementSyntax>(diagnostics, match, n => n.IsKind(SyntaxKind.FixedStatement), oldActiveStatement, newActiveStatement, areEquivalent: AreEquivalentActiveStatements, areSimilar: (n1, n2) => DeclareSameIdentifiers(n1.Declaration.Variables, n2.Declaration.Variables)); // Using statements with declaration do not introduce compiler generated temporary. ReportUnmatchedStatements<UsingStatementSyntax>( diagnostics, match, n => n.IsKind(SyntaxKind.UsingStatement, out UsingStatementSyntax? usingStatement) && usingStatement.Declaration is null, oldActiveStatement, newActiveStatement, areEquivalent: AreEquivalentActiveStatements, areSimilar: null); ReportUnmatchedStatements<CommonForEachStatementSyntax>( diagnostics, match, n => n.IsKind(SyntaxKind.ForEachStatement) || n.IsKind(SyntaxKind.ForEachVariableStatement), oldActiveStatement, newActiveStatement, areEquivalent: AreEquivalentActiveStatements, areSimilar: AreSimilarActiveStatements); } private static bool DeclareSameIdentifiers(SeparatedSyntaxList<VariableDeclaratorSyntax> oldVariables, SeparatedSyntaxList<VariableDeclaratorSyntax> newVariables) => DeclareSameIdentifiers(oldVariables.Select(v => v.Identifier).ToArray(), newVariables.Select(v => v.Identifier).ToArray()); private static bool DeclareSameIdentifiers(SyntaxToken[] oldVariables, SyntaxToken[] newVariables) { if (oldVariables.Length != newVariables.Length) { return false; } for (var i = 0; i < oldVariables.Length; i++) { if (!SyntaxFactory.AreEquivalent(oldVariables[i], newVariables[i])) { return false; } } return true; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue { internal sealed class CSharpEditAndContinueAnalyzer : AbstractEditAndContinueAnalyzer { [ExportLanguageServiceFactory(typeof(IEditAndContinueAnalyzer), LanguageNames.CSharp), Shared] internal sealed class Factory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } public ILanguageService CreateLanguageService(HostLanguageServices languageServices) { return new CSharpEditAndContinueAnalyzer(testFaultInjector: null); } } // Public for testing purposes public CSharpEditAndContinueAnalyzer(Action<SyntaxNode>? testFaultInjector = null) : base(testFaultInjector) { } #region Syntax Analysis private enum BlockPart { OpenBrace = DefaultStatementPart, CloseBrace = 1, } private enum ForEachPart { ForEach = DefaultStatementPart, VariableDeclaration = 1, In = 2, Expression = 3, } private enum SwitchExpressionPart { WholeExpression = DefaultStatementPart, // An active statement that covers IL generated for the decision tree: // <governing-expression> [|switch { <arm>, ..., <arm> }|] // This active statement is never a leaf active statement (does not correspond to a breakpoint span). SwitchBody = 1, } /// <returns> /// <see cref="BaseMethodDeclarationSyntax"/> for methods, operators, constructors, destructors and accessors. /// <see cref="VariableDeclaratorSyntax"/> for field initializers. /// <see cref="PropertyDeclarationSyntax"/> for property initializers and expression bodies. /// <see cref="IndexerDeclarationSyntax"/> for indexer expression bodies. /// <see cref="ArrowExpressionClauseSyntax"/> for getter of an expression-bodied property/indexer. /// </returns> internal override bool TryFindMemberDeclaration(SyntaxNode? root, SyntaxNode node, out OneOrMany<SyntaxNode> declarations) { var current = node; while (current != null && current != root) { switch (current.Kind()) { case SyntaxKind.MethodDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: declarations = new(current); return true; case SyntaxKind.PropertyDeclaration: // int P { get; } = [|initializer|]; RoslynDebug.Assert(((PropertyDeclarationSyntax)current).Initializer != null); declarations = new(current); return true; case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: // Active statements encompassing modifiers or type correspond to the first initialized field. // [|public static int F = 1|], G = 2; declarations = new(((BaseFieldDeclarationSyntax)current).Declaration.Variables.First()); return true; case SyntaxKind.VariableDeclarator: // public static int F = 1, [|G = 2|]; RoslynDebug.Assert(current.Parent.IsKind(SyntaxKind.VariableDeclaration)); switch (current.Parent.Parent!.Kind()) { case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: declarations = new(current); return true; } current = current.Parent; break; case SyntaxKind.ArrowExpressionClause: // represents getter symbol declaration node of a property/indexer with expression body if (current.Parent.IsKind(SyntaxKind.PropertyDeclaration, SyntaxKind.IndexerDeclaration)) { declarations = new(current); return true; } break; } current = current.Parent; } declarations = default; return false; } /// <returns> /// Given a node representing a declaration or a top-level match node returns: /// - <see cref="BlockSyntax"/> for method-like member declarations with block bodies (methods, operators, constructors, destructors, accessors). /// - <see cref="ExpressionSyntax"/> for variable declarators of fields, properties with an initializer expression, or /// for method-like member declarations with expression bodies (methods, properties, indexers, operators) /// - <see cref="CompilationUnitSyntax"/> for top level statements /// /// A null reference otherwise. /// </returns> internal override SyntaxNode? TryGetDeclarationBody(SyntaxNode node) { if (node.IsKind(SyntaxKind.VariableDeclarator, out VariableDeclaratorSyntax? variableDeclarator)) { return variableDeclarator.Initializer?.Value; } if (node is CompilationUnitSyntax unit && unit.ContainsTopLevelStatements()) { // For top level statements, where there is no syntax node to represent the entire body of the synthesized // main method we just use the compilation unit itself return node; } return SyntaxUtilities.TryGetMethodDeclarationBody(node); } internal override bool IsDeclarationWithSharedBody(SyntaxNode declaration) => false; protected override ImmutableArray<ISymbol> GetCapturedVariables(SemanticModel model, SyntaxNode memberBody) { if (memberBody is CompilationUnitSyntax unit && unit.ContainsTopLevelStatements()) { return model.AnalyzeDataFlow(((GlobalStatementSyntax)unit.Members[0]).Statement, unit.Members.OfType<GlobalStatementSyntax>().Last().Statement)!.Captured; } Debug.Assert(memberBody.IsKind(SyntaxKind.Block) || memberBody is ExpressionSyntax); return model.AnalyzeDataFlow(memberBody).Captured; } protected override bool AreHandledEventsEqual(IMethodSymbol oldMethod, IMethodSymbol newMethod) => true; internal override bool HasParameterClosureScope(ISymbol member) { // in instance constructor parameters are lifted to a closure different from method body return (member as IMethodSymbol)?.MethodKind == MethodKind.Constructor; } protected override IEnumerable<SyntaxNode> GetVariableUseSites(IEnumerable<SyntaxNode> roots, ISymbol localOrParameter, SemanticModel model, CancellationToken cancellationToken) { Debug.Assert(localOrParameter is IParameterSymbol || localOrParameter is ILocalSymbol || localOrParameter is IRangeVariableSymbol); // not supported (it's non trivial to find all places where "this" is used): Debug.Assert(!localOrParameter.IsThisParameter()); return from root in roots from node in root.DescendantNodesAndSelf() where node.IsKind(SyntaxKind.IdentifierName) let nameSyntax = (IdentifierNameSyntax)node where (string?)nameSyntax.Identifier.Value == localOrParameter.Name && (model.GetSymbolInfo(nameSyntax, cancellationToken).Symbol?.Equals(localOrParameter) ?? false) select node; } /// <returns> /// If <paramref name="node"/> is a method, accessor, operator, destructor, or constructor without an initializer, /// tokens of its block body, or tokens of the expression body. /// /// If <paramref name="node"/> is an indexer declaration the tokens of its expression body. /// /// If <paramref name="node"/> is a property declaration the tokens of its expression body or initializer. /// /// If <paramref name="node"/> is a constructor with an initializer, /// tokens of the initializer concatenated with tokens of the constructor body. /// /// If <paramref name="node"/> is a variable declarator of a field with an initializer, /// subset of the tokens of the field declaration depending on which variable declarator it is. /// /// Null reference otherwise. /// </returns> internal override IEnumerable<SyntaxToken>? TryGetActiveTokens(SyntaxNode node) { if (node.IsKind(SyntaxKind.VariableDeclarator)) { // TODO: The logic is similar to BreakpointSpans.TryCreateSpanForVariableDeclaration. Can we abstract it? var declarator = node; var fieldDeclaration = (BaseFieldDeclarationSyntax)declarator.Parent!.Parent!; var variableDeclaration = fieldDeclaration.Declaration; if (fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword)) { return null; } if (variableDeclaration.Variables.Count == 1) { if (variableDeclaration.Variables[0].Initializer == null) { return null; } return fieldDeclaration.Modifiers.Concat(variableDeclaration.DescendantTokens()).Concat(fieldDeclaration.SemicolonToken); } if (declarator == variableDeclaration.Variables[0]) { return fieldDeclaration.Modifiers.Concat(variableDeclaration.Type.DescendantTokens()).Concat(node.DescendantTokens()); } return declarator.DescendantTokens(); } if (node is PropertyDeclarationSyntax { ExpressionBody: var propertyExpressionBody and not null }) { return propertyExpressionBody.Expression.DescendantTokens(); } if (node is IndexerDeclarationSyntax { ExpressionBody: var indexerExpressionBody and not null }) { return indexerExpressionBody.Expression.DescendantTokens(); } var bodyTokens = SyntaxUtilities.TryGetMethodDeclarationBody(node)?.DescendantTokens(); if (node.IsKind(SyntaxKind.ConstructorDeclaration, out ConstructorDeclarationSyntax? ctor)) { if (ctor.Initializer != null) { bodyTokens = ctor.Initializer.DescendantTokens().Concat(bodyTokens ?? Enumerable.Empty<SyntaxToken>()); } } return bodyTokens; } internal override (TextSpan envelope, TextSpan hole) GetActiveSpanEnvelope(SyntaxNode declaration) => (BreakpointSpans.GetEnvelope(declaration), default); protected override SyntaxNode GetEncompassingAncestorImpl(SyntaxNode bodyOrMatchRoot) { // Constructor may contain active nodes outside of its body (constructor initializer), // but within the body of the member declaration (the parent). if (bodyOrMatchRoot.Parent.IsKind(SyntaxKind.ConstructorDeclaration)) { return bodyOrMatchRoot.Parent; } // Field initializer match root -- an active statement may include the modifiers // and type specification of the field declaration. if (bodyOrMatchRoot.IsKind(SyntaxKind.EqualsValueClause) && bodyOrMatchRoot.Parent.IsKind(SyntaxKind.VariableDeclarator) && bodyOrMatchRoot.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration)) { return bodyOrMatchRoot.Parent.Parent; } // Field initializer body -- an active statement may include the modifiers // and type specification of the field declaration. if (bodyOrMatchRoot.Parent.IsKind(SyntaxKind.EqualsValueClause) && bodyOrMatchRoot.Parent.Parent.IsKind(SyntaxKind.VariableDeclarator) && bodyOrMatchRoot.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration)) { return bodyOrMatchRoot.Parent.Parent.Parent; } // otherwise all active statements are covered by the body/match root itself: return bodyOrMatchRoot; } protected override SyntaxNode FindStatementAndPartner(SyntaxNode declarationBody, TextSpan span, SyntaxNode? partnerDeclarationBody, out SyntaxNode? partner, out int statementPart) { var position = span.Start; SyntaxUtilities.AssertIsBody(declarationBody, allowLambda: false); if (position < declarationBody.SpanStart) { // Only constructors and the field initializers may have an [|active statement|] starting outside of the <<body>>. // Constructor: [|public C()|] <<{ }>> // Constructor initializer: public C() : [|base(expr)|] <<{ }>> // Constructor initializer with lambda: public C() : base(() => { [|...|] }) <<{ }>> // Field initializers: [|public int a = <<expr>>|], [|b = <<expr>>|]; // No need to special case property initializers here, the active statement always spans the initializer expression. if (declarationBody.Parent.IsKind(SyntaxKind.ConstructorDeclaration)) { var constructor = (ConstructorDeclarationSyntax)declarationBody.Parent; var partnerConstructor = (ConstructorDeclarationSyntax?)partnerDeclarationBody?.Parent; if (constructor.Initializer == null || position < constructor.Initializer.ColonToken.SpanStart) { statementPart = DefaultStatementPart; partner = partnerConstructor; return constructor; } declarationBody = constructor.Initializer; partnerDeclarationBody = partnerConstructor?.Initializer; } } if (!declarationBody.FullSpan.Contains(position)) { // invalid position, let's find a labeled node that encompasses the body: position = declarationBody.SpanStart; } SyntaxNode node; if (partnerDeclarationBody != null) { SyntaxUtilities.FindLeafNodeAndPartner(declarationBody, position, partnerDeclarationBody, out node, out partner); } else { node = declarationBody.FindToken(position).Parent!; partner = null; } while (true) { var isBody = node == declarationBody || LambdaUtilities.IsLambdaBodyStatementOrExpression(node); if (isBody || SyntaxComparer.Statement.HasLabel(node)) { switch (node.Kind()) { case SyntaxKind.Block: statementPart = (int)GetStatementPart((BlockSyntax)node, position); return node; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: Debug.Assert(!isBody); statementPart = (int)GetStatementPart((CommonForEachStatementSyntax)node, position); return node; case SyntaxKind.DoStatement: // The active statement of DoStatement node is the while condition, // which is lexically not the closest breakpoint span (the body is). // do { ... } [|while (condition);|] Debug.Assert(position == ((DoStatementSyntax)node).WhileKeyword.SpanStart); Debug.Assert(!isBody); goto default; case SyntaxKind.PropertyDeclaration: // The active span corresponding to a property declaration is the span corresponding to its initializer (if any), // not the span corresponding to the accessor. // int P { [|get;|] } = [|<initializer>|]; Debug.Assert(position == ((PropertyDeclarationSyntax)node).Initializer!.SpanStart); goto default; case SyntaxKind.VariableDeclaration: // VariableDeclaration ::= TypeSyntax CommaSeparatedList(VariableDeclarator) // // The compiler places sequence points after each local variable initialization. // The TypeSyntax is considered to be part of the first sequence span. Debug.Assert(!isBody); node = ((VariableDeclarationSyntax)node).Variables.First(); if (partner != null) { partner = ((VariableDeclarationSyntax)partner).Variables.First(); } statementPart = DefaultStatementPart; return node; case SyntaxKind.SwitchExpression: // An active statement that covers IL generated for the decision tree: // <governing-expression> [|switch { <arm>, ..., <arm> }|] // This active statement is never a leaf active statement (does not correspond to a breakpoint span). var switchExpression = (SwitchExpressionSyntax)node; if (position == switchExpression.SwitchKeyword.SpanStart) { Debug.Assert(span.End == switchExpression.CloseBraceToken.Span.End); statementPart = (int)SwitchExpressionPart.SwitchBody; return node; } // The switch expression itself can be (a part of) an active statement associated with the containing node // For example, when it is used as a switch arm expression like so: // <expr> switch { <pattern> [|when <expr> switch { ... }|] ... } Debug.Assert(position == switchExpression.Span.Start); if (isBody) { goto default; } // ascend to parent node: break; case SyntaxKind.SwitchExpressionArm: // An active statement may occur in the when clause and in the arm expression: // <constant-pattern> [|when <condition>|] => [|<expression>|] // The former is covered by when-clause node - it's a labeled node. // The latter isn't enclosed in a distinct labeled syntax node and thus needs to be covered // by the arm node itself. Debug.Assert(position == ((SwitchExpressionArmSyntax)node).Expression.SpanStart); Debug.Assert(!isBody); goto default; default: statementPart = DefaultStatementPart; return node; } } node = node.Parent!; if (partner != null) { partner = partner.Parent; } } } private static BlockPart GetStatementPart(BlockSyntax node, int position) => position < node.OpenBraceToken.Span.End ? BlockPart.OpenBrace : BlockPart.CloseBrace; private static TextSpan GetActiveSpan(BlockSyntax node, BlockPart part) => part switch { BlockPart.OpenBrace => node.OpenBraceToken.Span, BlockPart.CloseBrace => node.CloseBraceToken.Span, _ => throw ExceptionUtilities.UnexpectedValue(part), }; private static ForEachPart GetStatementPart(CommonForEachStatementSyntax node, int position) => position < node.OpenParenToken.SpanStart ? ForEachPart.ForEach : position < node.InKeyword.SpanStart ? ForEachPart.VariableDeclaration : position < node.Expression.SpanStart ? ForEachPart.In : ForEachPart.Expression; private static TextSpan GetActiveSpan(ForEachStatementSyntax node, ForEachPart part) => part switch { ForEachPart.ForEach => node.ForEachKeyword.Span, ForEachPart.VariableDeclaration => TextSpan.FromBounds(node.Type.SpanStart, node.Identifier.Span.End), ForEachPart.In => node.InKeyword.Span, ForEachPart.Expression => node.Expression.Span, _ => throw ExceptionUtilities.UnexpectedValue(part), }; private static TextSpan GetActiveSpan(ForEachVariableStatementSyntax node, ForEachPart part) => part switch { ForEachPart.ForEach => node.ForEachKeyword.Span, ForEachPart.VariableDeclaration => TextSpan.FromBounds(node.Variable.SpanStart, node.Variable.Span.End), ForEachPart.In => node.InKeyword.Span, ForEachPart.Expression => node.Expression.Span, _ => throw ExceptionUtilities.UnexpectedValue(part), }; private static TextSpan GetActiveSpan(SwitchExpressionSyntax node, SwitchExpressionPart part) => part switch { SwitchExpressionPart.WholeExpression => node.Span, SwitchExpressionPart.SwitchBody => TextSpan.FromBounds(node.SwitchKeyword.SpanStart, node.CloseBraceToken.Span.End), _ => throw ExceptionUtilities.UnexpectedValue(part), }; protected override bool AreEquivalent(SyntaxNode left, SyntaxNode right) => SyntaxFactory.AreEquivalent(left, right); private static bool AreEquivalentIgnoringLambdaBodies(SyntaxNode left, SyntaxNode right) { // usual case: if (SyntaxFactory.AreEquivalent(left, right)) { return true; } return LambdaUtilities.AreEquivalentIgnoringLambdaBodies(left, right); } internal override SyntaxNode FindDeclarationBodyPartner(SyntaxNode leftRoot, SyntaxNode rightRoot, SyntaxNode leftNode) => SyntaxUtilities.FindPartner(leftRoot, rightRoot, leftNode); internal override bool IsClosureScope(SyntaxNode node) => LambdaUtilities.IsClosureScope(node); protected override SyntaxNode? FindEnclosingLambdaBody(SyntaxNode? container, SyntaxNode node) { var root = GetEncompassingAncestor(container); var current = node; while (current != root && current != null) { if (LambdaUtilities.IsLambdaBodyStatementOrExpression(current, out var body)) { return body; } current = current.Parent; } return null; } protected override IEnumerable<SyntaxNode> GetLambdaBodyExpressionsAndStatements(SyntaxNode lambdaBody) => SpecializedCollections.SingletonEnumerable(lambdaBody); protected override SyntaxNode? TryGetPartnerLambdaBody(SyntaxNode oldBody, SyntaxNode newLambda) => LambdaUtilities.TryGetCorrespondingLambdaBody(oldBody, newLambda); protected override Match<SyntaxNode> ComputeTopLevelMatch(SyntaxNode oldCompilationUnit, SyntaxNode newCompilationUnit) => SyntaxComparer.TopLevel.ComputeMatch(oldCompilationUnit, newCompilationUnit); protected override Match<SyntaxNode> ComputeTopLevelDeclarationMatch(SyntaxNode oldDeclaration, SyntaxNode newDeclaration) { Contract.ThrowIfNull(oldDeclaration.Parent); Contract.ThrowIfNull(newDeclaration.Parent); var comparer = new SyntaxComparer(oldDeclaration.Parent, newDeclaration.Parent, new[] { oldDeclaration }, new[] { newDeclaration }, compareStatementSyntax: false); return comparer.ComputeMatch(oldDeclaration.Parent, newDeclaration.Parent); } protected override Match<SyntaxNode> ComputeBodyMatch(SyntaxNode oldBody, SyntaxNode newBody, IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>>? knownMatches) { SyntaxUtilities.AssertIsBody(oldBody, allowLambda: true); SyntaxUtilities.AssertIsBody(newBody, allowLambda: true); if (oldBody is ExpressionSyntax || newBody is ExpressionSyntax || (oldBody.Parent.IsKind(SyntaxKind.LocalFunctionStatement) && newBody.Parent.IsKind(SyntaxKind.LocalFunctionStatement))) { Debug.Assert(oldBody is ExpressionSyntax || oldBody is BlockSyntax); Debug.Assert(newBody is ExpressionSyntax || newBody is BlockSyntax); // The matching algorithm requires the roots to match each other. // Lambda bodies, field/property initializers, and method/property/indexer/operator expression-bodies may also be lambda expressions. // Say we have oldBody 'x => x' and newBody 'F(x => x + 1)', then // the algorithm would match 'x => x' to 'F(x => x + 1)' instead of // matching 'x => x' to 'x => x + 1'. // We use the parent node as a root: // - for field/property initializers the root is EqualsValueClause. // - for member expression-bodies the root is ArrowExpressionClauseSyntax. // - for block bodies the root is a method/operator/accessor declaration (only happens when matching expression body with a block body) // - for lambdas the root is a LambdaExpression. // - for query lambdas the root is the query clause containing the lambda (e.g. where). // - for local functions the root is LocalFunctionStatement. static SyntaxNode GetMatchingRoot(SyntaxNode body) { var parent = body.Parent!; // We could apply this change across all ArrowExpressionClause consistently not just for ones with LocalFunctionStatement parents // but it would require an essential refactoring. return parent.IsKind(SyntaxKind.ArrowExpressionClause) && parent.Parent.IsKind(SyntaxKind.LocalFunctionStatement) ? parent.Parent : parent; } var oldRoot = GetMatchingRoot(oldBody); var newRoot = GetMatchingRoot(newBody); return new SyntaxComparer(oldRoot, newRoot, GetChildNodes(oldRoot, oldBody), GetChildNodes(newRoot, newBody), compareStatementSyntax: true).ComputeMatch(oldRoot, newRoot, knownMatches); } if (oldBody.Parent.IsKind(SyntaxKind.ConstructorDeclaration)) { // We need to include constructor initializer in the match, since it may contain lambdas. // Use the constructor declaration as a root. RoslynDebug.Assert(oldBody.IsKind(SyntaxKind.Block)); RoslynDebug.Assert(newBody.IsKind(SyntaxKind.Block)); RoslynDebug.Assert(newBody.Parent.IsKind(SyntaxKind.ConstructorDeclaration)); RoslynDebug.Assert(newBody.Parent is object); return SyntaxComparer.Statement.ComputeMatch(oldBody.Parent, newBody.Parent, knownMatches); } return SyntaxComparer.Statement.ComputeMatch(oldBody, newBody, knownMatches); } private static IEnumerable<SyntaxNode> GetChildNodes(SyntaxNode root, SyntaxNode body) { if (root is LocalFunctionStatementSyntax localFunc) { // local functions have multiple children we need to process for matches, but we won't automatically // descend into them, assuming they're nested, so we override the default behaviour and return // multiple children foreach (var attributeList in localFunc.AttributeLists) { yield return attributeList; } yield return localFunc.ReturnType; if (localFunc.TypeParameterList is not null) { yield return localFunc.TypeParameterList; } yield return localFunc.ParameterList; if (localFunc.Body is not null) { yield return localFunc.Body; } else if (localFunc.ExpressionBody is not null) { // Skip the ArrowExpressionClause that is ExressionBody and just return the expression itself yield return localFunc.ExpressionBody.Expression; } } else { yield return body; } } internal override void ReportDeclarationInsertDeleteRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode, ISymbol oldSymbol, ISymbol newSymbol, EditAndContinueCapabilities capabilities, CancellationToken cancellationToken) { // Global statements have a declaring syntax reference to the compilation unit itself, which we can just ignore // for the purposes of declaration rude edits if (oldNode.IsKind(SyntaxKind.CompilationUnit) || newNode.IsKind(SyntaxKind.CompilationUnit)) { return; } // Compiler generated methods of records have a declaring syntax reference to the record declaration itself // but their explicitly implemented counterparts reference the actual member. Compiler generated properties // of records reference the parameter that names them. // // Since there is no useful "old" syntax node for these members, we can't compute declaration or body edits // using the standard tree comparison code. // // Based on this, we can detect a new explicit implementation of a record member by checking if the // declaration kind has changed. If it hasn't changed, then our standard code will handle it. if (oldNode.RawKind == newNode.RawKind) { base.ReportDeclarationInsertDeleteRudeEdits(diagnostics, oldNode, newNode, oldSymbol, newSymbol, capabilities, cancellationToken); return; } // When explicitly implementing a property that is represented by a positional parameter // what looks like an edit could actually be a rude delete, or something else if (oldNode is ParameterSyntax && newNode is PropertyDeclarationSyntax property) { if (property.AccessorList!.Accessors.Count == 1) { // Explicitly implementing a property with only one accessor is a delete of the init accessor, so a rude edit. // Not implementing the get accessor would be a compile error diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ImplementRecordParameterAsReadOnly, GetDiagnosticSpan(newNode, EditKind.Delete), oldNode, new[] { property.Identifier.ToString() })); } else if (property.AccessorList.Accessors.Any(a => a.IsKind(SyntaxKind.SetAccessorDeclaration))) { // The compiler implements the properties with an init accessor so explicitly implementing // it with a set accessor is a rude accessor change edit diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ImplementRecordParameterWithSet, GetDiagnosticSpan(newNode, EditKind.Delete), oldNode, new[] { property.Identifier.ToString() })); } } else if (oldNode is RecordDeclarationSyntax && newNode is MethodDeclarationSyntax && !capabilities.HasFlag(EditAndContinueCapabilities.UpdateParameters) && !oldSymbol.GetParameters().Select(p => p.Name).SequenceEqual(newSymbol.GetParameters().Select(p => p.Name))) { // Explicitly implemented methods must have parameter names that match the compiler generated versions // exactly if the runtime doesn't support updating parameters, otherwise the debugger would show incorrect // parameter names. // We don't need to worry about parameter types, because if they were different then we wouldn't get here // as this wouldn't be the explicit implementation of a known method. // We don't need to worry about access modifiers because the symbol matching still works, and most of the // time changing access modifiers for these known methods is a compile error anyway. diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, GetDiagnosticSpan(newNode, EditKind.Update), oldNode, new[] { oldSymbol.ToDisplayString(SymbolDisplayFormats.NameFormat) })); } } protected override void ReportLocalFunctionsDeclarationRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> bodyMatch) { var bodyEditsForLambda = bodyMatch.GetTreeEdits(); var editMap = BuildEditMap(bodyEditsForLambda); foreach (var edit in bodyEditsForLambda.Edits) { if (HasParentEdit(editMap, edit)) { return; } var classifier = new EditClassifier(this, diagnostics, edit.OldNode, edit.NewNode, edit.Kind, bodyMatch); classifier.ClassifyEdit(); } } protected override bool TryMatchActiveStatement( SyntaxNode oldStatement, int statementPart, SyntaxNode oldBody, SyntaxNode newBody, [NotNullWhen(true)] out SyntaxNode? newStatement) { SyntaxUtilities.AssertIsBody(oldBody, allowLambda: true); SyntaxUtilities.AssertIsBody(newBody, allowLambda: true); switch (oldStatement.Kind()) { case SyntaxKind.ThisConstructorInitializer: case SyntaxKind.BaseConstructorInitializer: case SyntaxKind.ConstructorDeclaration: var newConstructor = (ConstructorDeclarationSyntax)(newBody.Parent.IsKind(SyntaxKind.ArrowExpressionClause) ? newBody.Parent.Parent : newBody.Parent)!; newStatement = (SyntaxNode?)newConstructor.Initializer ?? newConstructor; return true; default: // TODO: Consider mapping an expression body to an equivalent statement expression or return statement and vice versa. // It would benefit transformations of expression bodies to block bodies of lambdas, methods, operators and properties. // See https://github.com/dotnet/roslyn/issues/22696 // field initializer, lambda and query expressions: if (oldStatement == oldBody && !newBody.IsKind(SyntaxKind.Block)) { newStatement = newBody; return true; } newStatement = null; return false; } } #endregion #region Syntax and Semantic Utils protected override TextSpan GetGlobalStatementDiagnosticSpan(SyntaxNode node) { if (node is CompilationUnitSyntax unit) { // When deleting something from a compilation unit we just report diagnostics for the last global statement return unit.Members.OfType<GlobalStatementSyntax>().LastOrDefault()?.Span ?? default; } return GetDiagnosticSpan(node, EditKind.Delete); } protected override string LineDirectiveKeyword => "line"; protected override ushort LineDirectiveSyntaxKind => (ushort)SyntaxKind.LineDirectiveTrivia; protected override IEnumerable<SequenceEdit> GetSyntaxSequenceEdits(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes) => SyntaxComparer.GetSequenceEdits(oldNodes, newNodes); internal override SyntaxNode EmptyCompilationUnit => SyntaxFactory.CompilationUnit(); // there are no experimental features at this time. internal override bool ExperimentalFeaturesEnabled(SyntaxTree tree) => false; protected override bool StateMachineSuspensionPointKindEquals(SyntaxNode suspensionPoint1, SyntaxNode suspensionPoint2) => (suspensionPoint1 is CommonForEachStatementSyntax) ? suspensionPoint2 is CommonForEachStatementSyntax : suspensionPoint1.RawKind == suspensionPoint2.RawKind; protected override bool StatementLabelEquals(SyntaxNode node1, SyntaxNode node2) => SyntaxComparer.Statement.GetLabel(node1) == SyntaxComparer.Statement.GetLabel(node2); protected override bool TryGetEnclosingBreakpointSpan(SyntaxNode root, int position, out TextSpan span) => BreakpointSpans.TryGetClosestBreakpointSpan(root, position, out span); protected override bool TryGetActiveSpan(SyntaxNode node, int statementPart, int minLength, out TextSpan span) { switch (node.Kind()) { case SyntaxKind.Block: span = GetActiveSpan((BlockSyntax)node, (BlockPart)statementPart); return true; case SyntaxKind.ForEachStatement: span = GetActiveSpan((ForEachStatementSyntax)node, (ForEachPart)statementPart); return true; case SyntaxKind.ForEachVariableStatement: span = GetActiveSpan((ForEachVariableStatementSyntax)node, (ForEachPart)statementPart); return true; case SyntaxKind.DoStatement: // The active statement of DoStatement node is the while condition, // which is lexically not the closest breakpoint span (the body is). // do { ... } [|while (condition);|] Debug.Assert(statementPart == DefaultStatementPart); var doStatement = (DoStatementSyntax)node; return BreakpointSpans.TryGetClosestBreakpointSpan(node, doStatement.WhileKeyword.SpanStart, out span); case SyntaxKind.PropertyDeclaration: // The active span corresponding to a property declaration is the span corresponding to its initializer (if any), // not the span corresponding to the accessor. // int P { [|get;|] } = [|<initializer>|]; Debug.Assert(statementPart == DefaultStatementPart); var propertyDeclaration = (PropertyDeclarationSyntax)node; if (propertyDeclaration.Initializer != null && BreakpointSpans.TryGetClosestBreakpointSpan(node, propertyDeclaration.Initializer.SpanStart, out span)) { return true; } span = default; return false; case SyntaxKind.SwitchExpression: span = GetActiveSpan((SwitchExpressionSyntax)node, (SwitchExpressionPart)statementPart); return true; case SyntaxKind.SwitchExpressionArm: // An active statement may occur in the when clause and in the arm expression: // <constant-pattern> [|when <condition>|] => [|<expression>|] // The former is covered by when-clause node - it's a labeled node. // The latter isn't enclosed in a distinct labeled syntax node and thus needs to be covered // by the arm node itself. Debug.Assert(statementPart == DefaultStatementPart); span = ((SwitchExpressionArmSyntax)node).Expression.Span; return true; default: // make sure all nodes that use statement parts are handled above: Debug.Assert(statementPart == DefaultStatementPart); return BreakpointSpans.TryGetClosestBreakpointSpan(node, node.SpanStart, out span); } } protected override IEnumerable<(SyntaxNode statement, int statementPart)> EnumerateNearStatements(SyntaxNode statement) { var direction = +1; SyntaxNodeOrToken nodeOrToken = statement; var fieldOrPropertyModifiers = SyntaxUtilities.TryGetFieldOrPropertyModifiers(statement); while (true) { nodeOrToken = (direction < 0) ? nodeOrToken.GetPreviousSibling() : nodeOrToken.GetNextSibling(); if (nodeOrToken.RawKind == 0) { var parent = statement.Parent; if (parent == null) { yield break; } switch (parent.Kind()) { case SyntaxKind.Block: // The next sequence point hit after the last statement of a block is the closing brace: yield return (parent, (int)(direction > 0 ? BlockPart.CloseBrace : BlockPart.OpenBrace)); break; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: // The next sequence point hit after the body is the in keyword: // [|foreach|] ([|variable-declaration|] [|in|] [|expression|]) [|<body>|] yield return (parent, (int)ForEachPart.In); break; } if (direction > 0) { nodeOrToken = statement; direction = -1; continue; } if (fieldOrPropertyModifiers.HasValue) { // We enumerated all members and none of them has an initializer. // We don't have any better place where to place the span than the initial field. // Consider: in non-partial classes we could find a single constructor. // Otherwise, it would be confusing to select one arbitrarily. yield return (statement, -1); } nodeOrToken = statement = parent; fieldOrPropertyModifiers = SyntaxUtilities.TryGetFieldOrPropertyModifiers(statement); direction = +1; yield return (nodeOrToken.AsNode()!, DefaultStatementPart); } else { var node = nodeOrToken.AsNode(); if (node == null) { continue; } if (fieldOrPropertyModifiers.HasValue) { var nodeModifiers = SyntaxUtilities.TryGetFieldOrPropertyModifiers(node); if (!nodeModifiers.HasValue || nodeModifiers.Value.Any(SyntaxKind.StaticKeyword) != fieldOrPropertyModifiers.Value.Any(SyntaxKind.StaticKeyword)) { continue; } } switch (node.Kind()) { case SyntaxKind.Block: yield return (node, (int)(direction > 0 ? BlockPart.OpenBrace : BlockPart.CloseBrace)); break; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: yield return (node, (int)ForEachPart.ForEach); break; } yield return (node, DefaultStatementPart); } } } protected override bool AreEquivalentActiveStatements(SyntaxNode oldStatement, SyntaxNode newStatement, int statementPart) { if (oldStatement.Kind() != newStatement.Kind()) { return false; } switch (oldStatement.Kind()) { case SyntaxKind.Block: // closing brace of a using statement or a block that contains using local declarations: if (statementPart == (int)BlockPart.CloseBrace) { if (oldStatement.Parent.IsKind(SyntaxKind.UsingStatement, out UsingStatementSyntax? oldUsing)) { return newStatement.Parent.IsKind(SyntaxKind.UsingStatement, out UsingStatementSyntax? newUsing) && AreEquivalentActiveStatements(oldUsing, newUsing); } return HasEquivalentUsingDeclarations((BlockSyntax)oldStatement, (BlockSyntax)newStatement); } return true; case SyntaxKind.ConstructorDeclaration: // The call could only change if the base type of the containing class changed. return true; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: // only check the expression, edits in the body and the variable declaration are allowed: return AreEquivalentActiveStatements((CommonForEachStatementSyntax)oldStatement, (CommonForEachStatementSyntax)newStatement); case SyntaxKind.IfStatement: // only check the condition, edits in the body are allowed: return AreEquivalentActiveStatements((IfStatementSyntax)oldStatement, (IfStatementSyntax)newStatement); case SyntaxKind.WhileStatement: // only check the condition, edits in the body are allowed: return AreEquivalentActiveStatements((WhileStatementSyntax)oldStatement, (WhileStatementSyntax)newStatement); case SyntaxKind.DoStatement: // only check the condition, edits in the body are allowed: return AreEquivalentActiveStatements((DoStatementSyntax)oldStatement, (DoStatementSyntax)newStatement); case SyntaxKind.SwitchStatement: return AreEquivalentActiveStatements((SwitchStatementSyntax)oldStatement, (SwitchStatementSyntax)newStatement); case SyntaxKind.LockStatement: return AreEquivalentActiveStatements((LockStatementSyntax)oldStatement, (LockStatementSyntax)newStatement); case SyntaxKind.UsingStatement: return AreEquivalentActiveStatements((UsingStatementSyntax)oldStatement, (UsingStatementSyntax)newStatement); // fixed and for statements don't need special handling since the active statement is a variable declaration default: return AreEquivalentIgnoringLambdaBodies(oldStatement, newStatement); } } private static bool HasEquivalentUsingDeclarations(BlockSyntax oldBlock, BlockSyntax newBlock) { var oldUsingDeclarations = oldBlock.Statements.Where(s => s is LocalDeclarationStatementSyntax l && l.UsingKeyword != default); var newUsingDeclarations = newBlock.Statements.Where(s => s is LocalDeclarationStatementSyntax l && l.UsingKeyword != default); return oldUsingDeclarations.SequenceEqual(newUsingDeclarations, AreEquivalentIgnoringLambdaBodies); } private static bool AreEquivalentActiveStatements(IfStatementSyntax oldNode, IfStatementSyntax newNode) { // only check the condition, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition); } private static bool AreEquivalentActiveStatements(WhileStatementSyntax oldNode, WhileStatementSyntax newNode) { // only check the condition, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition); } private static bool AreEquivalentActiveStatements(DoStatementSyntax oldNode, DoStatementSyntax newNode) { // only check the condition, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition); } private static bool AreEquivalentActiveStatements(SwitchStatementSyntax oldNode, SwitchStatementSyntax newNode) { // only check the expression, edits in the body are allowed, unless the switch expression contains patterns: if (!AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression)) { return false; } // Check that switch statement decision tree has not changed. var hasDecitionTree = oldNode.Sections.Any(s => s.Labels.Any(l => l is CasePatternSwitchLabelSyntax)); return !hasDecitionTree || AreEquivalentSwitchStatementDecisionTrees(oldNode, newNode); } private static bool AreEquivalentActiveStatements(LockStatementSyntax oldNode, LockStatementSyntax newNode) { // only check the expression, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression); } private static bool AreEquivalentActiveStatements(FixedStatementSyntax oldNode, FixedStatementSyntax newNode) => AreEquivalentIgnoringLambdaBodies(oldNode.Declaration, newNode.Declaration); private static bool AreEquivalentActiveStatements(UsingStatementSyntax oldNode, UsingStatementSyntax newNode) { // only check the expression/declaration, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies( (SyntaxNode?)oldNode.Declaration ?? oldNode.Expression!, (SyntaxNode?)newNode.Declaration ?? newNode.Expression!); } private static bool AreEquivalentActiveStatements(CommonForEachStatementSyntax oldNode, CommonForEachStatementSyntax newNode) { if (oldNode.Kind() != newNode.Kind() || !AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression)) { return false; } switch (oldNode.Kind()) { case SyntaxKind.ForEachStatement: return AreEquivalentIgnoringLambdaBodies(((ForEachStatementSyntax)oldNode).Type, ((ForEachStatementSyntax)newNode).Type); case SyntaxKind.ForEachVariableStatement: return AreEquivalentIgnoringLambdaBodies(((ForEachVariableStatementSyntax)oldNode).Variable, ((ForEachVariableStatementSyntax)newNode).Variable); default: throw ExceptionUtilities.UnexpectedValue(oldNode.Kind()); } } private static bool AreSimilarActiveStatements(CommonForEachStatementSyntax oldNode, CommonForEachStatementSyntax newNode) { List<SyntaxToken>? oldTokens = null; List<SyntaxToken>? newTokens = null; SyntaxComparer.GetLocalNames(oldNode, ref oldTokens); SyntaxComparer.GetLocalNames(newNode, ref newTokens); // A valid foreach statement declares at least one variable. RoslynDebug.Assert(oldTokens != null); RoslynDebug.Assert(newTokens != null); return DeclareSameIdentifiers(oldTokens.ToArray(), newTokens.ToArray()); } internal override bool IsInterfaceDeclaration(SyntaxNode node) => node.IsKind(SyntaxKind.InterfaceDeclaration); internal override bool IsRecordDeclaration(SyntaxNode node) => node.IsKind(SyntaxKind.RecordDeclaration, SyntaxKind.RecordStructDeclaration); internal override SyntaxNode? TryGetContainingTypeDeclaration(SyntaxNode node) => node is CompilationUnitSyntax ? null : node.Parent!.FirstAncestorOrSelf<BaseTypeDeclarationSyntax>(); internal override bool HasBackingField(SyntaxNode propertyOrIndexerDeclaration) => propertyOrIndexerDeclaration.IsKind(SyntaxKind.PropertyDeclaration, out PropertyDeclarationSyntax? propertyDecl) && SyntaxUtilities.HasBackingField(propertyDecl); internal override bool TryGetAssociatedMemberDeclaration(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? declaration) { if (node.IsKind(SyntaxKind.Parameter, SyntaxKind.TypeParameter)) { Contract.ThrowIfFalse(node.IsParentKind(SyntaxKind.ParameterList, SyntaxKind.TypeParameterList, SyntaxKind.BracketedParameterList)); declaration = node.Parent!.Parent!; return true; } if (node.Parent.IsParentKind(SyntaxKind.PropertyDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.EventDeclaration)) { declaration = node.Parent.Parent!; return true; } declaration = null; return false; } internal override bool IsDeclarationWithInitializer(SyntaxNode declaration) => declaration is VariableDeclaratorSyntax { Initializer: not null } || declaration is PropertyDeclarationSyntax { Initializer: not null }; internal override bool IsRecordPrimaryConstructorParameter(SyntaxNode declaration) => declaration is ParameterSyntax { Parent: ParameterListSyntax { Parent: RecordDeclarationSyntax } }; private static bool IsPropertyDeclarationMatchingPrimaryConstructorParameter(SyntaxNode declaration, INamedTypeSymbol newContainingType) { if (newContainingType.IsRecord && declaration is PropertyDeclarationSyntax { Identifier: { ValueText: var name } }) { // We need to use symbol information to find the primary constructor, because it could be in another file if the type is partial foreach (var reference in newContainingType.DeclaringSyntaxReferences) { // Since users can define as many constructors as they like, going back to syntax to find the parameter list // in the record declaration is the simplest way to check if there is a matching parameter if (reference.GetSyntax() is RecordDeclarationSyntax record && record.ParameterList is not null && record.ParameterList.Parameters.Any(p => p.Identifier.ValueText.Equals(name))) { return true; } } } return false; } internal override bool IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(SyntaxNode declaration, INamedTypeSymbol newContainingType, out bool isFirstAccessor) { isFirstAccessor = false; if (declaration is AccessorDeclarationSyntax { Parent: AccessorListSyntax { Parent: PropertyDeclarationSyntax property } list } && IsPropertyDeclarationMatchingPrimaryConstructorParameter(property, newContainingType)) { isFirstAccessor = list.Accessors[0] == declaration; return true; } return false; } internal override bool IsConstructorWithMemberInitializers(SyntaxNode constructorDeclaration) => constructorDeclaration is ConstructorDeclarationSyntax ctor && (ctor.Initializer == null || ctor.Initializer.IsKind(SyntaxKind.BaseConstructorInitializer)); internal override bool IsPartial(INamedTypeSymbol type) { var syntaxRefs = type.DeclaringSyntaxReferences; return syntaxRefs.Length > 1 || ((BaseTypeDeclarationSyntax)syntaxRefs.Single().GetSyntax()).Modifiers.Any(SyntaxKind.PartialKeyword); } protected override SyntaxNode GetSymbolDeclarationSyntax(SyntaxReference reference, CancellationToken cancellationToken) => reference.GetSyntax(cancellationToken); protected override OneOrMany<(ISymbol? oldSymbol, ISymbol? newSymbol, EditKind editKind)> GetSymbolEdits( EditKind editKind, SyntaxNode? oldNode, SyntaxNode? newNode, SemanticModel? oldModel, SemanticModel newModel, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, CancellationToken cancellationToken) { var oldSymbol = (oldNode != null) ? GetSymbolForEdit(oldNode, oldModel!, cancellationToken) : null; var newSymbol = (newNode != null) ? GetSymbolForEdit(newNode, newModel, cancellationToken) : null; switch (editKind) { case EditKind.Update: Contract.ThrowIfNull(oldNode); Contract.ThrowIfNull(newNode); Contract.ThrowIfNull(oldModel); // Certain updates of a property/indexer node affects its accessors. // Return all affected symbols for these updates. // 1) Old or new property/indexer has an expression body: // int this[...] => expr; // int this[...] { get => expr; } // int P => expr; // int P { get => expr; } = init if (oldNode is PropertyDeclarationSyntax { ExpressionBody: not null } or IndexerDeclarationSyntax { ExpressionBody: not null } || newNode is PropertyDeclarationSyntax { ExpressionBody: not null } or IndexerDeclarationSyntax { ExpressionBody: not null }) { Debug.Assert(oldSymbol is IPropertySymbol); Debug.Assert(newSymbol is IPropertySymbol); var oldGetterSymbol = ((IPropertySymbol)oldSymbol).GetMethod; var newGetterSymbol = ((IPropertySymbol)newSymbol).GetMethod; return OneOrMany.Create(ImmutableArray.Create((oldSymbol, newSymbol, editKind), (oldGetterSymbol, newGetterSymbol, editKind))); } // 2) Property/indexer declarations differ in readonly keyword. if (oldNode is PropertyDeclarationSyntax oldProperty && newNode is PropertyDeclarationSyntax newProperty && DiffersInReadOnlyModifier(oldProperty.Modifiers, newProperty.Modifiers) || oldNode is IndexerDeclarationSyntax oldIndexer && newNode is IndexerDeclarationSyntax newIndexer && DiffersInReadOnlyModifier(oldIndexer.Modifiers, newIndexer.Modifiers)) { Debug.Assert(oldSymbol is IPropertySymbol); Debug.Assert(newSymbol is IPropertySymbol); var oldPropertySymbol = (IPropertySymbol)oldSymbol; var newPropertySymbol = (IPropertySymbol)newSymbol; using var _ = ArrayBuilder<(ISymbol?, ISymbol?, EditKind)>.GetInstance(out var builder); builder.Add((oldPropertySymbol, newPropertySymbol, editKind)); if (oldPropertySymbol.GetMethod != null && newPropertySymbol.GetMethod != null && oldPropertySymbol.GetMethod.IsReadOnly != newPropertySymbol.GetMethod.IsReadOnly) { builder.Add((oldPropertySymbol.GetMethod, newPropertySymbol.GetMethod, editKind)); } if (oldPropertySymbol.SetMethod != null && newPropertySymbol.SetMethod != null && oldPropertySymbol.SetMethod.IsReadOnly != newPropertySymbol.SetMethod.IsReadOnly) { builder.Add((oldPropertySymbol.SetMethod, newPropertySymbol.SetMethod, editKind)); } return OneOrMany.Create(builder.ToImmutable()); } static bool DiffersInReadOnlyModifier(SyntaxTokenList oldModifiers, SyntaxTokenList newModifiers) => (oldModifiers.IndexOf(SyntaxKind.ReadOnlyKeyword) >= 0) != (newModifiers.IndexOf(SyntaxKind.ReadOnlyKeyword) >= 0); // Change in attributes or modifiers of a field affects all its variable declarations. if (oldNode is BaseFieldDeclarationSyntax oldField && newNode is BaseFieldDeclarationSyntax newField) { return GetFieldSymbolUpdates(oldField.Declaration.Variables, newField.Declaration.Variables); } // Chnage in type of a field affects all its variable declarations. if (oldNode is VariableDeclarationSyntax oldVariableDeclaration && newNode is VariableDeclarationSyntax newVariableDeclaration) { return GetFieldSymbolUpdates(oldVariableDeclaration.Variables, newVariableDeclaration.Variables); } OneOrMany<(ISymbol?, ISymbol?, EditKind)> GetFieldSymbolUpdates(SeparatedSyntaxList<VariableDeclaratorSyntax> oldVariables, SeparatedSyntaxList<VariableDeclaratorSyntax> newVariables) { if (oldVariables.Count == 1 && newVariables.Count == 1) { return OneOrMany.Create((oldModel.GetDeclaredSymbol(oldVariables[0], cancellationToken), newModel.GetDeclaredSymbol(newVariables[0], cancellationToken), EditKind.Update)); } var result = from oldVariable in oldVariables join newVariable in newVariables on oldVariable.Identifier.Text equals newVariable.Identifier.Text select (oldModel.GetDeclaredSymbol(oldVariable, cancellationToken), newModel.GetDeclaredSymbol(newVariable, cancellationToken), EditKind.Update); return OneOrMany.Create(result.ToImmutableArray()); } break; case EditKind.Delete: case EditKind.Insert: var node = oldNode ?? newNode; // If the entire block-bodied property/indexer is deleted/inserted (accessors and the list they are contained in), // ignore this edit. We will have a semantic edit for the property/indexer itself. if (node.IsKind(SyntaxKind.GetAccessorDeclaration)) { Debug.Assert(node.Parent.IsKind(SyntaxKind.AccessorList)); if (HasEdit(editMap, node.Parent, editKind) && !HasEdit(editMap, node.Parent.Parent, editKind)) { return OneOrMany<(ISymbol?, ISymbol?, EditKind)>.Empty; } } // Inserting/deleting an expression-bodied property/indexer affects two symbols: // the property/indexer itself and the getter. // int this[...] => expr; // int P => expr; if (node is PropertyDeclarationSyntax { ExpressionBody: not null } or IndexerDeclarationSyntax { ExpressionBody: not null }) { var oldGetterSymbol = ((IPropertySymbol?)oldSymbol)?.GetMethod; var newGetterSymbol = ((IPropertySymbol?)newSymbol)?.GetMethod; return OneOrMany.Create(ImmutableArray.Create((oldSymbol, newSymbol, editKind), (oldGetterSymbol, newGetterSymbol, editKind))); } // Inserting/deleting a type parameter constraint should result in an update of the corresponding type parameter symbol: if (node.IsKind(SyntaxKind.TypeParameterConstraintClause)) { return OneOrMany.Create(ImmutableArray.Create((oldSymbol, newSymbol, EditKind.Update))); } // Inserting/deleting a global statement should result in an update of the implicit main method: if (node.IsKind(SyntaxKind.GlobalStatement)) { return OneOrMany.Create(ImmutableArray.Create((oldSymbol, newSymbol, EditKind.Update))); } break; } return (editKind == EditKind.Delete ? oldSymbol : newSymbol) is null ? OneOrMany<(ISymbol?, ISymbol?, EditKind)>.Empty : new OneOrMany<(ISymbol?, ISymbol?, EditKind)>((oldSymbol, newSymbol, editKind)); } private static ISymbol? GetSymbolForEdit( SyntaxNode node, SemanticModel model, CancellationToken cancellationToken) { if (node.IsKind(SyntaxKind.UsingDirective, SyntaxKind.NamespaceDeclaration, SyntaxKind.FileScopedNamespaceDeclaration)) { return null; } if (node.IsKind(SyntaxKind.TypeParameterConstraintClause)) { var constraintClause = (TypeParameterConstraintClauseSyntax)node; var symbolInfo = model.GetSymbolInfo(constraintClause.Name, cancellationToken); return symbolInfo.Symbol; } // Top level code always lives in a synthesized Main method if (node.IsKind(SyntaxKind.GlobalStatement)) { return model.GetEnclosingSymbol(node.SpanStart, cancellationToken); } var symbol = model.GetDeclaredSymbol(node, cancellationToken); // TODO: this is incorrect (https://github.com/dotnet/roslyn/issues/54800) // Ignore partial method definition parts. // Partial method that does not have implementation part is not emitted to metadata. // Partial method without a definition part is a compilation error. if (symbol is IMethodSymbol { IsPartialDefinition: true }) { return null; } return symbol; } internal override bool ContainsLambda(SyntaxNode declaration) => declaration.DescendantNodes().Any(LambdaUtilities.IsLambda); internal override bool IsLambda(SyntaxNode node) => LambdaUtilities.IsLambda(node); internal override bool IsLocalFunction(SyntaxNode node) => node.IsKind(SyntaxKind.LocalFunctionStatement); internal override bool IsNestedFunction(SyntaxNode node) => node is AnonymousFunctionExpressionSyntax or LocalFunctionStatementSyntax; internal override bool TryGetLambdaBodies(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? body1, out SyntaxNode? body2) => LambdaUtilities.TryGetLambdaBodies(node, out body1, out body2); internal override SyntaxNode GetLambda(SyntaxNode lambdaBody) => LambdaUtilities.GetLambda(lambdaBody); internal override IMethodSymbol GetLambdaExpressionSymbol(SemanticModel model, SyntaxNode lambdaExpression, CancellationToken cancellationToken) { var bodyExpression = LambdaUtilities.GetNestedFunctionBody(lambdaExpression); return (IMethodSymbol)model.GetRequiredEnclosingSymbol(bodyExpression.SpanStart, cancellationToken); } internal override SyntaxNode? GetContainingQueryExpression(SyntaxNode node) => node.FirstAncestorOrSelf<QueryExpressionSyntax>(); internal override bool QueryClauseLambdasTypeEquivalent(SemanticModel oldModel, SyntaxNode oldNode, SemanticModel newModel, SyntaxNode newNode, CancellationToken cancellationToken) { switch (oldNode.Kind()) { case SyntaxKind.FromClause: case SyntaxKind.LetClause: case SyntaxKind.WhereClause: case SyntaxKind.OrderByClause: case SyntaxKind.JoinClause: var oldQueryClauseInfo = oldModel.GetQueryClauseInfo((QueryClauseSyntax)oldNode, cancellationToken); var newQueryClauseInfo = newModel.GetQueryClauseInfo((QueryClauseSyntax)newNode, cancellationToken); return MemberSignaturesEquivalent(oldQueryClauseInfo.CastInfo.Symbol, newQueryClauseInfo.CastInfo.Symbol) && MemberSignaturesEquivalent(oldQueryClauseInfo.OperationInfo.Symbol, newQueryClauseInfo.OperationInfo.Symbol); case SyntaxKind.AscendingOrdering: case SyntaxKind.DescendingOrdering: var oldOrderingInfo = oldModel.GetSymbolInfo(oldNode, cancellationToken); var newOrderingInfo = newModel.GetSymbolInfo(newNode, cancellationToken); return MemberSignaturesEquivalent(oldOrderingInfo.Symbol, newOrderingInfo.Symbol); case SyntaxKind.SelectClause: var oldSelectInfo = oldModel.GetSymbolInfo(oldNode, cancellationToken); var newSelectInfo = newModel.GetSymbolInfo(newNode, cancellationToken); // Changing reduced select clause to a non-reduced form or vice versa // adds/removes a call to Select method, which is a supported change. return oldSelectInfo.Symbol == null || newSelectInfo.Symbol == null || MemberSignaturesEquivalent(oldSelectInfo.Symbol, newSelectInfo.Symbol); case SyntaxKind.GroupClause: var oldGroupByInfo = oldModel.GetSymbolInfo(oldNode, cancellationToken); var newGroupByInfo = newModel.GetSymbolInfo(newNode, cancellationToken); return MemberSignaturesEquivalent(oldGroupByInfo.Symbol, newGroupByInfo.Symbol, GroupBySignatureComparer); default: return true; } } private static bool GroupBySignatureComparer(ImmutableArray<IParameterSymbol> oldParameters, ITypeSymbol oldReturnType, ImmutableArray<IParameterSymbol> newParameters, ITypeSymbol newReturnType) { // C# spec paragraph 7.16.2.6 "Groupby clauses": // // A query expression of the form // from x in e group v by k // is translated into // (e).GroupBy(x => k, x => v) // except when v is the identifier x, the translation is // (e).GroupBy(x => k) // // Possible signatures: // C<G<K, T>> GroupBy<K>(Func<T, K> keySelector); // C<G<K, E>> GroupBy<K, E>(Func<T, K> keySelector, Func<T, E> elementSelector); if (!TypesEquivalent(oldReturnType, newReturnType, exact: false)) { return false; } Debug.Assert(oldParameters.Length == 1 || oldParameters.Length == 2); Debug.Assert(newParameters.Length == 1 || newParameters.Length == 2); // The types of the lambdas have to be the same if present. // The element selector may be added/removed. if (!ParameterTypesEquivalent(oldParameters[0], newParameters[0], exact: false)) { return false; } if (oldParameters.Length == newParameters.Length && newParameters.Length == 2) { return ParameterTypesEquivalent(oldParameters[1], newParameters[1], exact: false); } return true; } #endregion #region Diagnostic Info protected override SymbolDisplayFormat ErrorDisplayFormat => SymbolDisplayFormat.CSharpErrorMessageFormat; protected override TextSpan? TryGetDiagnosticSpan(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpanImpl(node, editKind); internal static new TextSpan GetDiagnosticSpan(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpanImpl(node, editKind) ?? node.Span; private static TextSpan? TryGetDiagnosticSpanImpl(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpanImpl(node.Kind(), node, editKind); // internal for testing; kind is passed explicitly for testing as well internal static TextSpan? TryGetDiagnosticSpanImpl(SyntaxKind kind, SyntaxNode node, EditKind editKind) { switch (kind) { case SyntaxKind.CompilationUnit: return default(TextSpan); case SyntaxKind.GlobalStatement: return node.Span; case SyntaxKind.ExternAliasDirective: case SyntaxKind.UsingDirective: return node.Span; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: var ns = (BaseNamespaceDeclarationSyntax)node; return TextSpan.FromBounds(ns.NamespaceKeyword.SpanStart, ns.Name.Span.End); case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: var typeDeclaration = (TypeDeclarationSyntax)node; return GetDiagnosticSpan(typeDeclaration.Modifiers, typeDeclaration.Keyword, typeDeclaration.TypeParameterList ?? (SyntaxNodeOrToken)typeDeclaration.Identifier); case SyntaxKind.EnumDeclaration: var enumDeclaration = (EnumDeclarationSyntax)node; return GetDiagnosticSpan(enumDeclaration.Modifiers, enumDeclaration.EnumKeyword, enumDeclaration.Identifier); case SyntaxKind.DelegateDeclaration: var delegateDeclaration = (DelegateDeclarationSyntax)node; return GetDiagnosticSpan(delegateDeclaration.Modifiers, delegateDeclaration.DelegateKeyword, delegateDeclaration.ParameterList); case SyntaxKind.FieldDeclaration: var fieldDeclaration = (BaseFieldDeclarationSyntax)node; return GetDiagnosticSpan(fieldDeclaration.Modifiers, fieldDeclaration.Declaration, fieldDeclaration.Declaration); case SyntaxKind.EventFieldDeclaration: var eventFieldDeclaration = (EventFieldDeclarationSyntax)node; return GetDiagnosticSpan(eventFieldDeclaration.Modifiers, eventFieldDeclaration.EventKeyword, eventFieldDeclaration.Declaration); case SyntaxKind.VariableDeclaration: return TryGetDiagnosticSpanImpl(node.Parent!, editKind); case SyntaxKind.VariableDeclarator: return node.Span; case SyntaxKind.MethodDeclaration: var methodDeclaration = (MethodDeclarationSyntax)node; return GetDiagnosticSpan(methodDeclaration.Modifiers, methodDeclaration.ReturnType, methodDeclaration.ParameterList); case SyntaxKind.ConversionOperatorDeclaration: var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)node; return GetDiagnosticSpan(conversionOperatorDeclaration.Modifiers, conversionOperatorDeclaration.ImplicitOrExplicitKeyword, conversionOperatorDeclaration.ParameterList); case SyntaxKind.OperatorDeclaration: var operatorDeclaration = (OperatorDeclarationSyntax)node; return GetDiagnosticSpan(operatorDeclaration.Modifiers, operatorDeclaration.ReturnType, operatorDeclaration.ParameterList); case SyntaxKind.ConstructorDeclaration: var constructorDeclaration = (ConstructorDeclarationSyntax)node; return GetDiagnosticSpan(constructorDeclaration.Modifiers, constructorDeclaration.Identifier, constructorDeclaration.ParameterList); case SyntaxKind.DestructorDeclaration: var destructorDeclaration = (DestructorDeclarationSyntax)node; return GetDiagnosticSpan(destructorDeclaration.Modifiers, destructorDeclaration.TildeToken, destructorDeclaration.ParameterList); case SyntaxKind.PropertyDeclaration: var propertyDeclaration = (PropertyDeclarationSyntax)node; return GetDiagnosticSpan(propertyDeclaration.Modifiers, propertyDeclaration.Type, propertyDeclaration.Identifier); case SyntaxKind.IndexerDeclaration: var indexerDeclaration = (IndexerDeclarationSyntax)node; return GetDiagnosticSpan(indexerDeclaration.Modifiers, indexerDeclaration.Type, indexerDeclaration.ParameterList); case SyntaxKind.EventDeclaration: var eventDeclaration = (EventDeclarationSyntax)node; return GetDiagnosticSpan(eventDeclaration.Modifiers, eventDeclaration.EventKeyword, eventDeclaration.Identifier); case SyntaxKind.EnumMemberDeclaration: return node.Span; case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.UnknownAccessorDeclaration: var accessorDeclaration = (AccessorDeclarationSyntax)node; return GetDiagnosticSpan(accessorDeclaration.Modifiers, accessorDeclaration.Keyword, accessorDeclaration.Keyword); case SyntaxKind.TypeParameterConstraintClause: var constraint = (TypeParameterConstraintClauseSyntax)node; return TextSpan.FromBounds(constraint.WhereKeyword.SpanStart, constraint.Constraints.Last().Span.End); case SyntaxKind.TypeParameter: var typeParameter = (TypeParameterSyntax)node; return typeParameter.Identifier.Span; case SyntaxKind.AccessorList: case SyntaxKind.TypeParameterList: case SyntaxKind.ParameterList: case SyntaxKind.BracketedParameterList: if (editKind == EditKind.Delete) { return TryGetDiagnosticSpanImpl(node.Parent!, editKind); } else { return node.Span; } case SyntaxKind.Parameter: var parameter = (ParameterSyntax)node; // Lambda parameters don't have types or modifiers, so the parameter is the only node var startNode = parameter.Type ?? (SyntaxNode)parameter; return GetDiagnosticSpan(parameter.Modifiers, startNode, parameter); case SyntaxKind.AttributeList: var attributeList = (AttributeListSyntax)node; return attributeList.Span; case SyntaxKind.Attribute: return node.Span; case SyntaxKind.ArrowExpressionClause: return TryGetDiagnosticSpanImpl(node.Parent!, editKind); // We only need a diagnostic span if reporting an error for a child statement. // The following statements may have child statements. case SyntaxKind.Block: return ((BlockSyntax)node).OpenBraceToken.Span; case SyntaxKind.UsingStatement: var usingStatement = (UsingStatementSyntax)node; return TextSpan.FromBounds(usingStatement.UsingKeyword.SpanStart, usingStatement.CloseParenToken.Span.End); case SyntaxKind.FixedStatement: var fixedStatement = (FixedStatementSyntax)node; return TextSpan.FromBounds(fixedStatement.FixedKeyword.SpanStart, fixedStatement.CloseParenToken.Span.End); case SyntaxKind.LockStatement: var lockStatement = (LockStatementSyntax)node; return TextSpan.FromBounds(lockStatement.LockKeyword.SpanStart, lockStatement.CloseParenToken.Span.End); case SyntaxKind.StackAllocArrayCreationExpression: return ((StackAllocArrayCreationExpressionSyntax)node).StackAllocKeyword.Span; case SyntaxKind.ImplicitStackAllocArrayCreationExpression: return ((ImplicitStackAllocArrayCreationExpressionSyntax)node).StackAllocKeyword.Span; case SyntaxKind.TryStatement: return ((TryStatementSyntax)node).TryKeyword.Span; case SyntaxKind.CatchClause: return ((CatchClauseSyntax)node).CatchKeyword.Span; case SyntaxKind.CatchDeclaration: case SyntaxKind.CatchFilterClause: return node.Span; case SyntaxKind.FinallyClause: return ((FinallyClauseSyntax)node).FinallyKeyword.Span; case SyntaxKind.IfStatement: var ifStatement = (IfStatementSyntax)node; return TextSpan.FromBounds(ifStatement.IfKeyword.SpanStart, ifStatement.CloseParenToken.Span.End); case SyntaxKind.ElseClause: return ((ElseClauseSyntax)node).ElseKeyword.Span; case SyntaxKind.SwitchStatement: var switchStatement = (SwitchStatementSyntax)node; return TextSpan.FromBounds(switchStatement.SwitchKeyword.SpanStart, (switchStatement.CloseParenToken != default) ? switchStatement.CloseParenToken.Span.End : switchStatement.Expression.Span.End); case SyntaxKind.SwitchSection: return ((SwitchSectionSyntax)node).Labels.Last().Span; case SyntaxKind.WhileStatement: var whileStatement = (WhileStatementSyntax)node; return TextSpan.FromBounds(whileStatement.WhileKeyword.SpanStart, whileStatement.CloseParenToken.Span.End); case SyntaxKind.DoStatement: return ((DoStatementSyntax)node).DoKeyword.Span; case SyntaxKind.ForStatement: var forStatement = (ForStatementSyntax)node; return TextSpan.FromBounds(forStatement.ForKeyword.SpanStart, forStatement.CloseParenToken.Span.End); case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: var commonForEachStatement = (CommonForEachStatementSyntax)node; return TextSpan.FromBounds( (commonForEachStatement.AwaitKeyword.Span.Length > 0) ? commonForEachStatement.AwaitKeyword.SpanStart : commonForEachStatement.ForEachKeyword.SpanStart, commonForEachStatement.CloseParenToken.Span.End); case SyntaxKind.LabeledStatement: return ((LabeledStatementSyntax)node).Identifier.Span; case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return ((CheckedStatementSyntax)node).Keyword.Span; case SyntaxKind.UnsafeStatement: return ((UnsafeStatementSyntax)node).UnsafeKeyword.Span; case SyntaxKind.LocalFunctionStatement: var lfd = (LocalFunctionStatementSyntax)node; return lfd.Identifier.Span; case SyntaxKind.YieldBreakStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.ExpressionStatement: case SyntaxKind.EmptyStatement: case SyntaxKind.GotoStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: return node.Span; case SyntaxKind.LocalDeclarationStatement: var localDeclarationStatement = (LocalDeclarationStatementSyntax)node; return CombineSpans(localDeclarationStatement.AwaitKeyword.Span, localDeclarationStatement.UsingKeyword.Span, node.Span); case SyntaxKind.AwaitExpression: return ((AwaitExpressionSyntax)node).AwaitKeyword.Span; case SyntaxKind.AnonymousObjectCreationExpression: return ((AnonymousObjectCreationExpressionSyntax)node).NewKeyword.Span; case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)node).ParameterList.Span; case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)node).Parameter.Span; case SyntaxKind.AnonymousMethodExpression: return ((AnonymousMethodExpressionSyntax)node).DelegateKeyword.Span; case SyntaxKind.QueryExpression: return ((QueryExpressionSyntax)node).FromClause.FromKeyword.Span; case SyntaxKind.QueryBody: var queryBody = (QueryBodySyntax)node; return TryGetDiagnosticSpanImpl(queryBody.Clauses.FirstOrDefault() ?? queryBody.Parent!, editKind); case SyntaxKind.QueryContinuation: return ((QueryContinuationSyntax)node).IntoKeyword.Span; case SyntaxKind.FromClause: return ((FromClauseSyntax)node).FromKeyword.Span; case SyntaxKind.JoinClause: return ((JoinClauseSyntax)node).JoinKeyword.Span; case SyntaxKind.JoinIntoClause: return ((JoinIntoClauseSyntax)node).IntoKeyword.Span; case SyntaxKind.LetClause: return ((LetClauseSyntax)node).LetKeyword.Span; case SyntaxKind.WhereClause: return ((WhereClauseSyntax)node).WhereKeyword.Span; case SyntaxKind.OrderByClause: return ((OrderByClauseSyntax)node).OrderByKeyword.Span; case SyntaxKind.AscendingOrdering: case SyntaxKind.DescendingOrdering: return node.Span; case SyntaxKind.SelectClause: return ((SelectClauseSyntax)node).SelectKeyword.Span; case SyntaxKind.GroupClause: return ((GroupClauseSyntax)node).GroupKeyword.Span; case SyntaxKind.IsPatternExpression: case SyntaxKind.TupleType: case SyntaxKind.TupleExpression: case SyntaxKind.DeclarationExpression: case SyntaxKind.RefType: case SyntaxKind.RefExpression: case SyntaxKind.DeclarationPattern: case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.WhenClause: case SyntaxKind.SingleVariableDesignation: case SyntaxKind.CasePatternSwitchLabel: return node.Span; case SyntaxKind.SwitchExpression: return ((SwitchExpressionSyntax)node).SwitchKeyword.Span; case SyntaxKind.SwitchExpressionArm: return ((SwitchExpressionArmSyntax)node).EqualsGreaterThanToken.Span; default: return null; } } private static TextSpan GetDiagnosticSpan(SyntaxTokenList modifiers, SyntaxNodeOrToken start, SyntaxNodeOrToken end) => TextSpan.FromBounds((modifiers.Count != 0) ? modifiers.First().SpanStart : start.SpanStart, end.Span.End); private static TextSpan CombineSpans(TextSpan first, TextSpan second, TextSpan defaultSpan) => (first.Length > 0 && second.Length > 0) ? TextSpan.FromBounds(first.Start, second.End) : (first.Length > 0) ? first : (second.Length > 0) ? second : defaultSpan; internal override TextSpan GetLambdaParameterDiagnosticSpan(SyntaxNode lambda, int ordinal) { Debug.Assert(ordinal >= 0); switch (lambda.Kind()) { case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)lambda).ParameterList.Parameters[ordinal].Identifier.Span; case SyntaxKind.SimpleLambdaExpression: Debug.Assert(ordinal == 0); return ((SimpleLambdaExpressionSyntax)lambda).Parameter.Identifier.Span; case SyntaxKind.AnonymousMethodExpression: // since we are given a parameter ordinal there has to be a parameter list: return ((AnonymousMethodExpressionSyntax)lambda).ParameterList!.Parameters[ordinal].Identifier.Span; default: return lambda.Span; } } internal override string GetDisplayName(INamedTypeSymbol symbol) => symbol.TypeKind switch { TypeKind.Struct => symbol.IsRecord ? CSharpFeaturesResources.record_struct : CSharpFeaturesResources.struct_, TypeKind.Class => symbol.IsRecord ? CSharpFeaturesResources.record_ : FeaturesResources.class_, _ => base.GetDisplayName(symbol) }; internal override string GetDisplayName(IPropertySymbol symbol) => symbol.IsIndexer ? CSharpFeaturesResources.indexer : base.GetDisplayName(symbol); internal override string GetDisplayName(IMethodSymbol symbol) => symbol.MethodKind switch { MethodKind.PropertyGet => symbol.AssociatedSymbol is IPropertySymbol { IsIndexer: true } ? CSharpFeaturesResources.indexer_getter : CSharpFeaturesResources.property_getter, MethodKind.PropertySet => symbol.AssociatedSymbol is IPropertySymbol { IsIndexer: true } ? CSharpFeaturesResources.indexer_setter : CSharpFeaturesResources.property_setter, MethodKind.StaticConstructor => FeaturesResources.static_constructor, MethodKind.Destructor => CSharpFeaturesResources.destructor, MethodKind.Conversion => CSharpFeaturesResources.conversion_operator, MethodKind.LocalFunction => FeaturesResources.local_function, _ => base.GetDisplayName(symbol) }; protected override string? TryGetDisplayName(SyntaxNode node, EditKind editKind) => TryGetDisplayNameImpl(node, editKind); internal static new string? GetDisplayName(SyntaxNode node, EditKind editKind) => TryGetDisplayNameImpl(node, editKind) ?? throw ExceptionUtilities.UnexpectedValue(node.Kind()); internal static string? TryGetDisplayNameImpl(SyntaxNode node, EditKind editKind) { switch (node.Kind()) { // top-level case SyntaxKind.CompilationUnit: case SyntaxKind.GlobalStatement: return CSharpFeaturesResources.global_statement; case SyntaxKind.ExternAliasDirective: return CSharpFeaturesResources.extern_alias; case SyntaxKind.UsingDirective: // Dev12 distinguishes using alias from using namespace and reports different errors for removing alias. // None of these changes are allowed anyways, so let's keep it simple. return CSharpFeaturesResources.using_directive; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return FeaturesResources.namespace_; case SyntaxKind.ClassDeclaration: return FeaturesResources.class_; case SyntaxKind.StructDeclaration: return CSharpFeaturesResources.struct_; case SyntaxKind.InterfaceDeclaration: return FeaturesResources.interface_; case SyntaxKind.RecordDeclaration: return CSharpFeaturesResources.record_; case SyntaxKind.RecordStructDeclaration: return CSharpFeaturesResources.record_struct; case SyntaxKind.EnumDeclaration: return FeaturesResources.enum_; case SyntaxKind.DelegateDeclaration: return FeaturesResources.delegate_; case SyntaxKind.FieldDeclaration: var declaration = (FieldDeclarationSyntax)node; return declaration.Modifiers.Any(SyntaxKind.ConstKeyword) ? FeaturesResources.const_field : FeaturesResources.field; case SyntaxKind.EventFieldDeclaration: return CSharpFeaturesResources.event_field; case SyntaxKind.VariableDeclaration: case SyntaxKind.VariableDeclarator: return TryGetDisplayNameImpl(node.Parent!, editKind); case SyntaxKind.MethodDeclaration: return FeaturesResources.method; case SyntaxKind.ConversionOperatorDeclaration: return CSharpFeaturesResources.conversion_operator; case SyntaxKind.OperatorDeclaration: return FeaturesResources.operator_; case SyntaxKind.ConstructorDeclaration: var ctor = (ConstructorDeclarationSyntax)node; return ctor.Modifiers.Any(SyntaxKind.StaticKeyword) ? FeaturesResources.static_constructor : FeaturesResources.constructor; case SyntaxKind.DestructorDeclaration: return CSharpFeaturesResources.destructor; case SyntaxKind.PropertyDeclaration: return SyntaxUtilities.HasBackingField((PropertyDeclarationSyntax)node) ? FeaturesResources.auto_property : FeaturesResources.property_; case SyntaxKind.IndexerDeclaration: return CSharpFeaturesResources.indexer; case SyntaxKind.EventDeclaration: return FeaturesResources.event_; case SyntaxKind.EnumMemberDeclaration: return FeaturesResources.enum_value; case SyntaxKind.GetAccessorDeclaration: if (node.Parent!.Parent!.IsKind(SyntaxKind.PropertyDeclaration)) { return CSharpFeaturesResources.property_getter; } else { RoslynDebug.Assert(node.Parent.Parent.IsKind(SyntaxKind.IndexerDeclaration)); return CSharpFeaturesResources.indexer_getter; } case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: if (node.Parent!.Parent!.IsKind(SyntaxKind.PropertyDeclaration)) { return CSharpFeaturesResources.property_setter; } else { RoslynDebug.Assert(node.Parent.Parent.IsKind(SyntaxKind.IndexerDeclaration)); return CSharpFeaturesResources.indexer_setter; } case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return FeaturesResources.event_accessor; case SyntaxKind.ArrowExpressionClause: return node.Parent!.Kind() switch { SyntaxKind.PropertyDeclaration => CSharpFeaturesResources.property_getter, SyntaxKind.IndexerDeclaration => CSharpFeaturesResources.indexer_getter, _ => null }; case SyntaxKind.TypeParameterConstraintClause: return FeaturesResources.type_constraint; case SyntaxKind.TypeParameterList: case SyntaxKind.TypeParameter: return FeaturesResources.type_parameter; case SyntaxKind.Parameter: return FeaturesResources.parameter; case SyntaxKind.AttributeList: return FeaturesResources.attribute; case SyntaxKind.Attribute: return FeaturesResources.attribute; case SyntaxKind.AttributeTargetSpecifier: return CSharpFeaturesResources.attribute_target; // statement: case SyntaxKind.TryStatement: return CSharpFeaturesResources.try_block; case SyntaxKind.CatchClause: case SyntaxKind.CatchDeclaration: return CSharpFeaturesResources.catch_clause; case SyntaxKind.CatchFilterClause: return CSharpFeaturesResources.filter_clause; case SyntaxKind.FinallyClause: return CSharpFeaturesResources.finally_clause; case SyntaxKind.FixedStatement: return CSharpFeaturesResources.fixed_statement; case SyntaxKind.UsingStatement: return CSharpFeaturesResources.using_statement; case SyntaxKind.LockStatement: return CSharpFeaturesResources.lock_statement; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: return CSharpFeaturesResources.foreach_statement; case SyntaxKind.CheckedStatement: return CSharpFeaturesResources.checked_statement; case SyntaxKind.UncheckedStatement: return CSharpFeaturesResources.unchecked_statement; case SyntaxKind.YieldBreakStatement: return CSharpFeaturesResources.yield_break_statement; case SyntaxKind.YieldReturnStatement: return CSharpFeaturesResources.yield_return_statement; case SyntaxKind.AwaitExpression: return CSharpFeaturesResources.await_expression; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: return CSharpFeaturesResources.lambda; case SyntaxKind.AnonymousMethodExpression: return CSharpFeaturesResources.anonymous_method; case SyntaxKind.FromClause: return CSharpFeaturesResources.from_clause; case SyntaxKind.JoinClause: case SyntaxKind.JoinIntoClause: return CSharpFeaturesResources.join_clause; case SyntaxKind.LetClause: return CSharpFeaturesResources.let_clause; case SyntaxKind.WhereClause: return CSharpFeaturesResources.where_clause; case SyntaxKind.OrderByClause: case SyntaxKind.AscendingOrdering: case SyntaxKind.DescendingOrdering: return CSharpFeaturesResources.orderby_clause; case SyntaxKind.SelectClause: return CSharpFeaturesResources.select_clause; case SyntaxKind.GroupClause: return CSharpFeaturesResources.groupby_clause; case SyntaxKind.QueryBody: return CSharpFeaturesResources.query_body; case SyntaxKind.QueryContinuation: return CSharpFeaturesResources.into_clause; case SyntaxKind.IsPatternExpression: return CSharpFeaturesResources.is_pattern; case SyntaxKind.SimpleAssignmentExpression: if (((AssignmentExpressionSyntax)node).IsDeconstruction()) { return CSharpFeaturesResources.deconstruction; } else { throw ExceptionUtilities.UnexpectedValue(node.Kind()); } case SyntaxKind.TupleType: case SyntaxKind.TupleExpression: return CSharpFeaturesResources.tuple; case SyntaxKind.LocalFunctionStatement: return CSharpFeaturesResources.local_function; case SyntaxKind.DeclarationExpression: return CSharpFeaturesResources.out_var; case SyntaxKind.RefType: case SyntaxKind.RefExpression: return CSharpFeaturesResources.ref_local_or_expression; case SyntaxKind.SwitchStatement: return CSharpFeaturesResources.switch_statement; case SyntaxKind.LocalDeclarationStatement: if (((LocalDeclarationStatementSyntax)node).UsingKeyword.IsKind(SyntaxKind.UsingKeyword)) { return CSharpFeaturesResources.using_declaration; } return CSharpFeaturesResources.local_variable_declaration; default: return null; } } protected override string GetSuspensionPointDisplayName(SyntaxNode node, EditKind editKind) { switch (node.Kind()) { case SyntaxKind.ForEachStatement: Debug.Assert(((CommonForEachStatementSyntax)node).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)); return CSharpFeaturesResources.asynchronous_foreach_statement; case SyntaxKind.VariableDeclarator: RoslynDebug.Assert(((LocalDeclarationStatementSyntax)node.Parent!.Parent!).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)); return CSharpFeaturesResources.asynchronous_using_declaration; default: return base.GetSuspensionPointDisplayName(node, editKind); } } #endregion #region Top-Level Syntactic Rude Edits private readonly struct EditClassifier { private readonly CSharpEditAndContinueAnalyzer _analyzer; private readonly ArrayBuilder<RudeEditDiagnostic> _diagnostics; private readonly Match<SyntaxNode>? _match; private readonly SyntaxNode? _oldNode; private readonly SyntaxNode? _newNode; private readonly EditKind _kind; private readonly TextSpan? _span; public EditClassifier( CSharpEditAndContinueAnalyzer analyzer, ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode? oldNode, SyntaxNode? newNode, EditKind kind, Match<SyntaxNode>? match = null, TextSpan? span = null) { RoslynDebug.Assert(oldNode != null || newNode != null); // if the node is deleted we have map that can be used to closest new ancestor RoslynDebug.Assert(newNode != null || match != null); _analyzer = analyzer; _diagnostics = diagnostics; _oldNode = oldNode; _newNode = newNode; _kind = kind; _span = span; _match = match; } private void ReportError(RudeEditKind kind, SyntaxNode? spanNode = null, SyntaxNode? displayNode = null) { var span = (spanNode != null) ? GetDiagnosticSpan(spanNode, _kind) : GetSpan(); var node = displayNode ?? _newNode ?? _oldNode; var displayName = GetDisplayName(node!, _kind); _diagnostics.Add(new RudeEditDiagnostic(kind, span, node, arguments: new[] { displayName })); } private TextSpan GetSpan() { if (_span.HasValue) { return _span.Value; } if (_newNode == null) { return _analyzer.GetDeletedNodeDiagnosticSpan(_match!.Matches, _oldNode!); } return GetDiagnosticSpan(_newNode, _kind); } public void ClassifyEdit() { switch (_kind) { case EditKind.Delete: ClassifyDelete(_oldNode!); return; case EditKind.Update: ClassifyUpdate(_oldNode!, _newNode!); return; case EditKind.Move: ClassifyMove(_newNode!); return; case EditKind.Insert: ClassifyInsert(_newNode!); return; case EditKind.Reorder: ClassifyReorder(_newNode!); return; default: throw ExceptionUtilities.UnexpectedValue(_kind); } } private void ClassifyMove(SyntaxNode newNode) { if (newNode.IsKind(SyntaxKind.LocalFunctionStatement)) { return; } // We could perhaps allow moving a type declaration to a different namespace syntax node // as long as it represents semantically the same namespace as the one of the original type declaration. ReportError(RudeEditKind.Move); } private void ClassifyReorder(SyntaxNode newNode) { if (_newNode.IsKind(SyntaxKind.LocalFunctionStatement)) { return; } switch (newNode.Kind()) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.VariableDeclarator: // Maybe we could allow changing order of field declarations unless the containing type layout is sequential. ReportError(RudeEditKind.Move); return; case SyntaxKind.EnumMemberDeclaration: // To allow this change we would need to check that values of all fields of the enum // are preserved, or make sure we can update all method bodies that accessed those that changed. ReportError(RudeEditKind.Move); return; case SyntaxKind.TypeParameter: case SyntaxKind.Parameter: ReportError(RudeEditKind.Move); return; } } private void ClassifyInsert(SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.ExternAliasDirective: case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: ReportError(RudeEditKind.Insert); return; case SyntaxKind.Attribute: case SyntaxKind.AttributeList: // To allow inserting of attributes we need to check if the inserted attribute // is a pseudo-custom attribute that CLR allows us to change, or if it is a compiler well-know attribute // that affects the generated IL, so we defer those checks until semantic analysis. // Unless the attribute is a module/assembly attribute if (node.IsParentKind(SyntaxKind.CompilationUnit) || node.Parent.IsParentKind(SyntaxKind.CompilationUnit)) { ReportError(RudeEditKind.Insert); } return; } } private void ClassifyDelete(SyntaxNode oldNode) { switch (oldNode.Kind()) { case SyntaxKind.ExternAliasDirective: case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: // To allow removal of declarations we would need to update method bodies that // were previously binding to them but now are binding to another symbol that was previously hidden. ReportError(RudeEditKind.Delete); return; case SyntaxKind.AttributeList: case SyntaxKind.Attribute: // To allow removal of attributes we need to check if the removed attribute // is a pseudo-custom attribute that CLR does not allow us to change, or if it is a compiler well-know attribute // that affects the generated IL, so we defer those checks until semantic analysis. // Unless the attribute is a module/assembly attribute if (oldNode.IsParentKind(SyntaxKind.CompilationUnit) || oldNode.Parent.IsParentKind(SyntaxKind.CompilationUnit)) { ReportError(RudeEditKind.Delete); } return; } } private void ClassifyUpdate(SyntaxNode oldNode, SyntaxNode newNode) { switch (newNode.Kind()) { case SyntaxKind.ExternAliasDirective: ReportError(RudeEditKind.Update); return; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: ClassifyUpdate((BaseNamespaceDeclarationSyntax)oldNode, (BaseNamespaceDeclarationSyntax)newNode); return; case SyntaxKind.Attribute: // To allow update of attributes we need to check if the updated attribute // is a pseudo-custom attribute that CLR allows us to change, or if it is a compiler well-know attribute // that affects the generated IL, so we defer those checks until semantic analysis. // Unless the attribute is a module/assembly attribute if (newNode.IsParentKind(SyntaxKind.CompilationUnit) || newNode.Parent.IsParentKind(SyntaxKind.CompilationUnit)) { ReportError(RudeEditKind.Update); } return; } } private void ClassifyUpdate(BaseNamespaceDeclarationSyntax oldNode, BaseNamespaceDeclarationSyntax newNode) { Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.Name, newNode.Name)); ReportError(RudeEditKind.Renamed); } public void ClassifyDeclarationBodyRudeUpdates(SyntaxNode newDeclarationOrBody) { foreach (var node in newDeclarationOrBody.DescendantNodesAndSelf(LambdaUtilities.IsNotLambda)) { switch (node.Kind()) { case SyntaxKind.StackAllocArrayCreationExpression: case SyntaxKind.ImplicitStackAllocArrayCreationExpression: ReportError(RudeEditKind.StackAllocUpdate, node, _newNode); return; } } } } internal override void ReportTopLevelSyntacticRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, Edit<SyntaxNode> edit, Dictionary<SyntaxNode, EditKind> editMap) { if (HasParentEdit(editMap, edit)) { return; } var classifier = new EditClassifier(this, diagnostics, edit.OldNode, edit.NewNode, edit.Kind, match); classifier.ClassifyEdit(); } internal override void ReportMemberBodyUpdateRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newMember, TextSpan? span) { var classifier = new EditClassifier(this, diagnostics, oldNode: null, newMember, EditKind.Update, span: span); classifier.ClassifyDeclarationBodyRudeUpdates(newMember); } #endregion #region Semantic Rude Edits internal override void ReportInsertedMemberSymbolRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol newSymbol, SyntaxNode newNode, bool insertingIntoExistingContainingType) { var rudeEditKind = newSymbol switch { // Inserting extern member into a new or existing type is not allowed. { IsExtern: true } => RudeEditKind.InsertExtern, // All rude edits below only apply when inserting into an existing type (not when the type itself is inserted): _ when !insertingIntoExistingContainingType => RudeEditKind.None, // Inserting a member into an existing generic type is not allowed. { ContainingType: { Arity: > 0 } } and not INamedTypeSymbol => RudeEditKind.InsertIntoGenericType, // Inserting virtual or interface member into an existing type is not allowed. { IsVirtual: true } or { IsOverride: true } or { IsAbstract: true } and not INamedTypeSymbol => RudeEditKind.InsertVirtual, // Inserting generic method into an existing type is not allowed. IMethodSymbol { Arity: > 0 } => RudeEditKind.InsertGenericMethod, // Inserting destructor to an existing type is not allowed. IMethodSymbol { MethodKind: MethodKind.Destructor } => RudeEditKind.Insert, // Inserting operator to an existing type is not allowed. IMethodSymbol { MethodKind: MethodKind.Conversion or MethodKind.UserDefinedOperator } => RudeEditKind.InsertOperator, // Inserting a method that explictly implements an interface method into an existing type is not allowed. IMethodSymbol { ExplicitInterfaceImplementations: { IsEmpty: false } } => RudeEditKind.InsertMethodWithExplicitInterfaceSpecifier, // TODO: Inserting non-virtual member to an interface (https://github.com/dotnet/roslyn/issues/37128) { ContainingType: { TypeKind: TypeKind.Interface } } and not INamedTypeSymbol => RudeEditKind.InsertIntoInterface, // Inserting a field into an enum: #pragma warning disable format // https://github.com/dotnet/roslyn/issues/54759 IFieldSymbol { ContainingType.TypeKind: TypeKind.Enum } => RudeEditKind.Insert, #pragma warning restore format _ => RudeEditKind.None }; if (rudeEditKind != RudeEditKind.None) { diagnostics.Add(new RudeEditDiagnostic( rudeEditKind, GetDiagnosticSpan(newNode, EditKind.Insert), newNode, arguments: new[] { GetDisplayName(newNode, EditKind.Insert) })); } } #endregion #region Exception Handling Rude Edits /// <summary> /// Return nodes that represent exception handlers encompassing the given active statement node. /// </summary> protected override List<SyntaxNode> GetExceptionHandlingAncestors(SyntaxNode node, bool isNonLeaf) { var result = new List<SyntaxNode>(); var current = node; while (current != null) { var kind = current.Kind(); switch (kind) { case SyntaxKind.TryStatement: if (isNonLeaf) { result.Add(current); } break; case SyntaxKind.CatchClause: case SyntaxKind.FinallyClause: result.Add(current); // skip try: RoslynDebug.Assert(current.Parent is object); RoslynDebug.Assert(current.Parent.Kind() == SyntaxKind.TryStatement); current = current.Parent; break; // stop at type declaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return result; } // stop at lambda: if (LambdaUtilities.IsLambda(current)) { return result; } current = current.Parent; } return result; } internal override void ReportEnclosingExceptionHandlingRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, IEnumerable<Edit<SyntaxNode>> exceptionHandlingEdits, SyntaxNode oldStatement, TextSpan newStatementSpan) { foreach (var edit in exceptionHandlingEdits) { // try/catch/finally have distinct labels so only the nodes of the same kind may match: Debug.Assert(edit.Kind != EditKind.Update || edit.OldNode.RawKind == edit.NewNode.RawKind); if (edit.Kind != EditKind.Update || !AreExceptionClausesEquivalent(edit.OldNode, edit.NewNode)) { AddAroundActiveStatementRudeDiagnostic(diagnostics, edit.OldNode, edit.NewNode, newStatementSpan); } } } private static bool AreExceptionClausesEquivalent(SyntaxNode oldNode, SyntaxNode newNode) { switch (oldNode.Kind()) { case SyntaxKind.TryStatement: var oldTryStatement = (TryStatementSyntax)oldNode; var newTryStatement = (TryStatementSyntax)newNode; return SyntaxFactory.AreEquivalent(oldTryStatement.Finally, newTryStatement.Finally) && SyntaxFactory.AreEquivalent(oldTryStatement.Catches, newTryStatement.Catches); case SyntaxKind.CatchClause: case SyntaxKind.FinallyClause: return SyntaxFactory.AreEquivalent(oldNode, newNode); default: throw ExceptionUtilities.UnexpectedValue(oldNode.Kind()); } } /// <summary> /// An active statement (leaf or not) inside a "catch" makes the catch block read-only. /// An active statement (leaf or not) inside a "finally" makes the whole try/catch/finally block read-only. /// An active statement (non leaf) inside a "try" makes the catch/finally block read-only. /// </summary> /// <remarks> /// Exception handling regions are only needed to be tracked if they contain user code. /// <see cref="UsingStatementSyntax"/> and using <see cref="LocalDeclarationStatementSyntax"/> generate finally blocks, /// but they do not contain non-hidden sequence points. /// </remarks> /// <param name="node">An exception handling ancestor of an active statement node.</param> /// <param name="coversAllChildren"> /// True if all child nodes of the <paramref name="node"/> are contained in the exception region represented by the <paramref name="node"/>. /// </param> protected override TextSpan GetExceptionHandlingRegion(SyntaxNode node, out bool coversAllChildren) { TryStatementSyntax tryStatement; switch (node.Kind()) { case SyntaxKind.TryStatement: tryStatement = (TryStatementSyntax)node; coversAllChildren = false; if (tryStatement.Catches.Count == 0) { RoslynDebug.Assert(tryStatement.Finally != null); return tryStatement.Finally.Span; } return TextSpan.FromBounds( tryStatement.Catches.First().SpanStart, (tryStatement.Finally != null) ? tryStatement.Finally.Span.End : tryStatement.Catches.Last().Span.End); case SyntaxKind.CatchClause: coversAllChildren = true; return node.Span; case SyntaxKind.FinallyClause: coversAllChildren = true; tryStatement = (TryStatementSyntax)node.Parent!; return tryStatement.Span; default: throw ExceptionUtilities.UnexpectedValue(node.Kind()); } } #endregion #region State Machines internal override bool IsStateMachineMethod(SyntaxNode declaration) => SyntaxUtilities.IsAsyncDeclaration(declaration) || SyntaxUtilities.GetSuspensionPoints(declaration).Any(); protected override void GetStateMachineInfo(SyntaxNode body, out ImmutableArray<SyntaxNode> suspensionPoints, out StateMachineKinds kinds) { suspensionPoints = SyntaxUtilities.GetSuspensionPoints(body).ToImmutableArray(); kinds = StateMachineKinds.None; if (suspensionPoints.Any(n => n.IsKind(SyntaxKind.YieldBreakStatement) || n.IsKind(SyntaxKind.YieldReturnStatement))) { kinds |= StateMachineKinds.Iterator; } if (SyntaxUtilities.IsAsyncDeclaration(body.Parent)) { kinds |= StateMachineKinds.Async; } } internal override void ReportStateMachineSuspensionPointRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode) { // TODO: changes around suspension points (foreach, lock, using, etc.) if (newNode.IsKind(SyntaxKind.AwaitExpression)) { var oldContainingStatementPart = FindContainingStatementPart(oldNode); var newContainingStatementPart = FindContainingStatementPart(newNode); // If the old statement has spilled state and the new doesn't the edit is ok. We'll just not use the spilled state. if (!SyntaxFactory.AreEquivalent(oldContainingStatementPart, newContainingStatementPart) && !HasNoSpilledState(newNode, newContainingStatementPart)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.AwaitStatementUpdate, newContainingStatementPart.Span)); } } } internal override void ReportStateMachineSuspensionPointDeletedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode deletedSuspensionPoint) { // Handle deletion of await keyword from await foreach statement. if (deletedSuspensionPoint is CommonForEachStatementSyntax deletedForeachStatement && match.Matches.TryGetValue(deletedSuspensionPoint, out var newForEachStatement) && newForEachStatement is CommonForEachStatementSyntax && deletedForeachStatement.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingFromAsynchronousToSynchronous, GetDiagnosticSpan(newForEachStatement, EditKind.Update), newForEachStatement, new[] { GetDisplayName(newForEachStatement, EditKind.Update) })); return; } // Handle deletion of await keyword from await using declaration. if (deletedSuspensionPoint.IsKind(SyntaxKind.VariableDeclarator) && match.Matches.TryGetValue(deletedSuspensionPoint.Parent!.Parent!, out var newLocalDeclaration) && !((LocalDeclarationStatementSyntax)newLocalDeclaration).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingFromAsynchronousToSynchronous, GetDiagnosticSpan(newLocalDeclaration, EditKind.Update), newLocalDeclaration, new[] { GetDisplayName(newLocalDeclaration, EditKind.Update) })); return; } base.ReportStateMachineSuspensionPointDeletedRudeEdit(diagnostics, match, deletedSuspensionPoint); } internal override void ReportStateMachineSuspensionPointInsertedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode insertedSuspensionPoint, bool aroundActiveStatement) { // Handle addition of await keyword to foreach statement. if (insertedSuspensionPoint is CommonForEachStatementSyntax insertedForEachStatement && match.ReverseMatches.TryGetValue(insertedSuspensionPoint, out var oldNode) && oldNode is CommonForEachStatementSyntax oldForEachStatement && !oldForEachStatement.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Insert, insertedForEachStatement.AwaitKeyword.Span, insertedForEachStatement, new[] { insertedForEachStatement.AwaitKeyword.ToString() })); return; } // Handle addition of using keyword to using declaration. if (insertedSuspensionPoint.IsKind(SyntaxKind.VariableDeclarator) && match.ReverseMatches.TryGetValue(insertedSuspensionPoint.Parent!.Parent!, out var oldLocalDeclaration) && !((LocalDeclarationStatementSyntax)oldLocalDeclaration).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) { var newLocalDeclaration = (LocalDeclarationStatementSyntax)insertedSuspensionPoint!.Parent!.Parent!; diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Insert, newLocalDeclaration.AwaitKeyword.Span, newLocalDeclaration, new[] { newLocalDeclaration.AwaitKeyword.ToString() })); return; } base.ReportStateMachineSuspensionPointInsertedRudeEdit(diagnostics, match, insertedSuspensionPoint, aroundActiveStatement); } private static SyntaxNode FindContainingStatementPart(SyntaxNode node) { while (true) { if (node is StatementSyntax statement) { return statement; } RoslynDebug.Assert(node is object); RoslynDebug.Assert(node.Parent is object); switch (node.Parent.Kind()) { case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.IfStatement: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.LockStatement: case SyntaxKind.UsingStatement: case SyntaxKind.ArrowExpressionClause: return node; } if (LambdaUtilities.IsLambdaBodyStatementOrExpression(node)) { return node; } node = node.Parent; } } private static bool HasNoSpilledState(SyntaxNode awaitExpression, SyntaxNode containingStatementPart) { Debug.Assert(awaitExpression.IsKind(SyntaxKind.AwaitExpression)); // There is nothing within the statement part surrounding the await expression. if (containingStatementPart == awaitExpression) { return true; } switch (containingStatementPart.Kind()) { case SyntaxKind.ExpressionStatement: case SyntaxKind.ReturnStatement: var expression = GetExpressionFromStatementPart(containingStatementPart); // await expr; // return await expr; if (expression == awaitExpression) { return true; } // identifier = await expr; // return identifier = await expr; return IsSimpleAwaitAssignment(expression, awaitExpression); case SyntaxKind.VariableDeclaration: // var idf = await expr in using, for, etc. // EqualsValueClause -> VariableDeclarator -> VariableDeclaration return awaitExpression.Parent!.Parent!.Parent == containingStatementPart; case SyntaxKind.LocalDeclarationStatement: // var idf = await expr; // EqualsValueClause -> VariableDeclarator -> VariableDeclaration -> LocalDeclarationStatement return awaitExpression.Parent!.Parent!.Parent!.Parent == containingStatementPart; } return IsSimpleAwaitAssignment(containingStatementPart, awaitExpression); } private static ExpressionSyntax GetExpressionFromStatementPart(SyntaxNode statement) { switch (statement.Kind()) { case SyntaxKind.ExpressionStatement: return ((ExpressionStatementSyntax)statement).Expression; case SyntaxKind.ReturnStatement: // Must have an expression since we are only inspecting at statements that contain an expression. return ((ReturnStatementSyntax)statement).Expression!; default: throw ExceptionUtilities.UnexpectedValue(statement.Kind()); } } private static bool IsSimpleAwaitAssignment(SyntaxNode node, SyntaxNode awaitExpression) { if (node.IsKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment)) { return assignment.Left.IsKind(SyntaxKind.IdentifierName) && assignment.Right == awaitExpression; } return false; } #endregion #region Rude Edits around Active Statement internal override void ReportOtherRudeEditsAroundActiveStatement( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement, bool isNonLeaf) { ReportRudeEditsForSwitchWhenClauses(diagnostics, oldActiveStatement, newActiveStatement); ReportRudeEditsForAncestorsDeclaringInterStatementTemps(diagnostics, match, oldActiveStatement, newActiveStatement); ReportRudeEditsForCheckedStatements(diagnostics, oldActiveStatement, newActiveStatement, isNonLeaf); } /// <summary> /// Reports rude edits when an active statement is a when clause in a switch statement and any of the switch cases or the switch value changed. /// This is necessary since the switch emits long-lived synthesized variables to store results of pattern evaluations. /// These synthesized variables are mapped to the slots of the new methods via ordinals. The mapping preserves the values of these variables as long as /// exactly the same variables are emitted for the new switch as they were for the old one and their order didn't change either. /// This is guaranteed if none of the case clauses have changed. /// </summary> private void ReportRudeEditsForSwitchWhenClauses(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement) { if (!oldActiveStatement.IsKind(SyntaxKind.WhenClause)) { return; } // switch expression does not have sequence points (active statements): if (oldActiveStatement.Parent!.Parent!.Parent is not SwitchStatementSyntax oldSwitch) { return; } // switch statement does not match switch expression, so it must be part of a switch statement as well. var newSwitch = (SwitchStatementSyntax)newActiveStatement.Parent!.Parent!.Parent!; // when clauses can only match other when clauses: Debug.Assert(newActiveStatement.IsKind(SyntaxKind.WhenClause)); if (!AreEquivalentIgnoringLambdaBodies(oldSwitch.Expression, newSwitch.Expression)) { AddRudeUpdateAroundActiveStatement(diagnostics, newSwitch); } if (!AreEquivalentSwitchStatementDecisionTrees(oldSwitch, newSwitch)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdateAroundActiveStatement, GetDiagnosticSpan(newSwitch, EditKind.Update), newSwitch, new[] { CSharpFeaturesResources.switch_statement_case_clause })); } } private static bool AreEquivalentSwitchStatementDecisionTrees(SwitchStatementSyntax oldSwitch, SwitchStatementSyntax newSwitch) => oldSwitch.Sections.SequenceEqual(newSwitch.Sections, AreSwitchSectionsEquivalent); private static bool AreSwitchSectionsEquivalent(SwitchSectionSyntax oldSection, SwitchSectionSyntax newSection) => oldSection.Labels.SequenceEqual(newSection.Labels, AreLabelsEquivalent); private static bool AreLabelsEquivalent(SwitchLabelSyntax oldLabel, SwitchLabelSyntax newLabel) { if (oldLabel.IsKind(SyntaxKind.CasePatternSwitchLabel, out CasePatternSwitchLabelSyntax? oldCasePatternLabel) && newLabel.IsKind(SyntaxKind.CasePatternSwitchLabel, out CasePatternSwitchLabelSyntax? newCasePatternLabel)) { // ignore the actual when expressions: return SyntaxFactory.AreEquivalent(oldCasePatternLabel.Pattern, newCasePatternLabel.Pattern) && (oldCasePatternLabel.WhenClause != null) == (newCasePatternLabel.WhenClause != null); } else { return SyntaxFactory.AreEquivalent(oldLabel, newLabel); } } private void ReportRudeEditsForCheckedStatements( ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement, bool isNonLeaf) { // checked context can't be changed around non-leaf active statement: if (!isNonLeaf) { return; } // Changing checked context around an internal active statement may change the instructions // executed after method calls in the active statement but before the next sequence point. // Since the debugger remaps the IP at the first sequence point following a call instruction // allowing overflow context to be changed may lead to execution of code with old semantics. var oldCheckedStatement = TryGetCheckedStatementAncestor(oldActiveStatement); var newCheckedStatement = TryGetCheckedStatementAncestor(newActiveStatement); bool isRude; if (oldCheckedStatement == null || newCheckedStatement == null) { isRude = oldCheckedStatement != newCheckedStatement; } else { isRude = oldCheckedStatement.Kind() != newCheckedStatement.Kind(); } if (isRude) { AddAroundActiveStatementRudeDiagnostic(diagnostics, oldCheckedStatement, newCheckedStatement, newActiveStatement.Span); } } private static CheckedStatementSyntax? TryGetCheckedStatementAncestor(SyntaxNode? node) { // Ignoring lambda boundaries since checked context flows through. while (node != null) { switch (node.Kind()) { case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return (CheckedStatementSyntax)node; } node = node.Parent; } return null; } private void ReportRudeEditsForAncestorsDeclaringInterStatementTemps( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement) { // Rude Edits for fixed/using/lock/foreach statements that are added/updated around an active statement. // Although such changes are technically possible, they might lead to confusion since // the temporary variables these statements generate won't be properly initialized. // // We use a simple algorithm to match each new node with its old counterpart. // If all nodes match this algorithm is linear, otherwise it's quadratic. // // Unlike exception regions matching where we use LCS, we allow reordering of the statements. ReportUnmatchedStatements<LockStatementSyntax>(diagnostics, match, n => n.IsKind(SyntaxKind.LockStatement), oldActiveStatement, newActiveStatement, areEquivalent: AreEquivalentActiveStatements, areSimilar: null); ReportUnmatchedStatements<FixedStatementSyntax>(diagnostics, match, n => n.IsKind(SyntaxKind.FixedStatement), oldActiveStatement, newActiveStatement, areEquivalent: AreEquivalentActiveStatements, areSimilar: (n1, n2) => DeclareSameIdentifiers(n1.Declaration.Variables, n2.Declaration.Variables)); // Using statements with declaration do not introduce compiler generated temporary. ReportUnmatchedStatements<UsingStatementSyntax>( diagnostics, match, n => n.IsKind(SyntaxKind.UsingStatement, out UsingStatementSyntax? usingStatement) && usingStatement.Declaration is null, oldActiveStatement, newActiveStatement, areEquivalent: AreEquivalentActiveStatements, areSimilar: null); ReportUnmatchedStatements<CommonForEachStatementSyntax>( diagnostics, match, n => n.IsKind(SyntaxKind.ForEachStatement) || n.IsKind(SyntaxKind.ForEachVariableStatement), oldActiveStatement, newActiveStatement, areEquivalent: AreEquivalentActiveStatements, areSimilar: AreSimilarActiveStatements); } private static bool DeclareSameIdentifiers(SeparatedSyntaxList<VariableDeclaratorSyntax> oldVariables, SeparatedSyntaxList<VariableDeclaratorSyntax> newVariables) => DeclareSameIdentifiers(oldVariables.Select(v => v.Identifier).ToArray(), newVariables.Select(v => v.Identifier).ToArray()); private static bool DeclareSameIdentifiers(SyntaxToken[] oldVariables, SyntaxToken[] newVariables) { if (oldVariables.Length != newVariables.Length) { return false; } for (var i = 0; i < oldVariables.Length; i++) { if (!SyntaxFactory.AreEquivalent(oldVariables[i], newVariables[i])) { return false; } } return true; } #endregion } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/VisualStudio/LiveShare/Impl/ProjectsHandler.Exports.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.LiveShare.CustomProtocol; using Microsoft.VisualStudio.LiveShare.LanguageServices; namespace Microsoft.VisualStudio.LanguageServices.LiveShare { [ExportLspRequestHandler(LiveShareConstants.RoslynContractName, RoslynMethods.ProjectsName)] [Obsolete("Used for backwards compatibility with old liveshare clients.")] internal class RoslynProjectsHandler : ProjectsHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RoslynProjectsHandler() { } } [ExportLspRequestHandler(LiveShareConstants.CSharpContractName, RoslynMethods.ProjectsName)] internal class CSharpProjectsHandler : ProjectsHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpProjectsHandler() { } } [ExportLspRequestHandler(LiveShareConstants.VisualBasicContractName, RoslynMethods.ProjectsName)] internal class VisualBasicProjectsHandler : ProjectsHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualBasicProjectsHandler() { } } [ExportLspRequestHandler(LiveShareConstants.TypeScriptContractName, RoslynMethods.ProjectsName)] internal class TypeScriptProjectsHandler : ProjectsHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TypeScriptProjectsHandler() { } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.LiveShare.CustomProtocol; using Microsoft.VisualStudio.LiveShare.LanguageServices; namespace Microsoft.VisualStudio.LanguageServices.LiveShare { [ExportLspRequestHandler(LiveShareConstants.RoslynContractName, RoslynMethods.ProjectsName)] [Obsolete("Used for backwards compatibility with old liveshare clients.")] internal class RoslynProjectsHandler : ProjectsHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RoslynProjectsHandler() { } } [ExportLspRequestHandler(LiveShareConstants.CSharpContractName, RoslynMethods.ProjectsName)] internal class CSharpProjectsHandler : ProjectsHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpProjectsHandler() { } } [ExportLspRequestHandler(LiveShareConstants.VisualBasicContractName, RoslynMethods.ProjectsName)] internal class VisualBasicProjectsHandler : ProjectsHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualBasicProjectsHandler() { } } [ExportLspRequestHandler(LiveShareConstants.TypeScriptContractName, RoslynMethods.ProjectsName)] internal class TypeScriptProjectsHandler : ProjectsHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TypeScriptProjectsHandler() { } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/EditorFeatures/TestUtilities/Diagnostics/TestDiagnosticAnalyzerDriver.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Diagnostics { public class TestDiagnosticAnalyzerDriver { private readonly DiagnosticAnalyzerService _diagnosticAnalyzerService; private readonly bool _includeSuppressedDiagnostics; public TestDiagnosticAnalyzerDriver(Workspace workspace, Project project, bool includeSuppressedDiagnostics = false) { Assert.IsType<MockDiagnosticUpdateSourceRegistrationService>(((IMefHostExportProvider)workspace.Services.HostServices).GetExportedValue<IDiagnosticUpdateSourceRegistrationService>()); _diagnosticAnalyzerService = Assert.IsType<DiagnosticAnalyzerService>(((IMefHostExportProvider)workspace.Services.HostServices).GetExportedValue<IDiagnosticAnalyzerService>()); _diagnosticAnalyzerService.CreateIncrementalAnalyzer(project.Solution.Workspace); _includeSuppressedDiagnostics = includeSuppressedDiagnostics; } private async Task<IEnumerable<Diagnostic>> GetDiagnosticsAsync( Project project, Document document, TextSpan? filterSpan, bool getDocumentDiagnostics, bool getProjectDiagnostics) { var documentDiagnostics = SpecializedCollections.EmptyEnumerable<Diagnostic>(); var projectDiagnostics = SpecializedCollections.EmptyEnumerable<Diagnostic>(); if (getDocumentDiagnostics) { var dxs = await _diagnosticAnalyzerService.GetDiagnosticsAsync(project.Solution, project.Id, document.Id, _includeSuppressedDiagnostics); documentDiagnostics = await CodeAnalysis.Diagnostics.Extensions.ToDiagnosticsAsync( filterSpan is null ? dxs.Where(d => d.HasTextSpan) : dxs.Where(d => d.HasTextSpan && d.GetTextSpan().IntersectsWith(filterSpan.Value)), project, CancellationToken.None); } if (getProjectDiagnostics) { var dxs = await _diagnosticAnalyzerService.GetDiagnosticsAsync(project.Solution, project.Id, includeSuppressedDiagnostics: _includeSuppressedDiagnostics); projectDiagnostics = await CodeAnalysis.Diagnostics.Extensions.ToDiagnosticsAsync(dxs.Where(d => !d.HasTextSpan), project, CancellationToken.None); } var allDiagnostics = documentDiagnostics.Concat(projectDiagnostics); if (!_includeSuppressedDiagnostics) { Assert.True(!allDiagnostics.Any(d => d.IsSuppressed)); } return allDiagnostics; } public Task<IEnumerable<Diagnostic>> GetAllDiagnosticsAsync(Document document, TextSpan? filterSpan) => GetDiagnosticsAsync(document.Project, document, filterSpan, getDocumentDiagnostics: true, getProjectDiagnostics: true); public async Task<IEnumerable<Diagnostic>> GetAllDiagnosticsAsync(Project project) { var diagnostics = new List<Diagnostic>(); foreach (var document in project.Documents) { var span = (await document.GetSyntaxRootAsync()).FullSpan; var documentDiagnostics = await GetDocumentDiagnosticsAsync(document, span); diagnostics.AddRange(documentDiagnostics); } var projectDiagnostics = await GetProjectDiagnosticsAsync(project); diagnostics.AddRange(projectDiagnostics); return diagnostics; } public Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, TextSpan span) => GetDiagnosticsAsync(document.Project, document, span, getDocumentDiagnostics: true, getProjectDiagnostics: false); public Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project) => GetDiagnosticsAsync(project, document: null, filterSpan: null, getDocumentDiagnostics: false, getProjectDiagnostics: true); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Diagnostics { public class TestDiagnosticAnalyzerDriver { private readonly DiagnosticAnalyzerService _diagnosticAnalyzerService; private readonly bool _includeSuppressedDiagnostics; public TestDiagnosticAnalyzerDriver(Workspace workspace, Project project, bool includeSuppressedDiagnostics = false) { Assert.IsType<MockDiagnosticUpdateSourceRegistrationService>(((IMefHostExportProvider)workspace.Services.HostServices).GetExportedValue<IDiagnosticUpdateSourceRegistrationService>()); _diagnosticAnalyzerService = Assert.IsType<DiagnosticAnalyzerService>(((IMefHostExportProvider)workspace.Services.HostServices).GetExportedValue<IDiagnosticAnalyzerService>()); _diagnosticAnalyzerService.CreateIncrementalAnalyzer(project.Solution.Workspace); _includeSuppressedDiagnostics = includeSuppressedDiagnostics; } private async Task<IEnumerable<Diagnostic>> GetDiagnosticsAsync( Project project, Document document, TextSpan? filterSpan, bool getDocumentDiagnostics, bool getProjectDiagnostics) { var documentDiagnostics = SpecializedCollections.EmptyEnumerable<Diagnostic>(); var projectDiagnostics = SpecializedCollections.EmptyEnumerable<Diagnostic>(); if (getDocumentDiagnostics) { var dxs = await _diagnosticAnalyzerService.GetDiagnosticsAsync(project.Solution, project.Id, document.Id, _includeSuppressedDiagnostics); documentDiagnostics = await CodeAnalysis.Diagnostics.Extensions.ToDiagnosticsAsync( filterSpan is null ? dxs.Where(d => d.HasTextSpan) : dxs.Where(d => d.HasTextSpan && d.GetTextSpan().IntersectsWith(filterSpan.Value)), project, CancellationToken.None); } if (getProjectDiagnostics) { var dxs = await _diagnosticAnalyzerService.GetDiagnosticsAsync(project.Solution, project.Id, includeSuppressedDiagnostics: _includeSuppressedDiagnostics); projectDiagnostics = await CodeAnalysis.Diagnostics.Extensions.ToDiagnosticsAsync(dxs.Where(d => !d.HasTextSpan), project, CancellationToken.None); } var allDiagnostics = documentDiagnostics.Concat(projectDiagnostics); if (!_includeSuppressedDiagnostics) { Assert.True(!allDiagnostics.Any(d => d.IsSuppressed)); } return allDiagnostics; } public Task<IEnumerable<Diagnostic>> GetAllDiagnosticsAsync(Document document, TextSpan? filterSpan) => GetDiagnosticsAsync(document.Project, document, filterSpan, getDocumentDiagnostics: true, getProjectDiagnostics: true); public async Task<IEnumerable<Diagnostic>> GetAllDiagnosticsAsync(Project project) { var diagnostics = new List<Diagnostic>(); foreach (var document in project.Documents) { var span = (await document.GetSyntaxRootAsync()).FullSpan; var documentDiagnostics = await GetDocumentDiagnosticsAsync(document, span); diagnostics.AddRange(documentDiagnostics); } var projectDiagnostics = await GetProjectDiagnosticsAsync(project); diagnostics.AddRange(projectDiagnostics); return diagnostics; } public Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, TextSpan span) => GetDiagnosticsAsync(document.Project, document, span, getDocumentDiagnostics: true, getProjectDiagnostics: false); public Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project) => GetDiagnosticsAsync(project, document: null, filterSpan: null, getDocumentDiagnostics: false, getProjectDiagnostics: true); } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Compilers/Core/Portable/Symbols/Attributes/CommonPropertyWellKnownAttributeData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Information decoded from well-known custom attributes applied on a property. /// </summary> internal class CommonPropertyWellKnownAttributeData : WellKnownAttributeData { #region SpecialNameAttribute private bool _hasSpecialNameAttribute; public bool HasSpecialNameAttribute { get { VerifySealed(expected: true); return _hasSpecialNameAttribute; } set { VerifySealed(expected: false); _hasSpecialNameAttribute = value; SetDataStored(); } } #endregion #region ExcludeFromCodeCoverageAttribute private bool _hasExcludeFromCodeCoverageAttribute; public bool HasExcludeFromCodeCoverageAttribute { get { VerifySealed(expected: true); return _hasExcludeFromCodeCoverageAttribute; } set { VerifySealed(expected: false); _hasExcludeFromCodeCoverageAttribute = value; SetDataStored(); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Information decoded from well-known custom attributes applied on a property. /// </summary> internal class CommonPropertyWellKnownAttributeData : WellKnownAttributeData { #region SpecialNameAttribute private bool _hasSpecialNameAttribute; public bool HasSpecialNameAttribute { get { VerifySealed(expected: true); return _hasSpecialNameAttribute; } set { VerifySealed(expected: false); _hasSpecialNameAttribute = value; SetDataStored(); } } #endregion #region ExcludeFromCodeCoverageAttribute private bool _hasExcludeFromCodeCoverageAttribute; public bool HasExcludeFromCodeCoverageAttribute { get { VerifySealed(expected: true); return _hasExcludeFromCodeCoverageAttribute; } set { VerifySealed(expected: false); _hasExcludeFromCodeCoverageAttribute = value; SetDataStored(); } } #endregion } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Declarations/EventKeywordRecommender.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations ''' <summary> ''' Recommends the "Event" keyword in type declaration contexts ''' </summary> Friend Class EventKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Event", VBFeaturesResources.Declares_a_user_defined_event)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.IsTypeMemberDeclarationKeywordContext OrElse context.IsInterfaceMemberDeclarationKeywordContext Then Dim modifiers = context.ModifierCollectionFacts If modifiers.CouldApplyToOneOf(PossibleDeclarationTypes.Event) Then Return s_keywords End If End If ' We also allow "Event" after Custom (which is parsed as an identifier) in a class/structure declaration context If context.FollowsEndOfStatement Then Return ImmutableArray(Of RecommendedKeyword).Empty End If Dim targetToken = context.TargetToken If targetToken.Kind = SyntaxKind.IdentifierToken AndAlso SyntaxFacts.GetContextualKeywordKind(targetToken.GetIdentifierText()) = SyntaxKind.CustomKeyword Then If targetToken.GetAncestor(Of MethodBlockBaseSyntax)() Is Nothing AndAlso targetToken.GetInnermostDeclarationContext().IsKind(SyntaxKind.StructureBlock, SyntaxKind.ClassBlock) Then Dim variableDeclarator = targetToken.GetAncestor(Of VariableDeclaratorSyntax)() If variableDeclarator IsNot Nothing Then If variableDeclarator.Names.Count = 1 AndAlso variableDeclarator.Names.First().Identifier = targetToken Then Return s_keywords End If End If End If End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations ''' <summary> ''' Recommends the "Event" keyword in type declaration contexts ''' </summary> Friend Class EventKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Event", VBFeaturesResources.Declares_a_user_defined_event)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.IsTypeMemberDeclarationKeywordContext OrElse context.IsInterfaceMemberDeclarationKeywordContext Then Dim modifiers = context.ModifierCollectionFacts If modifiers.CouldApplyToOneOf(PossibleDeclarationTypes.Event) Then Return s_keywords End If End If ' We also allow "Event" after Custom (which is parsed as an identifier) in a class/structure declaration context If context.FollowsEndOfStatement Then Return ImmutableArray(Of RecommendedKeyword).Empty End If Dim targetToken = context.TargetToken If targetToken.Kind = SyntaxKind.IdentifierToken AndAlso SyntaxFacts.GetContextualKeywordKind(targetToken.GetIdentifierText()) = SyntaxKind.CustomKeyword Then If targetToken.GetAncestor(Of MethodBlockBaseSyntax)() Is Nothing AndAlso targetToken.GetInnermostDeclarationContext().IsKind(SyntaxKind.StructureBlock, SyntaxKind.ClassBlock) Then Dim variableDeclarator = targetToken.GetAncestor(Of VariableDeclaratorSyntax)() If variableDeclarator IsNot Nothing Then If variableDeclarator.Names.Count = 1 AndAlso variableDeclarator.Names.First().Identifier = targetToken Then Return s_keywords End If End If End If End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ko.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="ko" original="../EditorFeaturesWpfResources.resx"> <body> <trans-unit id="Building_Project"> <source>Building Project</source> <target state="translated">프로젝트 빌드 중</target> <note /> </trans-unit> <trans-unit id="Copying_selection_to_Interactive_Window"> <source>Copying selection to Interactive Window.</source> <target state="translated">선택 영역을 대화형 창으로 복사하는 중입니다.</target> <note /> </trans-unit> <trans-unit id="Error_performing_rename_0"> <source>Error performing rename: '{0}'</source> <target state="translated">이름 바꾸기 수행 중 오류 발생: '{0}'</target> <note /> </trans-unit> <trans-unit id="Executing_selection_in_Interactive_Window"> <source>Executing selection in Interactive Window.</source> <target state="translated">선택 영역을 대화형 창에서 실행하는 중입니다.</target> <note /> </trans-unit> <trans-unit id="Interactive_host_process_platform"> <source>Interactive host process platform</source> <target state="translated">대화형 호스트 프로세스 플랫폼</target> <note /> </trans-unit> <trans-unit id="Print_a_list_of_referenced_assemblies"> <source>Print a list of referenced assemblies.</source> <target state="translated">참조된 어셈블리의 목록을 인쇄합니다.</target> <note /> </trans-unit> <trans-unit id="Reset_the_execution_environment_to_the_initial_state_keep_history"> <source>Reset the execution environment to the initial state, keep history.</source> <target state="translated">실행 환경을 초기 상태로 다시 설정하고 기록을 보관합니다.</target> <note /> </trans-unit> <trans-unit id="Reset_to_a_clean_environment_only_mscorlib_referenced_do_not_run_initialization_script"> <source>Reset to a clean environment (only mscorlib referenced), do not run initialization script.</source> <target state="translated">정리된 환경(mscorlib만 참조됨)으로 다시 설정하고 초기화 스크립트를 실행하지 않습니다.</target> <note /> </trans-unit> <trans-unit id="Resetting_Interactive"> <source>Resetting Interactive</source> <target state="translated">대화형을 다시 설정하는 중</target> <note /> </trans-unit> <trans-unit id="Resetting_execution_engine"> <source>Resetting execution engine.</source> <target state="translated">실행 엔진을 다시 설정하는 중입니다.</target> <note /> </trans-unit> <trans-unit id="The_CurrentWindow_property_may_only_be_assigned_once"> <source>The CurrentWindow property may only be assigned once.</source> <target state="translated">CurrentWindow 속성은 한 번만 할당될 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="The_references_command_is_not_supported_in_this_Interactive_Window_implementation"> <source>The references command is not supported in this Interactive Window implementation.</source> <target state="translated">참조 명령은 이 대화형 창 구현에서 지원되지 않습니다.</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="ko" original="../EditorFeaturesWpfResources.resx"> <body> <trans-unit id="Building_Project"> <source>Building Project</source> <target state="translated">프로젝트 빌드 중</target> <note /> </trans-unit> <trans-unit id="Copying_selection_to_Interactive_Window"> <source>Copying selection to Interactive Window.</source> <target state="translated">선택 영역을 대화형 창으로 복사하는 중입니다.</target> <note /> </trans-unit> <trans-unit id="Error_performing_rename_0"> <source>Error performing rename: '{0}'</source> <target state="translated">이름 바꾸기 수행 중 오류 발생: '{0}'</target> <note /> </trans-unit> <trans-unit id="Executing_selection_in_Interactive_Window"> <source>Executing selection in Interactive Window.</source> <target state="translated">선택 영역을 대화형 창에서 실행하는 중입니다.</target> <note /> </trans-unit> <trans-unit id="Interactive_host_process_platform"> <source>Interactive host process platform</source> <target state="translated">대화형 호스트 프로세스 플랫폼</target> <note /> </trans-unit> <trans-unit id="Print_a_list_of_referenced_assemblies"> <source>Print a list of referenced assemblies.</source> <target state="translated">참조된 어셈블리의 목록을 인쇄합니다.</target> <note /> </trans-unit> <trans-unit id="Reset_the_execution_environment_to_the_initial_state_keep_history"> <source>Reset the execution environment to the initial state, keep history.</source> <target state="translated">실행 환경을 초기 상태로 다시 설정하고 기록을 보관합니다.</target> <note /> </trans-unit> <trans-unit id="Reset_to_a_clean_environment_only_mscorlib_referenced_do_not_run_initialization_script"> <source>Reset to a clean environment (only mscorlib referenced), do not run initialization script.</source> <target state="translated">정리된 환경(mscorlib만 참조됨)으로 다시 설정하고 초기화 스크립트를 실행하지 않습니다.</target> <note /> </trans-unit> <trans-unit id="Resetting_Interactive"> <source>Resetting Interactive</source> <target state="translated">대화형을 다시 설정하는 중</target> <note /> </trans-unit> <trans-unit id="Resetting_execution_engine"> <source>Resetting execution engine.</source> <target state="translated">실행 엔진을 다시 설정하는 중입니다.</target> <note /> </trans-unit> <trans-unit id="The_CurrentWindow_property_may_only_be_assigned_once"> <source>The CurrentWindow property may only be assigned once.</source> <target state="translated">CurrentWindow 속성은 한 번만 할당될 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="The_references_command_is_not_supported_in_this_Interactive_Window_implementation"> <source>The references command is not supported in this Interactive Window implementation.</source> <target state="translated">참조 명령은 이 대화형 창 구현에서 지원되지 않습니다.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValuesTestsBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.RemoveUnusedParametersAndValues; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnusedParametersAndValues { public abstract class RemoveUnusedValuesTestsBase : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { protected RemoveUnusedValuesTestsBase(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer(), new CSharpRemoveUnusedValuesCodeFixProvider()); private protected abstract OptionsCollection PreferNone { get; } private protected abstract OptionsCollection PreferDiscard { get; } private protected abstract OptionsCollection PreferUnusedLocal { get; } private protected OptionsCollection GetOptions(string optionName) { switch (optionName) { case nameof(PreferDiscard): return PreferDiscard; case nameof(PreferUnusedLocal): return PreferUnusedLocal; default: return PreferNone; } } private protected Task TestMissingInRegularAndScriptAsync(string initialMarkup, OptionsCollection options, ParseOptions parseOptions = null) => TestMissingInRegularAndScriptAsync(initialMarkup, new TestParameters(options: options, parseOptions: parseOptions)); private protected Task TestMissingInRegularAndScriptAsync(string initialMarkup, string optionName, ParseOptions parseOptions = null) => TestMissingInRegularAndScriptAsync(initialMarkup, GetOptions(optionName), parseOptions); protected Task TestInRegularAndScriptAsync(string initialMarkup, string expectedMarkup, string optionName, ParseOptions parseOptions = null) => TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: GetOptions(optionName), parseOptions: parseOptions); // Helpers to test all options - only used by tests which already have InlineData for custom input test code snippets. protected async Task TestInRegularAndScriptWithAllOptionsAsync(string initialMarkup, string expectedMarkup, ParseOptions parseOptions = null) { foreach (var options in new[] { PreferDiscard, PreferUnusedLocal }) { await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: options, parseOptions: parseOptions); } } protected async Task TestMissingInRegularAndScriptWithAllOptionsAsync(string initialMarkup, ParseOptions parseOptions = null) { foreach (var options in new[] { PreferDiscard, PreferUnusedLocal }) { await TestMissingInRegularAndScriptAsync(initialMarkup, new TestParameters(options: options, parseOptions: parseOptions)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.RemoveUnusedParametersAndValues; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnusedParametersAndValues { public abstract class RemoveUnusedValuesTestsBase : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { protected RemoveUnusedValuesTestsBase(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer(), new CSharpRemoveUnusedValuesCodeFixProvider()); private protected abstract OptionsCollection PreferNone { get; } private protected abstract OptionsCollection PreferDiscard { get; } private protected abstract OptionsCollection PreferUnusedLocal { get; } private protected OptionsCollection GetOptions(string optionName) { switch (optionName) { case nameof(PreferDiscard): return PreferDiscard; case nameof(PreferUnusedLocal): return PreferUnusedLocal; default: return PreferNone; } } private protected Task TestMissingInRegularAndScriptAsync(string initialMarkup, OptionsCollection options, ParseOptions parseOptions = null) => TestMissingInRegularAndScriptAsync(initialMarkup, new TestParameters(options: options, parseOptions: parseOptions)); private protected Task TestMissingInRegularAndScriptAsync(string initialMarkup, string optionName, ParseOptions parseOptions = null) => TestMissingInRegularAndScriptAsync(initialMarkup, GetOptions(optionName), parseOptions); protected Task TestInRegularAndScriptAsync(string initialMarkup, string expectedMarkup, string optionName, ParseOptions parseOptions = null) => TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: GetOptions(optionName), parseOptions: parseOptions); // Helpers to test all options - only used by tests which already have InlineData for custom input test code snippets. protected async Task TestInRegularAndScriptWithAllOptionsAsync(string initialMarkup, string expectedMarkup, ParseOptions parseOptions = null) { foreach (var options in new[] { PreferDiscard, PreferUnusedLocal }) { await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: options, parseOptions: parseOptions); } } protected async Task TestMissingInRegularAndScriptWithAllOptionsAsync(string initialMarkup, ParseOptions parseOptions = null) { foreach (var options in new[] { PreferDiscard, PreferUnusedLocal }) { await TestMissingInRegularAndScriptAsync(initialMarkup, new TestParameters(options: options, parseOptions: parseOptions)); } } } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/ContextQuery/ISyntaxContextService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery { internal interface ISyntaxContextService : ILanguageService { SyntaxContext CreateContext(Document document, SemanticModel semanticModel, int position, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery { internal interface ISyntaxContextService : ILanguageService { SyntaxContext CreateContext(Document document, SemanticModel semanticModel, int position, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./src/Compilers/Test/Resources/Core/SymbolsTests/V3/MTTestLib1.Dll
MZ@ !L!This program cannot be run in DOS mode. $PELK! n/ @@ @/O@`  H.textt  `.rsrc@@@.reloc `@BP/H" ( *( *s s s s *0~o +*0~o +*0~o +*0~o +*0( ( +*0 ( +*0( +*0 ( +*0 - (+ ++ +*0 *( *0, { o -(+ { o  +*J( s } *( *( *( *BSJB v4.0.30128l4#~#Strings #US #GUID L#BlobW %3  '    S S)xx = Um hI|)7:7 E7 O ] x   1 1?-1a:1G!bP X `    /( X5 vB Fc!Fh4!lP!Fqh!x!!!!!" " 9IQ$,4<$,4<YaiqKch)Xq hxDbL5L?L)...<@+@CCI#cci+{s7++ ++ + @+@`+`+++++PT_dssOTSY^l  uu  -n-<Module>mscorlibMicrosoft.VisualBasicMyApplicationMyMyComputerMyProjectMyWebServicesThreadSafeObjectProvider`1Class1Class2Class3Microsoft.VisualBasic.ApplicationServicesApplicationBase.ctorMicrosoft.VisualBasic.DevicesComputerSystemObject.cctorget_Computerm_ComputerObjectProviderget_Applicationm_AppObjectProviderUserget_Userm_UserObjectProviderget_WebServicesm_MyWebServicesObjectProviderApplicationWebServicesEqualsoGetHashCodeTypeGetTypeToStringCreate__Instance__TinstanceDispose__Instance__get_GetInstanceMicrosoft.VisualBasic.MyServices.InternalContextValue`1m_ContextGetInstanceSystem.ComponentModelEditorBrowsableAttributeEditorBrowsableStateSystem.CodeDom.CompilerGeneratedCodeAttributeSystem.DiagnosticsDebuggerHiddenAttributeMicrosoft.VisualBasic.CompilerServicesStandardModuleAttributeHideModuleNameAttributeSystem.ComponentModel.DesignHelpKeywordAttributeSystem.Runtime.CompilerServicesRuntimeHelpersGetObjectValueRuntimeTypeHandleGetTypeFromHandleActivatorCreateInstanceMyGroupCollectionAttributeget_Valueset_ValueSystem.Runtime.InteropServicesComVisibleAttributeCompilationRelaxationsAttributeRuntimeCompatibilityAttributeSystem.ReflectionAssemblyFileVersionAttributeMTTestLib1MTTestLib1.Dll E|?i&Oz\V4?_ :        0 ( !  MyTemplate10.0.0.0    My.Computer My.UserMy.ApplicationMy.WebServices=  a4System.Web.Services.Protocols.SoapHttpClientProtocolCreate__Instance__Dispose__Instance__    TWrapNonExceptionThrows 3.0.0.0D/^/ P/_CorDllMainmscoree.dll% @0HX@TT4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion3.0.0.0@InternalNameMTTestLib1.Dll(LegalCopyright HOriginalFilenameMTTestLib1.Dll4ProductVersion3.0.0.08Assembly Version3.0.0.0 p?
MZ@ !L!This program cannot be run in DOS mode. $PELK! n/ @@ @/O@`  H.textt  `.rsrc@@@.reloc `@BP/H" ( *( *s s s s *0~o +*0~o +*0~o +*0~o +*0( ( +*0 ( +*0( +*0 ( +*0 - (+ ++ +*0 *( *0, { o -(+ { o  +*J( s } *( *( *( *BSJB v4.0.30128l4#~#Strings #US #GUID L#BlobW %3  '    S S)xx = Um hI|)7:7 E7 O ] x   1 1?-1a:1G!bP X `    /( X5 vB Fc!Fh4!lP!Fqh!x!!!!!" " 9IQ$,4<$,4<YaiqKch)Xq hxDbL5L?L)...<@+@CCI#cci+{s7++ ++ + @+@`+`+++++PT_dssOTSY^l  uu  -n-<Module>mscorlibMicrosoft.VisualBasicMyApplicationMyMyComputerMyProjectMyWebServicesThreadSafeObjectProvider`1Class1Class2Class3Microsoft.VisualBasic.ApplicationServicesApplicationBase.ctorMicrosoft.VisualBasic.DevicesComputerSystemObject.cctorget_Computerm_ComputerObjectProviderget_Applicationm_AppObjectProviderUserget_Userm_UserObjectProviderget_WebServicesm_MyWebServicesObjectProviderApplicationWebServicesEqualsoGetHashCodeTypeGetTypeToStringCreate__Instance__TinstanceDispose__Instance__get_GetInstanceMicrosoft.VisualBasic.MyServices.InternalContextValue`1m_ContextGetInstanceSystem.ComponentModelEditorBrowsableAttributeEditorBrowsableStateSystem.CodeDom.CompilerGeneratedCodeAttributeSystem.DiagnosticsDebuggerHiddenAttributeMicrosoft.VisualBasic.CompilerServicesStandardModuleAttributeHideModuleNameAttributeSystem.ComponentModel.DesignHelpKeywordAttributeSystem.Runtime.CompilerServicesRuntimeHelpersGetObjectValueRuntimeTypeHandleGetTypeFromHandleActivatorCreateInstanceMyGroupCollectionAttributeget_Valueset_ValueSystem.Runtime.InteropServicesComVisibleAttributeCompilationRelaxationsAttributeRuntimeCompatibilityAttributeSystem.ReflectionAssemblyFileVersionAttributeMTTestLib1MTTestLib1.Dll E|?i&Oz\V4?_ :        0 ( !  MyTemplate10.0.0.0    My.Computer My.UserMy.ApplicationMy.WebServices=  a4System.Web.Services.Protocols.SoapHttpClientProtocolCreate__Instance__Dispose__Instance__    TWrapNonExceptionThrows 3.0.0.0D/^/ P/_CorDllMainmscoree.dll% @0HX@TT4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion3.0.0.0@InternalNameMTTestLib1.Dll(LegalCopyright HOriginalFilenameMTTestLib1.Dll4ProductVersion3.0.0.08Assembly Version3.0.0.0 p?
-1
dotnet/roslyn
56,491
Make method extensions
No need for these to be instance methods on ABstractSyntaxFacts
CyrusNajmabadi
"2021-09-17T20:59:25Z"
"2021-09-18T00:30:21Z"
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6
Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts
./docs/features/DefaultInterfaceImplementation.md
Default Interface Implementation ========================= The *Default Interface Implementation* feature enables a default implementation of an interface member to be provided as part of the interface declaration. Here is a link to the proposal https://github.com/dotnet/csharplang/blob/main/proposals/csharp-8.0/default-interface-methods.md. **What is supported:** - Supplying an implementation along with declaration of a regular interface method and recognizing that implementation as default implementation for the method when a type implements the interface. Here is an example: ``` public interface I1 { void M1() { System.Console.WriteLine("Default implementation of M1 is called!!!"); } } class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M1(); } } ``` - Re-abstraction of interface implementation in derived interfaces. Types implementing the derived interface are required to supply implementation even when a base interface provides an implementation. Here is an example: ``` public interface I1 { void M1() { } int P1 { get => throw null; set => throw null; } event System.Action E1 { add => throw null; remove => throw null; } } public interface I2 : I1 { abstract void I1.M1(); abstract int I1.P1 {get;set;} abstract event System.Action I1.E1; } class Test1 : I2 // This type must implement all members of I1 { } ``` In metadata, methods representing re-abstraction have all three flags `abstract`, `virtual`, `sealed` set and do not have `newslot` flag set. - Supplying an implementation along with declaration of a property or an indexer and recognizing that implementation as default implementation for them when a type implements the interface. - Supplying an implementation along with declaration of an event and recognizing that implementation as default implementation for the event when a type implements the interface. - Using **partial**, **public**, **internal**, **private**, **protected**, **static**, **virtual**, **sealed**, **abstract**, **extern** and **async** modifiers with interface methods. - Using **public**, **internal**, **private**, **protected**, **static**, **virtual**, **sealed**, **abstract** and **extern** modifiers with interface properties. - Using **public**, **internal**, **private**, **protected**, **virtual**, **sealed**, **abstract** and **extern** modifiers with interface indexers. - Using **internal**, **private**, **protected** modifiers with interface property/indexer accessors. - Using **public**, **internal**, **private**, **protected**, **static**, **virtual**, **sealed**, **abstract** and **extern** modifiers with interface events. - Declaring types within interfaces. - Implementing interface methods in derived interfaces by using explicit implementation syntax, accessibility is **protected**, allowed modifiers: **extern** and **async**. - Implementing interface properties and indexers in derived interfaces by using explicit implementation syntax, accessibility **protected**, allowed modifiers: **extern**. - Implementing interface events in derived interfaces by using explicit implementation syntax, accessibility **protected**, no allowed modifiers. - Declaring static fields, auto-properties and field-like events. - Declaring operators ```+ - ! ~ ++ -- true false * / % & | ^ << >> > < >= <=``` in interfaces. - Base access The following forms of base-access are added (https://github.com/dotnet/csharplang/blob/main/meetings/2018/LDM-2018-11-14.md) ``` base ( <type-syntax> ) . identifier base ( <type-syntax> ) [ argument-list ] ``` The type-syntax can refer to one of the base classes of the containing type, or one of the interfaces implemented or inherited by the containing type. When the type-syntax refers to a class, the member lookup rules, overload resolution rules and IL emit match the rules for the 7.3 supported forms of base-access. The difference is that the specified base class is used instead of the immediate base class. The most derived implementation found must be a member of that class. When the type-syntax refers to an interface: 1. The member lookup is performed in that interface, using the regular member lookup rules within interfaces, with an exception that members of System.Object do not participate in the lookup. 2. Regular overload resolution is performed for members returned by the lookup process, virtual or abstract members are not replaced with most derived implementations at this step (unlike the case when the type-syntax refers to a class). If result of overload resolution is a virtual or abstract method, it must have an implementation within the specified interface type, an error is reported otherwise. That implementation must be accessible at the call site. If result of overload resolution is a non-virtual method, the method must be declared in the specified interface type. 3. During IL emit a **call** (non-virtual call) instruction is used to invoke methods. If result of overload resolution on the previous step is a virtual or abstract method, the implementation of the method from the specified interface is used as the target for the instruction. Given the accessibility requirements for the most specific interface implementation, accessibility of implementations provided in derived interfaces is changed to **protected**. **Open issues and work items** are tracked in https://github.com/dotnet/roslyn/issues/17952. **Parts of ECMA-335 that become obsolete/inaccurate/incomplete** >I.8.5.3.2 Accessibility of members and nested types Members (other than nested types) defined by an interface shall be public. I.8.9.4 Interface type definition Similarly, an interface type definition shall not provide implementations for any methods on the values of its type. Interfaces can have static or virtual methods, but shall not have instance methods. However, since accessibility attributes are relative to the implementing type rather than the interface itself, all members of an interface shall have public accessibility, ... I.8.11.1 Method definitions All non-static methods of an interface definition are abstract. All non-static method definitions in interface definitions shall be virtual methods. II.10.4 Method implementat ion requirements II.12 Semantics of interfaces Interfaces can have static fields and methods, but they shall not have instance fields or methods. Interfaces can define virtual methods, but only if those methods are abstract (see Partition I and §II.15.4.2.4). II.12.2 Implement ing virtual methods on interfaces If the class defines any public virtual methods whose name and signature match a virtual method on the interface, then add these to the list for that method, in type declaration order (see above). If there are any public virtual methods available on this class (directly or inherited) having the same name and signature as the interface method, and whose generic type parameters do not exactly match any methods in the existing list for that interface method for this class or any class in its inheritance chain, then add them (in type declaration order) to the list for the corresponding methods on the interface. II.15.2 Static, instance, and virtual methods It follows that instance methods shall only be defined in classes or value types, but not in interfaces or outside of a type (i.e., globally). II.22.27 MethodImpl : 0x19 The method indexed by MethodBody shall be a member of Class or some base class of Class (MethodImpls do not allow compilers to ‘hook’ arbitrary method bodies) II.22.37 TypeDef : 0x02 All of the methods owned by an Interface (Flags.Interface = 1) shall be abstract (Flags.Abstract = 1) IV.6 Implementation-specific modifications to the system libraries Interfaces and virtual methods shall not be added to an existing interface.
Default Interface Implementation ========================= The *Default Interface Implementation* feature enables a default implementation of an interface member to be provided as part of the interface declaration. Here is a link to the proposal https://github.com/dotnet/csharplang/blob/main/proposals/csharp-8.0/default-interface-methods.md. **What is supported:** - Supplying an implementation along with declaration of a regular interface method and recognizing that implementation as default implementation for the method when a type implements the interface. Here is an example: ``` public interface I1 { void M1() { System.Console.WriteLine("Default implementation of M1 is called!!!"); } } class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M1(); } } ``` - Re-abstraction of interface implementation in derived interfaces. Types implementing the derived interface are required to supply implementation even when a base interface provides an implementation. Here is an example: ``` public interface I1 { void M1() { } int P1 { get => throw null; set => throw null; } event System.Action E1 { add => throw null; remove => throw null; } } public interface I2 : I1 { abstract void I1.M1(); abstract int I1.P1 {get;set;} abstract event System.Action I1.E1; } class Test1 : I2 // This type must implement all members of I1 { } ``` In metadata, methods representing re-abstraction have all three flags `abstract`, `virtual`, `sealed` set and do not have `newslot` flag set. - Supplying an implementation along with declaration of a property or an indexer and recognizing that implementation as default implementation for them when a type implements the interface. - Supplying an implementation along with declaration of an event and recognizing that implementation as default implementation for the event when a type implements the interface. - Using **partial**, **public**, **internal**, **private**, **protected**, **static**, **virtual**, **sealed**, **abstract**, **extern** and **async** modifiers with interface methods. - Using **public**, **internal**, **private**, **protected**, **static**, **virtual**, **sealed**, **abstract** and **extern** modifiers with interface properties. - Using **public**, **internal**, **private**, **protected**, **virtual**, **sealed**, **abstract** and **extern** modifiers with interface indexers. - Using **internal**, **private**, **protected** modifiers with interface property/indexer accessors. - Using **public**, **internal**, **private**, **protected**, **static**, **virtual**, **sealed**, **abstract** and **extern** modifiers with interface events. - Declaring types within interfaces. - Implementing interface methods in derived interfaces by using explicit implementation syntax, accessibility is **protected**, allowed modifiers: **extern** and **async**. - Implementing interface properties and indexers in derived interfaces by using explicit implementation syntax, accessibility **protected**, allowed modifiers: **extern**. - Implementing interface events in derived interfaces by using explicit implementation syntax, accessibility **protected**, no allowed modifiers. - Declaring static fields, auto-properties and field-like events. - Declaring operators ```+ - ! ~ ++ -- true false * / % & | ^ << >> > < >= <=``` in interfaces. - Base access The following forms of base-access are added (https://github.com/dotnet/csharplang/blob/main/meetings/2018/LDM-2018-11-14.md) ``` base ( <type-syntax> ) . identifier base ( <type-syntax> ) [ argument-list ] ``` The type-syntax can refer to one of the base classes of the containing type, or one of the interfaces implemented or inherited by the containing type. When the type-syntax refers to a class, the member lookup rules, overload resolution rules and IL emit match the rules for the 7.3 supported forms of base-access. The difference is that the specified base class is used instead of the immediate base class. The most derived implementation found must be a member of that class. When the type-syntax refers to an interface: 1. The member lookup is performed in that interface, using the regular member lookup rules within interfaces, with an exception that members of System.Object do not participate in the lookup. 2. Regular overload resolution is performed for members returned by the lookup process, virtual or abstract members are not replaced with most derived implementations at this step (unlike the case when the type-syntax refers to a class). If result of overload resolution is a virtual or abstract method, it must have an implementation within the specified interface type, an error is reported otherwise. That implementation must be accessible at the call site. If result of overload resolution is a non-virtual method, the method must be declared in the specified interface type. 3. During IL emit a **call** (non-virtual call) instruction is used to invoke methods. If result of overload resolution on the previous step is a virtual or abstract method, the implementation of the method from the specified interface is used as the target for the instruction. Given the accessibility requirements for the most specific interface implementation, accessibility of implementations provided in derived interfaces is changed to **protected**. **Open issues and work items** are tracked in https://github.com/dotnet/roslyn/issues/17952. **Parts of ECMA-335 that become obsolete/inaccurate/incomplete** >I.8.5.3.2 Accessibility of members and nested types Members (other than nested types) defined by an interface shall be public. I.8.9.4 Interface type definition Similarly, an interface type definition shall not provide implementations for any methods on the values of its type. Interfaces can have static or virtual methods, but shall not have instance methods. However, since accessibility attributes are relative to the implementing type rather than the interface itself, all members of an interface shall have public accessibility, ... I.8.11.1 Method definitions All non-static methods of an interface definition are abstract. All non-static method definitions in interface definitions shall be virtual methods. II.10.4 Method implementat ion requirements II.12 Semantics of interfaces Interfaces can have static fields and methods, but they shall not have instance fields or methods. Interfaces can define virtual methods, but only if those methods are abstract (see Partition I and §II.15.4.2.4). II.12.2 Implement ing virtual methods on interfaces If the class defines any public virtual methods whose name and signature match a virtual method on the interface, then add these to the list for that method, in type declaration order (see above). If there are any public virtual methods available on this class (directly or inherited) having the same name and signature as the interface method, and whose generic type parameters do not exactly match any methods in the existing list for that interface method for this class or any class in its inheritance chain, then add them (in type declaration order) to the list for the corresponding methods on the interface. II.15.2 Static, instance, and virtual methods It follows that instance methods shall only be defined in classes or value types, but not in interfaces or outside of a type (i.e., globally). II.22.27 MethodImpl : 0x19 The method indexed by MethodBody shall be a member of Class or some base class of Class (MethodImpls do not allow compilers to ‘hook’ arbitrary method bodies) II.22.37 TypeDef : 0x02 All of the methods owned by an Interface (Flags.Interface = 1) shall be abstract (Flags.Abstract = 1) IV.6 Implementation-specific modifications to the system libraries Interfaces and virtual methods shall not be added to an existing interface.
-1